Skip to main content

kernel/records/
byte_format.rs

1//! Human-readable byte-size formatting.
2//!
3//! Sizes are decimal (`4.9 GB` is 4.9e9 bytes, not 4.9 GiB), which is how
4//! the hubs and a model's own page state them; memory is binary and keeps
5//! its own `GiB` figures through the constants below.
6
7const GB: i64 = 1_000_000_000;
8const MB: i64 = 1_000_000;
9const KB: i64 = 1_000;
10
11/// Bytes in one mebibyte, for the memory figures budgeted in them.
12pub const BYTES_PER_MIB: i64 = 1 << 20;
13/// Bytes in one gibibyte, for memory figures.
14pub const BYTES_PER_GIB: i64 = 1 << 30;
15
16/// `value` with one decimal place, a trailing `.0` trimmed: `4.7`, `64`.
17pub fn one_decimal(value: f64) -> String {
18    let formatted = format!("{value:.1}");
19    formatted
20        .strip_suffix(".0")
21        .unwrap_or(&formatted)
22        .to_owned()
23}
24
25/// Format a byte count as a short human string (`B`/`KB`/`MB`/`GB`). Gigabytes
26/// get one decimal place, with a trailing `.0` trimmed.
27pub fn format_bytes(bytes: i64) -> String {
28    if bytes >= GB {
29        format!("{} GB", one_decimal(bytes as f64 / GB as f64))
30    } else if bytes >= MB {
31        format!("{} MB", bytes / MB)
32    } else if bytes >= KB {
33        format!("{} KB", bytes / KB)
34    } else {
35        format!("{bytes} B")
36    }
37}