@@ -20,7 +20,8 @@ use crate::Displayable;
2020
2121/// Create a [`Display`] instance for displaying a byte size.
2222///
23- /// See [`Display`] for examples.
23+ /// See [`Display`] for examples. Use [`Display::new`] when the byte count is already represented
24+ /// as an `f64`.
2425pub fn display ( size : impl Displayable ) -> Display {
2526 Display :: new ( size. canonicalize ( ) )
2627}
@@ -36,8 +37,8 @@ impl<T: Displayable> BSize<T> {
3637
3738/// Display wrapper for formatting byte sizes as human-readable strings.
3839///
39- /// You may create this wrapper with [`display`] or [`BSize::display`], then pass custom
40- /// [`DisplayOptions`] with [`Display::options`].
40+ /// You may create this wrapper with [`Display::new`], [` display`], or [`BSize::display`], then
41+ /// pass custom [`DisplayOptions`] with [`Display::options`].
4142///
4243/// # Examples
4344///
@@ -68,6 +69,15 @@ impl<T: Displayable> BSize<T> {
6869/// assert_eq!("1.5 KiB", bsize::display(1536u64).to_string());
6970/// ```
7071///
72+ /// Use [`Display::new`] when the byte count is already represented as an `f64`.
73+ ///
74+ /// ```
75+ /// use bsize::Display;
76+ ///
77+ /// assert_eq!("1.5 KiB", Display::new(1536.5).to_string());
78+ /// assert_eq!("1.54 kB", format!("{:.2}", Display::new(1536.5).decimal()));
79+ /// ```
80+ ///
7181/// Use standard formatter precision to control the number of fractional digits.
7282///
7383/// ```
@@ -311,7 +321,24 @@ impl Display {
311321 self
312322 }
313323
314- fn new ( size : f64 ) -> Self {
324+ /// Create a [`Display`] instance from a byte count.
325+ ///
326+ /// This constructor is useful when the byte count is already represented as an `f64`. For
327+ /// supported integer byte counts, use [`display`] or [`BSize::display`].
328+ ///
329+ /// # Examples
330+ ///
331+ /// ```
332+ /// use bsize::Display;
333+ ///
334+ /// assert_eq!("2.5 KiB", Display::new(2560.0).to_string());
335+ /// ```
336+ ///
337+ /// # Panics
338+ ///
339+ /// Panics if the `size` is not finite or is negative.
340+ pub fn new ( size : f64 ) -> Self {
341+ assert ! ( size. is_finite( ) && size >= 0.0 ) ;
315342 let options = DisplayOptions :: BINARY ;
316343 Self { size, options }
317344 }
@@ -505,6 +532,24 @@ mod tests {
505532 assert_snapshot ! ( format!( "{:.2}" , Display :: new( 2500.5 ) . decimal( ) ) , @"2.50 kB" ) ;
506533 }
507534
535+ #[ test]
536+ #[ should_panic]
537+ fn test_new_rejects_nan_size ( ) {
538+ Display :: new ( f64:: NAN ) ;
539+ }
540+
541+ #[ test]
542+ #[ should_panic]
543+ fn test_new_rejects_infinite_size ( ) {
544+ Display :: new ( f64:: INFINITY ) ;
545+ }
546+
547+ #[ test]
548+ #[ should_panic]
549+ fn test_new_rejects_negative_size ( ) {
550+ Display :: new ( -1.0 ) ;
551+ }
552+
508553 #[ test]
509554 fn test_formats_default_binary ( ) {
510555 assert_snapshot ! ( display( 999u64 ) , @"999 B" ) ;
0 commit comments