mprober_lib/
functions.rs

1use std::{fmt::Write, time::Duration};
2
3/// Format a `Duration` to a string. The string would be like `4 hours, 39 minutes, and 25 seconds`.
4///
5/// ```rust
6/// use mprober_lib::uptime;
7///
8/// let uptime = uptime::get_uptime().unwrap();
9///
10/// println!("{}", mprober_lib::format_duration(uptime.total_uptime))
11/// ```
12pub fn format_duration(duration: Duration) -> String {
13    let sec = duration.as_secs();
14    let days = sec / 86400;
15    let sec = sec % 86400;
16    let hours = sec / 3600;
17    let sec = sec % 3600;
18    let minutes = sec / 60;
19    let seconds = sec % 60;
20
21    let mut s = String::with_capacity(10);
22
23    if days > 0 {
24        s.write_fmt(format_args!("{} day", days)).unwrap();
25
26        if days > 1 {
27            s.push('s');
28        }
29
30        s.push_str(", ");
31    }
32
33    if hours > 0 || (days > 0) && (minutes > 0 || seconds > 0) {
34        s.write_fmt(format_args!("{} hour", hours)).unwrap();
35
36        if hours > 1 {
37            s.push('s');
38        }
39
40        s.push_str(", ");
41    }
42
43    if minutes > 0 || (hours > 0 && seconds > 0) {
44        s.write_fmt(format_args!("{} minute", minutes)).unwrap();
45
46        if minutes > 1 {
47            s.push('s');
48        }
49
50        s.push_str(", ");
51    }
52
53    if seconds > 0 {
54        s.write_fmt(format_args!("{} second", seconds)).unwrap();
55
56        if seconds > 1 {
57            s.push('s');
58        }
59
60        s.push_str(", ");
61    }
62
63    debug_assert!(s.len() >= 2);
64
65    if let Some(index) = s.as_str()[..(s.len() - 2)].rfind(", ") {
66        s.insert_str(index + 2, "and ");
67    }
68
69    let mut v = s.into_bytes();
70
71    unsafe {
72        v.set_len(v.len() - 2);
73
74        String::from_utf8_unchecked(v)
75    }
76}