human-memsize 0.1.0

Human-readable formatting for memory sizes
Documentation
#[must_use] pub fn human_size(size: u64) -> String {
    const KIB: f64 = 1024.0;
    const MIB: f64 = KIB * 1024.0;
    const GIB: f64 = MIB * 1024.0;
    const TIB: f64 = GIB * 1024.0;

    match size {
        0..=0x7FF => format!("{size} B"), // Up to 2047 bytes
        0x400..=0xFFFFF => format!("{} KiB", size / 1024),
        0x100000..=0x3FFFFFFF => format_number(size as f64 / MIB, "MiB"),
        0x40000000..=0xFFFFFFFFFF => format_number(size as f64 / GIB, "GiB"),
        _ => format_number(size as f64 / TIB, "TiB"),
    }
}

fn format_number(value: f64, unit: &str) -> String {
    // Safe to compare fract() directly to 0.0 here because `value`
    // is always computed by dividing an integer by an exact power of two (KiB, MiB, GiB, TiB).
    if value.fract() == 0.0 {
        format!("{value:.0} {unit}")
    } else {
        format!("{value:.1} {unit}")
    }
}