Skip to content

Commit

Permalink
feat: control precision via standard format options (#84)
Browse files Browse the repository at this point in the history
Co-authored-by: Rob Ede <[email protected]>
  • Loading branch information
weihanglo and robjtede authored Feb 28, 2025
1 parent 9aa5e11 commit 0a54210
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 5 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- Add support for precision in `Display` implementations.

## v2.0.0

- Add support for `no_std` targets.
Expand Down
2 changes: 1 addition & 1 deletion ensure-no-std/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 11 additions & 2 deletions src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")?;
Expand All @@ -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),
)?;
}
Expand Down Expand Up @@ -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::*;

Expand Down Expand Up @@ -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));
}
}
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand Down

0 comments on commit 0a54210

Please sign in to comment.