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
use std::convert::TryFrom;
pub struct HumanReadableDuration {
time_in_seconds: u64,
}
impl HumanReadableDuration {
pub fn seconds(&self) -> u64 {
self.time_in_seconds
}
}
impl TryFrom<&str> for HumanReadableDuration {
type Error = ();
fn try_from(value: &str) -> Result<Self, Self::Error> {
Ok(HumanReadableDuration {
time_in_seconds: value.split("s").next().unwrap().parse::<u64>().unwrap(),
})
}
}
#[cfg(test)]
mod tests {
use crate::HumanReadableDuration;
use std::convert::TryFrom;
#[test]
fn from_10s_works() {
let representation = HumanReadableDuration::try_from("10s");
assert_eq!(true, representation.is_ok());
assert_eq!(10, representation.unwrap().seconds());
}
#[test]
fn from_60s_works() {
let representation = HumanReadableDuration::try_from("60");
assert_eq!(true, representation.is_ok());
assert_eq!(60, representation.unwrap().seconds());
}
#[test]
fn from_61s_works() {
let representation = HumanReadableDuration::try_from("61s");
assert_eq!(true, representation.is_ok());
assert_eq!(61, representation.unwrap().seconds());
}
}