diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f61063..a58e85a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Add support for precision in `Display` implementations. + ## v2.0.0 - Add support for `no_std` targets. diff --git a/ensure-no-std/Cargo.lock b/ensure-no-std/Cargo.lock index 76d3ca0..d43290f 100644 --- a/ensure-no-std/Cargo.lock +++ b/ensure-no-std/Cargo.lock @@ -4,7 +4,7 @@ version = 4 [[package]] name = "bytesize" -version = "1.3.0" +version = "2.0.0" [[package]] name = "ensure-no-std" diff --git a/src/display.rs b/src/display.rs index e140db7..a17e08d 100644 --- a/src/display.rs +++ b/src/display.rs @@ -128,6 +128,7 @@ impl fmt::Display for Display { let unit_prefixes = self.format.unit_prefixes(); let unit_separator = self.format.unit_separator(); let unit_suffix = self.format.unit_suffix(); + let precision = f.precision().unwrap_or(1); if bytes < unit { write!(f, "{bytes}{unit_separator}B")?; @@ -144,7 +145,7 @@ impl fmt::Display for Display { write!( f, - "{:.1}{unit_separator}{unit_prefix}{unit_suffix}", + "{:.precision$}{unit_separator}{unit_prefix}{unit_suffix}", (size / unit.pow(exp as u32) as f64), )?; } @@ -185,7 +186,7 @@ fn ideal_unit_std(size: f64, unit_base: f64) -> usize { #[cfg(test)] mod tests { - use alloc::string::ToString as _; + use alloc::{format, string::ToString as _}; use super::*; @@ -293,4 +294,12 @@ mod tests { assert_to_string("540.9 PiB", ByteSize::pb(609), Format::Iec); assert_to_string("609.0 PB", ByteSize::pb(609), Format::Si); } + + #[test] + fn precision() { + let size = ByteSize::mib(1908); + assert_eq!("1.9 GiB".to_string(), format!("{}", size)); + assert_eq!("2 GiB".to_string(), format!("{:.0}", size)); + assert_eq!("1.86328 GiB".to_string(), format!("{:.5}", size)); + } } diff --git a/src/lib.rs b/src/lib.rs index b766a57..d82d1ce 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -236,9 +236,9 @@ impl fmt::Display for ByteSize { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let display = self.display(); - if f.width().is_none() && f.precision().is_none() { + if f.width().is_none() { // allocation-free fast path for when no formatting options are specified - write!(f, "{display}") + display.fmt(f) } else { f.pad(&display.to_string()) }