1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
use std::time::Duration;
pub trait AsSecs {
fn as_secs(&self) -> u64;
}
impl AsSecs for Duration {
fn as_secs(&self) -> u64 {
self.as_secs_f64() as u64
}
}
impl AsSecs for time::Duration {
fn as_secs(&self) -> u64 {
self.whole_seconds() as u64
}
}
pub struct FancyDuration<D: AsSecs>(pub D);
impl<D> FancyDuration<D>
where
D: AsSecs + Sized,
{
pub fn new(d: D) -> Self {
Self(d)
}
pub fn format(&self) -> String {
let mut time = self.0.as_secs();
if time == 0 {
return "0".to_string();
}
let days = time / 24 / 60 / 60;
time -= days * 24 * 60 * 60;
let hours = time / 60 / 60;
time -= hours * 60 * 60;
let minutes = time / 60;
time -= minutes * 60;
format!(
"{}{}{}{}",
if days >= 1 {
format!("{}d ", days)
} else {
"".to_string()
},
if hours >= 1 {
format!("{}h ", hours)
} else {
"".to_string()
},
if minutes >= 1 {
format!("{}m ", minutes)
} else {
"".to_string()
},
if time >= 1 {
format!("{}s", time)
} else {
"".to_string()
},
)
.trim_end()
.to_string()
}
}
impl<D> ToString for FancyDuration<D>
where
D: AsSecs,
{
fn to_string(&self) -> String {
self.format()
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use crate::FancyDuration;
#[test]
fn test_duration_to_string() {
assert_eq!(FancyDuration(Duration::new(600, 0)).to_string(), "10m");
assert_eq!(FancyDuration(Duration::new(120, 0)).to_string(), "2m");
assert_eq!(FancyDuration(Duration::new(185, 0)).to_string(), "3m 5s");
assert_eq!(
FancyDuration(Duration::new(24 * 60 * 60, 0)).to_string(),
"1d"
);
assert_eq!(FancyDuration(Duration::new(324, 0)).to_string(), "5m 24s");
assert_eq!(
FancyDuration(Duration::new(24 * 60 * 60 + 324, 0)).to_string(),
"1d 5m 24s"
);
}
#[test]
fn test_time_duration_to_string() {
assert_eq!(
FancyDuration(time::Duration::new(600, 0)).to_string(),
"10m"
);
assert_eq!(FancyDuration(time::Duration::new(120, 0)).to_string(), "2m");
assert_eq!(
FancyDuration(time::Duration::new(185, 0)).to_string(),
"3m 5s"
);
assert_eq!(
FancyDuration(time::Duration::new(24 * 60 * 60, 0)).to_string(),
"1d"
);
assert_eq!(
FancyDuration(time::Duration::new(324, 0)).to_string(),
"5m 24s"
);
assert_eq!(
FancyDuration(time::Duration::new(24 * 60 * 60 + 324, 0)).to_string(),
"1d 5m 24s"
);
}
}