procutils_common/fmt.rs
1//! Human-readable size formatters.
2//!
3//! Used across the workspace for size columns in `top`, `hugetop`,
4//! `pmap`, and friends. Two entry points:
5//!
6//! - [`format_bytes`] takes raw bytes and produces `B`/`K`/`M`/`G`.
7//! - [`format_kb`] takes KiB (the unit `/proc` files report in) and
8//! produces lowercase `k`/`m`/`g`/`t` suffixes, matching the
9//! classic procps style for memory columns.
10//!
11//! Both use binary multiples (1024-based) and fixed-precision
12//! formatting; neither rounds down to an empty string.
13
14/// Format a size in bytes as a human-readable string (`B`, `K`, `M`,
15/// `G`). Uses binary multiples (1024-based). Two-decimal precision
16/// for `K`/`M`/`G`; integer for raw bytes.
17pub fn format_bytes(bytes: u64) -> String {
18 if bytes >= 1_073_741_824 {
19 format!("{:.2}G", bytes as f64 / 1_073_741_824.0)
20 } else if bytes >= 1_048_576 {
21 format!("{:.2}M", bytes as f64 / 1_048_576.0)
22 } else if bytes >= 1024 {
23 format!("{:.2}K", bytes as f64 / 1024.0)
24 } else {
25 format!("{bytes}B")
26 }
27}
28
29/// Format a size in KiB as a human-readable string (`m`, `g`, `t`).
30///
31/// Inputs below 10 MiB render as the raw KiB integer; above that, scales
32/// to `m`/`g`/`t` with one decimal place. Lowercase suffixes match the
33/// procps-ng convention used in `top`'s memory columns.
34pub fn format_kb(kb: u64) -> String {
35 if kb >= 10_485_760 {
36 format!("{:.1}t", kb as f64 / 1_073_741_824.0)
37 } else if kb >= 1_048_576 {
38 format!("{:.1}g", kb as f64 / 1_048_576.0)
39 } else if kb >= 10_240 {
40 format!("{:.1}m", kb as f64 / 1024.0)
41 } else {
42 format!("{kb}")
43 }
44}