Skip to content

Commit 0a54210

Browse files
weihanglorobjtede
andauthored
feat: control precision via standard format options (#84)
Co-authored-by: Rob Ede <[email protected]>
1 parent 9aa5e11 commit 0a54210

File tree

4 files changed

+16
-5
lines changed

4 files changed

+16
-5
lines changed

CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
## Unreleased
44

5+
- Add support for precision in `Display` implementations.
6+
57
## v2.0.0
68

79
- Add support for `no_std` targets.

ensure-no-std/Cargo.lock

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/display.rs

+11-2
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ impl fmt::Display for Display {
128128
let unit_prefixes = self.format.unit_prefixes();
129129
let unit_separator = self.format.unit_separator();
130130
let unit_suffix = self.format.unit_suffix();
131+
let precision = f.precision().unwrap_or(1);
131132

132133
if bytes < unit {
133134
write!(f, "{bytes}{unit_separator}B")?;
@@ -144,7 +145,7 @@ impl fmt::Display for Display {
144145

145146
write!(
146147
f,
147-
"{:.1}{unit_separator}{unit_prefix}{unit_suffix}",
148+
"{:.precision$}{unit_separator}{unit_prefix}{unit_suffix}",
148149
(size / unit.pow(exp as u32) as f64),
149150
)?;
150151
}
@@ -185,7 +186,7 @@ fn ideal_unit_std(size: f64, unit_base: f64) -> usize {
185186

186187
#[cfg(test)]
187188
mod tests {
188-
use alloc::string::ToString as _;
189+
use alloc::{format, string::ToString as _};
189190

190191
use super::*;
191192

@@ -293,4 +294,12 @@ mod tests {
293294
assert_to_string("540.9 PiB", ByteSize::pb(609), Format::Iec);
294295
assert_to_string("609.0 PB", ByteSize::pb(609), Format::Si);
295296
}
297+
298+
#[test]
299+
fn precision() {
300+
let size = ByteSize::mib(1908);
301+
assert_eq!("1.9 GiB".to_string(), format!("{}", size));
302+
assert_eq!("2 GiB".to_string(), format!("{:.0}", size));
303+
assert_eq!("1.86328 GiB".to_string(), format!("{:.5}", size));
304+
}
296305
}

src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -236,9 +236,9 @@ impl fmt::Display for ByteSize {
236236
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237237
let display = self.display();
238238

239-
if f.width().is_none() && f.precision().is_none() {
239+
if f.width().is_none() {
240240
// allocation-free fast path for when no formatting options are specified
241-
write!(f, "{display}")
241+
display.fmt(f)
242242
} else {
243243
f.pad(&display.to_string())
244244
}

0 commit comments

Comments
 (0)