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/// Bytes in one mebibyte, for footprints recorded in MiB.
8pub const BYTES_PER_MIB: i64 = MB;
9/// Bytes in one gibibyte, for memory figures.
10pub const BYTES_PER_GIB: i64 = GB;
11
12/// `value` with one decimal place, a trailing `.0` trimmed: `4.7`, `64`.
13pub fn one_decimal(value: f64) -> String {
14    let formatted = format!("{value:.1}");
15    formatted
16        .strip_suffix(".0")
17        .unwrap_or(&formatted)
18        .to_owned()
19}
20
21/// Format a byte count as a short human string (`B`/`KB`/`MB`/`GB`). Gigabytes
22/// get one decimal place, with a trailing `.0` trimmed.
23pub fn format_bytes(bytes: i64) -> String {
24    if bytes >= GB {
25        format!("{} GB", one_decimal(bytes as f64 / GB as f64))
26    } else if bytes >= MB {
27        format!("{} MB", bytes / MB)
28    } else if bytes >= KB {
29        format!("{} KB", bytes / KB)
30    } else {
31        format!("{bytes} B")
32    }
33}