src/fmt.rs 2.3 KiB raw
1
//! Plain string formatting helpers shared across Rustik crates.
2
3
use std::time::SystemTime;
4
5
/// Formats byte counts using compact binary units.
6
pub fn human_size(bytes: u64) -> String {
7
    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
8
9
    let mut value = bytes as f64;
10
    let mut unit = 0;
11
    while value >= 1024.0 && unit + 1 < UNITS.len() {
12
        value /= 1024.0;
13
        unit += 1;
14
    }
15
    if unit == 0 {
16
        format!("{bytes} {}", UNITS[unit])
17
    } else {
18
        format!("{value:.1} {}", UNITS[unit])
19
    }
20
}
21
22
/// Returns a relative time label from `now` to `time`.
23
pub fn relative_time(now: SystemTime, time: SystemTime) -> String {
24
    let Ok(age) = now.duration_since(time) else {
25
        return String::from("in the future");
26
    };
27
    let seconds = age.as_secs();
28
    if seconds < 60 {
29
        String::from("just now")
30
    } else if seconds < 60 * 60 {
31
        format!("{}m ago", seconds / 60)
32
    } else if seconds < 60 * 60 * 24 {
33
        format!("{}h ago", seconds / 60 / 60)
34
    } else {
35
        format!("{}d ago", seconds / 60 / 60 / 24)
36
    }
37
}
38
39
#[cfg(test)]
40
mod tests {
41
    use super::*;
42
    use std::time::Duration;
43
44
    #[test]
45
    fn human_size_formats_compact_binary_units() {
46
        assert_eq!(human_size(0), "0 B");
47
        assert_eq!(human_size(999), "999 B");
48
        assert_eq!(human_size(1024), "1.0 KB");
49
        assert_eq!(human_size(1536), "1.5 KB");
50
        assert_eq!(human_size(1024 * 1024), "1.0 MB");
51
        assert_eq!(human_size(1024 * 1024 * 1024), "1.0 GB");
52
    }
53
54
    #[test]
55
    fn relative_time_formats_past_ranges() {
56
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(60 * 60 * 24 * 2);
57
58
        assert_eq!(relative_time(now, now), "just now");
59
        assert_eq!(
60
            relative_time(now, now - Duration::from_secs(5 * 60)),
61
            "5m ago"
62
        );
63
        assert_eq!(
64
            relative_time(now, now - Duration::from_secs(3 * 60 * 60)),
65
            "3h ago"
66
        );
67
        assert_eq!(
68
            relative_time(now, now - Duration::from_secs(2 * 60 * 60 * 24)),
69
            "2d ago"
70
        );
71
    }
72
73
    #[test]
74
    fn relative_time_formats_future_times() {
75
        let now = SystemTime::UNIX_EPOCH;
76
77
        assert_eq!(
78
            relative_time(now, now + Duration::from_secs(1)),
79
            "in the future"
80
        );
81
    }
82
}