Skip to content

Commit

Permalink
feat!: switch display to binary prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
MilesCranmer committed Apr 21, 2024
1 parent 2c441cf commit 8fd45f1
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 12 deletions.
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ fn do_inspection(
.filter_map(|x| x.ok())
.filter_map(|x| x.metadata().ok())
.map(|x| x.len())
.sum::<u64>(),
.sum(),
)
)?;

Expand Down
41 changes: 31 additions & 10 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,16 +136,37 @@ pub fn rename_grave(grave: impl AsRef<Path>) -> PathBuf {
.expect("Failed to rename duplicate file or directory")
}

const UNITS: [(&str, u64); 4] = [
("KiB", 1_u64 << 10),
("MiB", 1_u64 << 20),
("GiB", 1_u64 << 30),
("TiB", 1_u64 << 40),
];

pub fn humanize_bytes(bytes: u64) -> String {
let values = ["bytes", "KB", "MB", "GB", "TB"];
let pair = values
.iter()
.enumerate()
.take_while(|x| bytes as usize / (1000_usize).pow(x.0 as u32) > 10)
.last();
if let Some((i, unit)) = pair {
format!("{} {}", bytes as usize / (1000_usize).pow(i as u32), unit)
} else {
format!("{} {}", bytes, values[0])
for (unit, size) in UNITS.iter().rev() {
if bytes >= *size {
return format!("{:.1} {}", bytes as f64 / *size as f64, unit);
}
}
format!("{} B", bytes)
}


#[cfg(test)]
mod test_humanize_bytes {
use super::*;
use rstest::rstest;

#[rstest]
fn test() {
assert_eq!(humanize_bytes(0), "0 B");
assert_eq!(humanize_bytes(1), "1 B");
assert_eq!(humanize_bytes(1024), "1.0 KiB");
assert_eq!(humanize_bytes(1024 * 1024), "1.0 MiB");
assert_eq!(humanize_bytes(1024 * 1024 * 1024), "1.0 GiB");
assert_eq!(humanize_bytes(1024 * 1024 * 1024 * 1024), "1.0 TiB");

assert_eq!(humanize_bytes(1024 * 1024 + 1024 * 512), "1.5 MiB");
}
}
2 changes: 1 addition & 1 deletion tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ fn test_bury_unbury(#[values(false, true)] decompose: bool, #[values(false, true
.unwrap();
if inspect {
let log_s = String::from_utf8(log).unwrap();
assert!(log_s.contains("100 bytes"));
assert!(log_s.contains("100 B"));
} else {
assert!(log.is_empty())
}
Expand Down

0 comments on commit 8fd45f1

Please sign in to comment.