Skip to main content

dima_core/
human.rs

1//! Human-readable numbers for messages: durations, sizes and counts, shared by the command line
2//! and the desktop app so both say the same thing (D104).
3//!
4//! Numbers are plain digits with `.` as the decimal mark and no thousands separators, as the
5//! JSON outputs write them: the SI allows the comma as a decimal marker and never inserts commas
6//! or dots between digit groups ("Neither dots nor commas are ever inserted in the spaces
7//! between groups"), grouping being "a matter of choice" not always followed in "scripts to be
8//! read by a computer" (BIPM SI Brochure, 9th ed., §5.4.4), and speech synthesisers read "2,637"
9//! as a decimal in most languages. Unit symbols follow the number after a space (§5.4.3): `s`;
10//! `min` and `h`, accepted for use with the SI (Table 8); and bytes, `B`, with the SI's decimal
11//! prefixes `kB`, `MB`, `GB`. Every value is rounded *before* its unit is chosen, so the boundaries read
12//! naturally (59.96 s is `1 min 00 s`, not `60.0 s`; 999 999 bytes is `1.0 MB`, not
13//! `1000 kB`).
14
15use std::time::Duration;
16
17/// Separators of human-readable messages, in one place.
18pub mod separators {
19    /// Between groups of a message (`…in 1.00 s; entropy mean …`).
20    pub const GROUP: &str = "; ";
21    /// Between items of a list (`opening 0.01 s, counting k-mers 0.20 s`).
22    pub const ITEM: &str = ", ";
23}
24
25/// `"1 sequence"` / `"3 sequences"`.
26#[must_use]
27pub fn plural(n: u64, one: &str, many: &str) -> String {
28    format!("{n} {}", if n == 1 { one } else { many })
29}
30
31/// `0.21 s`, `12.3 s`, `4 min 05 s`, `1 h 02 min` (hours keep counting past a day).
32#[must_use]
33pub fn duration(d: Duration) -> String {
34    let s = d.as_secs_f64();
35    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
36    let round = |x: f64| x.round() as u64;
37    let centis = round(s * 100.0);
38    if centis < 1_000 {
39        return format!("{}.{:02} s", centis / 100, centis % 100);
40    }
41    let decis = round(s * 10.0);
42    if decis < 600 {
43        return format!("{}.{} s", decis / 10, decis % 10);
44    }
45    let seconds = round(s);
46    if seconds < 3_600 {
47        return format!("{} min {:02} s", seconds / 60, seconds % 60);
48    }
49    let minutes = round(s / 60.0);
50    format!("{} h {:02} min", minutes / 60, minutes % 60)
51}
52
53/// `17 B`, `512 kB`, `42.0 MB`, `1.2 GB`: decimal multiples with SI prefix symbols (lower-case
54/// k for kilo; BIPM SI Brochure, 9th ed., Table 7), one decimal below 100.
55#[must_use]
56pub fn bytes(n: u64) -> String {
57    const UNITS: [(&str, u64); 4] = [
58        ("kB", 1_000),
59        ("MB", 1_000_000),
60        ("GB", 1_000_000_000),
61        ("TB", 1_000_000_000_000),
62    ];
63    if n < 1_000 {
64        return format!("{n} B");
65    }
66    for (i, (unit, size)) in UNITS.iter().enumerate() {
67        #[allow(clippy::cast_precision_loss)]
68        let v = n as f64 / *size as f64;
69        // One decimal below 100 (after rounding), none above.
70        let text = if (v * 10.0).round() < 1_000.0 {
71            format!("{v:.1}")
72        } else {
73            format!("{v:.0}")
74        };
75        let shown: f64 = text.parse().unwrap_or(v);
76        if shown < 1_000.0 || i == UNITS.len() - 1 {
77            return format!("{text} {unit}");
78        }
79    }
80    unreachable!("the last unit always returns")
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86
87    #[test]
88    fn durations_round_before_choosing_the_unit() {
89        let ms = Duration::from_millis;
90        assert_eq!(duration(Duration::ZERO), "0.00 s");
91        assert_eq!(duration(ms(210)), "0.21 s");
92        assert_eq!(duration(ms(9_994)), "9.99 s");
93        assert_eq!(duration(ms(9_996)), "10.0 s");
94        assert_eq!(duration(ms(12_340)), "12.3 s");
95        assert_eq!(duration(ms(59_940)), "59.9 s");
96        assert_eq!(duration(ms(59_960)), "1 min 00 s");
97        assert_eq!(duration(Duration::from_secs(245)), "4 min 05 s");
98        assert_eq!(duration(ms(3_599_600)), "1 h 00 min");
99        assert_eq!(duration(Duration::from_secs(3_720)), "1 h 02 min");
100        assert_eq!(duration(Duration::from_secs(93_900)), "26 h 05 min");
101    }
102
103    #[test]
104    fn sizes_round_before_choosing_the_unit() {
105        assert_eq!(bytes(0), "0 B");
106        assert_eq!(bytes(999), "999 B");
107        assert_eq!(bytes(1_000), "1.0 kB");
108        assert_eq!(bytes(99_949), "99.9 kB");
109        assert_eq!(bytes(99_960), "100 kB");
110        assert_eq!(bytes(512_000), "512 kB");
111        assert_eq!(bytes(999_499), "999 kB");
112        assert_eq!(bytes(999_999), "1.0 MB");
113        assert_eq!(bytes(42_000_000), "42.0 MB");
114        assert_eq!(bytes(1_234_000_000), "1.2 GB");
115        assert_eq!(bytes(5_000_000_000_000_000), "5000 TB");
116    }
117
118    #[test]
119    fn plurals() {
120        assert_eq!(plural(1, "warning", "warnings"), "1 warning");
121        assert_eq!(plural(0, "warning", "warnings"), "0 warnings");
122        assert_eq!(plural(2637, "sequence", "sequences"), "2637 sequences");
123    }
124}