Skip to main content

kernel/records/
byte_format.rs

1//! Human-readable byte-size formatting.
2
3const GB: i64 = 1 << 30;
4const MB: i64 = 1 << 20;
5const KB: i64 = 1 << 10;
6
7/// Format a byte count as a short human string (`B`/`KB`/`MB`/`GB`). Gigabytes
8/// get one decimal place, with a trailing `.0` trimmed.
9pub fn format_bytes(bytes: i64) -> String {
10    if bytes >= GB {
11        let value = bytes as f64 / GB as f64;
12        let formatted = format!("{value:.1}");
13        let trimmed = formatted.strip_suffix(".0").unwrap_or(&formatted);
14        format!("{trimmed} GB")
15    } else if bytes >= MB {
16        format!("{} MB", bytes / MB)
17    } else if bytes >= KB {
18        format!("{} KB", bytes / KB)
19    } else {
20        format!("{bytes} B")
21    }
22}