procutils-common 0.2.0

Shared utilities for procutils tools (utmp, signal, procmatch, fmt, uid)
Documentation
//! Human-readable size formatters.
//!
//! Used across the workspace for size columns in `top`, `hugetop`,
//! `pmap`, and friends. Two entry points:
//!
//! - [`format_bytes`] takes raw bytes and produces `B`/`K`/`M`/`G`.
//! - [`format_kb`] takes KiB (the unit `/proc` files report in) and
//!   produces lowercase `k`/`m`/`g`/`t` suffixes, matching the
//!   classic procps style for memory columns.
//!
//! Both use binary multiples (1024-based) and fixed-precision
//! formatting; neither rounds down to an empty string.

/// Format a size in bytes as a human-readable string (`B`, `K`, `M`,
/// `G`). Uses binary multiples (1024-based). Two-decimal precision
/// for `K`/`M`/`G`; integer for raw bytes.
pub fn format_bytes(bytes: u64) -> String {
    if bytes >= 1_073_741_824 {
        format!("{:.2}G", bytes as f64 / 1_073_741_824.0)
    } else if bytes >= 1_048_576 {
        format!("{:.2}M", bytes as f64 / 1_048_576.0)
    } else if bytes >= 1024 {
        format!("{:.2}K", bytes as f64 / 1024.0)
    } else {
        format!("{bytes}B")
    }
}

/// Format a size in KiB as a human-readable string (`m`, `g`, `t`).
///
/// Inputs below 10 MiB render as the raw KiB integer; above that, scales
/// to `m`/`g`/`t` with one decimal place. Lowercase suffixes match the
/// procps-ng convention used in `top`'s memory columns.
pub fn format_kb(kb: u64) -> String {
    if kb >= 10_485_760 {
        format!("{:.1}t", kb as f64 / 1_073_741_824.0)
    } else if kb >= 1_048_576 {
        format!("{:.1}g", kb as f64 / 1_048_576.0)
    } else if kb >= 10_240 {
        format!("{:.1}m", kb as f64 / 1024.0)
    } else {
        format!("{kb}")
    }
}