Skip to content

Commit

Permalink
fix: format with IEC (binary) by default
Browse files Browse the repository at this point in the history
  • Loading branch information
robjtede committed Feb 10, 2025
1 parent 8e7c57d commit d9eef51
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 13 deletions.
4 changes: 2 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

## Unreleased

- Use SI format by default with `Display`.
- Use "KiB" for SI unit.
- Use IEC (binary) format by default with `Display`.
- Use "kB" for SI unit.
- Implement `Sub<ByteSize>` for `ByteSize`.
- Implement `Sub<impl Into<u64>>` for `ByteSize`.
- Implement `SubAssign<ByteSize>` for `ByteSize`.
Expand Down
20 changes: 11 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,12 +179,15 @@ impl ByteSize {
pub fn to_string(bytes: u64, si_prefix: bool) -> String {
let unit = if si_prefix { KB } else { KIB };
let unit_base = if si_prefix { LN_KB } else { LN_KIB };
let unit_prefix = if si_prefix {
UNITS_SI.as_bytes()
} else {
UNITS.as_bytes()

let unit_prefix = match si_prefix {
true => UNITS_SI.as_bytes(),
false => UNITS.as_bytes(),
};
let unit_suffix = match si_prefix {
true => "B",
false => "iB",
};
let unit_suffix = if si_prefix { "B" } else { "iB" };

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

impl Display for ByteSize {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad(&to_string(self.0, true))
f.pad(&to_string(self.0, false))
}
}

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

assert_to_string("1.0 MiB", ByteSize::mib(1), false);
assert_to_string("1048.6 kB", ByteSize::mib(1), true);
assert_to_string("1024.0 KiB", ByteSize::mib(1), false);
assert_to_string("1.0 MB", ByteSize::mib(1), true);

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

Expand Down
3 changes: 1 addition & 2 deletions src/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,9 @@ mod tests {
}

#[test]

fn test_serde_json() {
let json = serde_json::to_string(&ByteSize::mib(1)).unwrap();
assert_eq!(json, "\"1.0 MiB\"");
assert_eq!(json, "\"1024.0 KiB\"");

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

0 comments on commit d9eef51

Please sign in to comment.