1use std::time::Duration;
2
3pub fn duration_alt_display(duration: Duration) -> String {
4 if duration < Duration::from_secs(60) {
5 format!("{}s", duration.as_secs())
6 } else {
7 duration_clock_format(duration)
8 }
9}
10
11fn duration_clock_format(duration: Duration) -> String {
12 let hours = duration.as_secs() / 3600;
13 let minutes = (duration.as_secs() % 3600) / 60;
14 let seconds = duration.as_secs() % 60;
15
16 if hours > 0 {
17 format!("{hours}:{minutes:02}:{seconds:02}")
18 } else if minutes > 0 {
19 format!("{minutes}:{seconds:02}")
20 } else {
21 format!("{seconds}")
22 }
23}
24
25#[cfg(test)]
26mod tests {
27 use super::*;
28
29 #[test]
30 fn test_duration_to_clock_format() {
31 use duration_clock_format as f;
32 assert_eq!("0", f(Duration::from_secs(0)));
33 assert_eq!("59", f(Duration::from_secs(59)));
34 assert_eq!("1:00", f(Duration::from_secs(60)));
35 assert_eq!("10:00", f(Duration::from_secs(600)));
36 assert_eq!("1:00:00", f(Duration::from_secs(3600)));
37 assert_eq!("3:02:01", f(Duration::from_secs(3600 * 3 + 60 * 2 + 1)));
38 assert_eq!("23:59:59", f(Duration::from_secs(3600 * 24 - 1)));
39 assert_eq!("100:00:00", f(Duration::from_secs(3600 * 100)));
40 }
41}