Skip to content

Commit d9eef51

Browse files
committed
fix: format with IEC (binary) by default
1 parent 8e7c57d commit d9eef51

File tree

3 files changed

+14
-13
lines changed

3 files changed

+14
-13
lines changed

CHANGELOG.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22

33
## Unreleased
44

5-
- Use SI format by default with `Display`.
6-
- Use "KiB" for SI unit.
5+
- Use IEC (binary) format by default with `Display`.
6+
- Use "kB" for SI unit.
77
- Implement `Sub<ByteSize>` for `ByteSize`.
88
- Implement `Sub<impl Into<u64>>` for `ByteSize`.
99
- Implement `SubAssign<ByteSize>` for `ByteSize`.

src/lib.rs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -179,12 +179,15 @@ impl ByteSize {
179179
pub fn to_string(bytes: u64, si_prefix: bool) -> String {
180180
let unit = if si_prefix { KB } else { KIB };
181181
let unit_base = if si_prefix { LN_KB } else { LN_KIB };
182-
let unit_prefix = if si_prefix {
183-
UNITS_SI.as_bytes()
184-
} else {
185-
UNITS.as_bytes()
182+
183+
let unit_prefix = match si_prefix {
184+
true => UNITS_SI.as_bytes(),
185+
false => UNITS.as_bytes(),
186+
};
187+
let unit_suffix = match si_prefix {
188+
true => "B",
189+
false => "iB",
186190
};
187-
let unit_suffix = if si_prefix { "B" } else { "iB" };
188191

189192
if bytes < unit {
190193
format!("{} B", bytes)
@@ -206,7 +209,7 @@ pub fn to_string(bytes: u64, si_prefix: bool) -> String {
206209

207210
impl Display for ByteSize {
208211
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
209-
f.pad(&to_string(self.0, true))
212+
f.pad(&to_string(self.0, false))
210213
}
211214
}
212215

@@ -440,10 +443,9 @@ mod tests {
440443
assert_to_string("293.9 KiB", ByteSize::kb(301), false);
441444
assert_to_string("301.0 kB", ByteSize::kb(301), true);
442445

443-
assert_to_string("1.0 MiB", ByteSize::mib(1), false);
444-
assert_to_string("1048.6 kB", ByteSize::mib(1), true);
446+
assert_to_string("1024.0 KiB", ByteSize::mib(1), false);
447+
assert_to_string("1.0 MB", ByteSize::mib(1), true);
445448

446-
// a bug case: https://github.com/flang-project/bytesize/issues/8
447449
assert_to_string("1.9 GiB", ByteSize::mib(1907), false);
448450
assert_to_string("2.0 GB", ByteSize::mib(1908), true);
449451

src/serde.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,9 @@ mod tests {
9292
}
9393

9494
#[test]
95-
9695
fn test_serde_json() {
9796
let json = serde_json::to_string(&ByteSize::mib(1)).unwrap();
98-
assert_eq!(json, "\"1.0 MiB\"");
97+
assert_eq!(json, "\"1024.0 KiB\"");
9998

10099
let deserialized = serde_json::from_str::<ByteSize>(&json).unwrap();
101100
assert_eq!(deserialized.0, 1048576);

0 commit comments

Comments
 (0)