Skip to main content

human_memsize/
lib.rs

1#[must_use] pub fn human_size(size: u64) -> String {
2    const KIB: f64 = 1024.0;
3    const MIB: f64 = KIB * 1024.0;
4    const GIB: f64 = MIB * 1024.0;
5    const TIB: f64 = GIB * 1024.0;
6
7    match size {
8        0..=0x7FF => format!("{size} B"), // Up to 2047 bytes
9        0x400..=0xFFFFF => format!("{} KiB", size / 1024),
10        0x100000..=0x3FFFFFFF => format_number(size as f64 / MIB, "MiB"),
11        0x40000000..=0xFFFFFFFFFF => format_number(size as f64 / GIB, "GiB"),
12        _ => format_number(size as f64 / TIB, "TiB"),
13    }
14}
15
16fn format_number(value: f64, unit: &str) -> String {
17    // Safe to compare fract() directly to 0.0 here because `value`
18    // is always computed by dividing an integer by an exact power of two (KiB, MiB, GiB, TiB).
19    if value.fract() == 0.0 {
20        format!("{value:.0} {unit}")
21    } else {
22        format!("{value:.1} {unit}")
23    }
24}