Skip to main content

heft_format/
display.rs

1/// Format a byte count as a human-readable string (B, KiB, MiB, GiB, TiB).
2pub fn format_size(bytes: u64) -> String {
3    const KIB: u64 = 1024;
4    const MIB: u64 = 1024 * KIB;
5    const GIB: u64 = 1024 * MIB;
6    const TIB: u64 = 1024 * GIB;
7
8    if bytes >= TIB {
9        format!("{:.1} TiB", bytes as f64 / TIB as f64)
10    } else if bytes >= GIB {
11        format!("{:.1} GiB", bytes as f64 / GIB as f64)
12    } else if bytes >= MIB {
13        format!("{:.1} MiB", bytes as f64 / MIB as f64)
14    } else if bytes >= KIB {
15        format!("{:.1} KiB", bytes as f64 / KIB as f64)
16    } else {
17        format!("{bytes} B")
18    }
19}
20
21/// Format an integer with comma separators (e.g. 1,234,567).
22pub fn format_count(n: u64) -> String {
23    if n < 1000 {
24        return n.to_string();
25    }
26    let s = n.to_string();
27    let mut result = String::new();
28    for (i, ch) in s.chars().rev().enumerate() {
29        if i > 0 && i % 3 == 0 {
30            result.push(',');
31        }
32        result.push(ch);
33    }
34    result.chars().rev().collect()
35}