Skip to main content

rigtop_core/
format.rs

1//! Compact human-readable formatting for narrow terminal cells.
2
3use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
4
5/// Formats a byte count with a binary unit, e.g. `"1.5G"`, `"512K"`, `"0B"`.
6///
7/// Uses at most 5 characters so that columns stay aligned.
8pub fn bytes(value: u64) -> String {
9    const UNITS: &[&str] = &["B", "K", "M", "G", "T", "P"];
10    let mut v = value as f64;
11    let mut unit = 0;
12    while v >= 1024.0 && unit < UNITS.len() - 1 {
13        v /= 1024.0;
14        unit += 1;
15    }
16    if unit == 0 {
17        format!("{value}B")
18    } else if v < 10.0 {
19        format!("{v:.1}{}", UNITS[unit])
20    } else {
21        format!("{v:.0}{}", UNITS[unit])
22    }
23}
24
25/// Formats a throughput, e.g. `"3.4M/s"`.
26pub fn rate(bytes_per_sec: f64) -> String {
27    format!("{}/s", bytes(bytes_per_sec.max(0.0) as u64))
28}
29
30/// Formats a duration in seconds as `"3d04h"`, `"5h12m"` or `"12:34"`.
31pub fn duration(secs: u64) -> String {
32    let days = secs / 86_400;
33    let hours = (secs % 86_400) / 3_600;
34    let minutes = (secs % 3_600) / 60;
35    if days > 0 {
36        format!("{days}d{hours:02}h")
37    } else if hours > 0 {
38        format!("{hours}h{minutes:02}m")
39    } else {
40        format!("{minutes:02}:{:02}", secs % 60)
41    }
42}
43
44/// Formats how long ago something happened, e.g. `"45s ago"`, `"8m ago"`, `"3d ago"`.
45pub fn age(secs: u64) -> String {
46    match secs {
47        0..10 => "just now".to_owned(),
48        10..120 => format!("{secs}s ago"),
49        120..7_200 => format!("{}m ago", secs / 60),
50        7_200..172_800 => format!("{}h ago", secs / 3_600),
51        _ => format!("{}d ago", secs / 86_400),
52    }
53}
54
55/// Formats a link speed in Mbit/s, e.g. `"10G"`, `"2.5G"`, `"100M"`.
56pub fn link_speed(mbps: f64) -> String {
57    if mbps >= 1000.0 {
58        let gbps = mbps / 1000.0;
59        if gbps.fract().abs() < 0.05 {
60            format!("{gbps:.0}G")
61        } else {
62            format!("{gbps:.1}G")
63        }
64    } else {
65        format!("{mbps:.0}M")
66    }
67}
68
69/// Truncates `text` to at most `width` characters, marking the cut with `…`.
70///
71/// Widths are terminal columns: CJK characters such as "イーサネット" count
72/// as two.
73pub fn truncate(text: &str, width: usize) -> String {
74    if text.width() <= width {
75        return text.to_owned();
76    }
77    if width == 0 {
78        return String::new();
79    }
80    // Keep characters while they fit, leaving one column for the ellipsis.
81    let mut out = String::new();
82    let mut used = 0;
83    for ch in text.chars() {
84        let w = ch.width().unwrap_or(0);
85        if used + w > width - 1 {
86            break;
87        }
88        out.push(ch);
89        used += w;
90    }
91    out.push('…');
92    out
93}
94
95/// Truncates `text` to `width` terminal columns and pads it with spaces to
96/// exactly that width (`format!("{:<N}")` counts characters, not columns).
97pub fn pad(text: &str, width: usize) -> String {
98    let mut out = truncate(text, width);
99    let used = out.width();
100    out.extend(std::iter::repeat_n(' ', width.saturating_sub(used)));
101    out
102}
103
104/// A percentage right-aligned in 4 columns (`" 12%"`), or `" --%"` when it
105/// is unknown (e.g. Intel GPU utilization).
106pub fn percent(value: Option<f32>) -> String {
107    value.map_or_else(|| " --%".to_owned(), |v| format!("{v:>3.0}%"))
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn percent_or_unknown() {
116        assert_eq!(percent(Some(7.4)), "  7%");
117        assert_eq!(percent(Some(100.0)), "100%");
118        assert_eq!(percent(None), " --%");
119    }
120    use unicode_width::UnicodeWidthStr;
121
122    #[test]
123    fn bytes_uses_binary_units_and_short_output() {
124        assert_eq!(bytes(0), "0B");
125        assert_eq!(bytes(1023), "1023B");
126        assert_eq!(bytes(1536), "1.5K");
127        assert_eq!(bytes(20 * 1024 * 1024), "20M");
128        assert_eq!(bytes(6_000_067_395_584), "5.5T");
129    }
130
131    #[test]
132    fn rate_appends_per_second() {
133        assert_eq!(rate(3_560_916.6), "3.4M/s");
134        assert_eq!(rate(-1.0), "0B/s");
135    }
136
137    #[test]
138    fn duration_picks_the_largest_units() {
139        assert_eq!(duration(75), "01:15");
140        assert_eq!(duration(3 * 3600 + 5 * 60), "3h05m");
141        assert_eq!(duration(2 * 86_400 + 4 * 3600), "2d04h");
142    }
143
144    #[test]
145    fn age_picks_a_readable_unit() {
146        assert_eq!(age(3), "just now");
147        assert_eq!(age(45), "45s ago");
148        assert_eq!(age(8 * 60), "8m ago");
149        assert_eq!(age(5 * 3600), "5h ago");
150        assert_eq!(age(3 * 86_400), "3d ago");
151    }
152
153    #[test]
154    fn link_speed_uses_g_and_m() {
155        assert_eq!(link_speed(10_000.0), "10G");
156        assert_eq!(link_speed(2_500.0), "2.5G");
157        assert_eq!(link_speed(1_000.0), "1G");
158        assert_eq!(link_speed(576.4), "576M");
159    }
160
161    #[test]
162    fn wide_characters_count_as_two_columns() {
163        // "イーサネット 3" is 7 characters but 14 columns.
164        assert_eq!(truncate("イーサネット 3", 14), "イーサネット 3");
165        assert_eq!(truncate("イーサネット 3", 8), "イーサ…");
166        assert_eq!(pad("イーサネット 3", 16), "イーサネット 3  ");
167        assert_eq!(pad("enp9s0", 8), "enp9s0  ");
168        assert_eq!(pad("イーサネット", 5).width(), 5);
169    }
170
171    #[test]
172    fn truncate_marks_the_cut() {
173        assert_eq!(truncate("rigtop", 10), "rigtop");
174        assert_eq!(truncate("rigtop-gui", 6), "rigto…");
175        assert_eq!(truncate("abc", 0), "");
176    }
177}