Skip to main content

atman_runtime/
humanize.rs

1pub fn format_count(n: u64) -> String {
2    if n < 10_000 {
3        return n.to_string();
4    }
5    let (v, unit) = if n >= 1_000_000_000 {
6        (n as f64 / 1_000_000_000.0, "G")
7    } else if n >= 1_000_000 {
8        (n as f64 / 1_000_000.0, "M")
9    } else {
10        (n as f64 / 1_000.0, "K")
11    };
12    if v >= 100.0 {
13        format!("{:.0}{unit}", v)
14    } else if v >= 10.0 {
15        format!("{:.1}{unit}", v)
16    } else {
17        format!("{:.2}{unit}", v)
18    }
19}
20
21pub fn format_secs(secs: i64) -> String {
22    if secs < 0 {
23        return "0s".into();
24    }
25    let s = secs as u64;
26    if s < 60 {
27        return format!("{s}s");
28    }
29    if s < 3_600 {
30        return format!("{}m{}s", s / 60, s % 60);
31    }
32    if s < 86_400 {
33        return format!("{}h{}m", s / 3_600, (s % 3_600) / 60);
34    }
35    format!("{}d{}h", s / 86_400, (s % 86_400) / 3_600)
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn small_counts_stay_raw() {
44        assert_eq!(format_count(0), "0");
45        assert_eq!(format_count(999), "999");
46        assert_eq!(format_count(9_999), "9999");
47    }
48
49    #[test]
50    fn thousands_use_k() {
51        assert_eq!(format_count(10_000), "10.0K");
52        assert_eq!(format_count(12_345), "12.3K");
53        assert_eq!(format_count(999_000), "999K");
54    }
55
56    #[test]
57    fn millions_use_m() {
58        assert_eq!(format_count(1_000_000), "1.00M");
59        assert_eq!(format_count(224_694), "225K");
60        assert_eq!(format_count(1_500_000), "1.50M");
61    }
62
63    #[test]
64    fn billions_use_g() {
65        assert_eq!(format_count(1_000_000_000), "1.00G");
66        assert_eq!(format_count(12_345_678_901), "12.3G");
67    }
68
69    #[test]
70    fn seconds_under_minute_stay_raw() {
71        assert_eq!(format_secs(0), "0s");
72        assert_eq!(format_secs(45), "45s");
73    }
74
75    #[test]
76    fn seconds_convert_to_minutes() {
77        assert_eq!(format_secs(60), "1m0s");
78        assert_eq!(format_secs(125), "2m5s");
79        assert_eq!(format_secs(2_220), "37m0s");
80    }
81
82    #[test]
83    fn seconds_convert_to_hours() {
84        assert_eq!(format_secs(3_600), "1h0m");
85        assert_eq!(format_secs(7_500), "2h5m");
86    }
87
88    #[test]
89    fn seconds_convert_to_days() {
90        assert_eq!(format_secs(86_400), "1d0h");
91        assert_eq!(format_secs(90_061), "1d1h");
92    }
93
94    #[test]
95    fn negative_seconds_clamp_to_zero() {
96        assert_eq!(format_secs(-42), "0s");
97    }
98}