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
use std::fmt::{Debug, Display, Formatter};
use std::str::FromStr;
pub struct HumanReadableDuration {
time_in_seconds: u64,
}
impl HumanReadableDuration {
pub fn seconds(&self) -> u64 {
self.time_in_seconds
}
}
pub struct ParseHumanReadableDurationError;
impl Debug for ParseHumanReadableDurationError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "ParseHumanReadableDurationError")
}
}
impl Display for ParseHumanReadableDurationError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "ParseHumanReadableDurationError")
}
}
impl std::error::Error for ParseHumanReadableDurationError {}
impl FromStr for HumanReadableDuration {
type Err = ParseHumanReadableDurationError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Ok(HumanReadableDuration {
time_in_seconds: value.split("s").next().unwrap().parse::<u64>().unwrap(),
})
}
}
#[cfg(test)]
mod tests {
use crate::HumanReadableDuration;
use std::str::FromStr;
#[test]
fn from_str_10s_works() {
let representation = HumanReadableDuration::from_str("10s");
assert_eq!(true, representation.is_ok());
assert_eq!(10, representation.unwrap().seconds());
}
#[test]
fn from_str_60s_works() {
let representation = HumanReadableDuration::from_str("60");
assert_eq!(true, representation.is_ok());
assert_eq!(60, representation.unwrap().seconds());
}
#[test]
fn from_str_61s_works() {
let representation = HumanReadableDuration::from_str("61s");
assert_eq!(true, representation.is_ok());
assert_eq!(61, representation.unwrap().seconds());
}
}