Skip to main content

cosmic_applet_avestruz/
helpers.rs

1// SPDX-License-Identifier: MIT
2
3//! Small pure helpers shared by views and handlers.
4
5use std::time::{SystemTime, UNIX_EPOCH};
6
7/// Seconds since the Unix epoch, now.
8pub fn unix_now() -> u64 {
9    SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_secs())
10}
11
12/// How long ago `then` was, seen from `now`, as a feed shows it: `now`, `5m`,
13/// `3h`, `2d`, `6w`, `1y`. A time in the future (a clock that runs ahead)
14/// reads as `now`.
15pub fn relative_time(now: u64, then: u64) -> String {
16    const MINUTE: u64 = 60;
17    const HOUR: u64 = 60 * MINUTE;
18    const DAY: u64 = 24 * HOUR;
19    const WEEK: u64 = 7 * DAY;
20    const YEAR: u64 = 365 * DAY;
21
22    let elapsed = now.saturating_sub(then);
23    match elapsed {
24        e if e < MINUTE => "now".to_string(),
25        e if e < HOUR => format!("{}m", e / MINUTE),
26        e if e < DAY => format!("{}h", e / HOUR),
27        e if e < WEEK => format!("{}d", e / DAY),
28        e if e < YEAR => format!("{}w", e / WEEK),
29        e => format!("{}y", e / YEAR),
30    }
31}
32
33/// At most `max` characters of `text`, with an ellipsis when it was longer.
34pub fn truncate_chars(text: &str, max: usize) -> std::borrow::Cow<'_, str> {
35    match text.char_indices().nth(max) {
36        Some((cut, _)) => {
37            let head = text.get(..cut).unwrap_or(text);
38            std::borrow::Cow::Owned(format!("{}\u{2026}", head.trim_end()))
39        }
40        None => std::borrow::Cow::Borrowed(text),
41    }
42}
43
44/// `bytes` as a size someone reads: in the unit that leaves one to three
45/// digits before the point, with one after it past the first unit.
46pub fn readable_size(bytes: usize) -> String {
47    let mut size = bytes as f64;
48    let mut unit = "B";
49    for larger in ["kB", "MB", "GB"] {
50        if size < 1000.0 {
51            break;
52        }
53        size /= 1000.0;
54        unit = larger;
55    }
56    if unit == "B" { format!("{bytes} B") } else { format!("{size:.1} {unit}") }
57}
58
59/// A count short enough to sit beside an icon: `999`, `1.2k`, `15k`,
60/// `3.4M`. Rounded down, so it never says more than there is.
61pub fn compact_count(count: u64) -> String {
62    let scaled = |unit: u64, suffix: &str| {
63        let (whole, tenth) = (count / unit, count % unit * 10 / unit);
64        if whole < 10 && tenth > 0 { format!("{whole}.{tenth}{suffix}") } else { format!("{whole}{suffix}") }
65    };
66    match count {
67        0..1_000 => count.to_string(),
68        1_000..1_000_000 => scaled(1_000, "k"),
69        _ => scaled(1_000_000, "M"),
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::{compact_count, readable_size, relative_time, truncate_chars};
76
77    #[test]
78    fn a_size_is_said_in_the_unit_that_keeps_it_short() {
79        assert_eq!(readable_size(0), "0 B");
80        assert_eq!(readable_size(999), "999 B");
81        assert_eq!(readable_size(1_000), "1.0 kB");
82        assert_eq!(readable_size(21_400_000), "21.4 MB");
83        assert_eq!(readable_size(3_000_000_000), "3.0 GB");
84        assert_eq!(readable_size(5_000_000_000_000), "5000.0 GB");
85    }
86
87    #[test]
88    fn a_count_is_cut_to_what_fits_beside_an_icon() {
89        assert_eq!(compact_count(0), "0");
90        assert_eq!(compact_count(999), "999");
91        assert_eq!(compact_count(1_000), "1k");
92        assert_eq!(compact_count(1_250), "1.2k");
93        assert_eq!(compact_count(9_999), "9.9k");
94        assert_eq!(compact_count(15_800), "15k");
95        assert_eq!(compact_count(999_999), "999k");
96        assert_eq!(compact_count(3_400_000), "3.4M");
97        assert_eq!(compact_count(21_000_000), "21M");
98    }
99
100    #[test]
101    fn a_time_reads_in_the_largest_unit_that_fits() {
102        let now = 1_000_000_000;
103        let ago = |seconds: u64| relative_time(now, now - seconds);
104        assert_eq!(ago(0), "now");
105        assert_eq!(ago(59), "now");
106        assert_eq!(ago(60), "1m");
107        assert_eq!(ago(59 * 60 + 59), "59m");
108        assert_eq!(ago(3 * 3600), "3h");
109        assert_eq!(ago(2 * 86_400), "2d");
110        assert_eq!(ago(6 * 7 * 86_400), "6w");
111        assert_eq!(ago(400 * 86_400), "1y");
112    }
113
114    #[test]
115    fn a_time_ahead_of_the_clock_reads_as_now() {
116        assert_eq!(relative_time(100, 500), "now");
117    }
118
119    #[test]
120    fn long_text_is_cut_on_a_character_and_marked() {
121        assert_eq!(truncate_chars("short", 10), "short");
122        assert_eq!(truncate_chars("exactly ten", 11), "exactly ten");
123        assert_eq!(truncate_chars("olá avestruz", 3), "olá…");
124        assert_eq!(truncate_chars("one two three", 4), "one…");
125    }
126}