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
use std::fmt;
#[derive(Debug, PartialEq)]
pub struct TimeHMS {
h: u64,
m: u64,
s: u64,
}
impl TimeHMS {
pub fn new(seconds: u64) -> TimeHMS {
let (m, s) = divmod(seconds, 60);
let (h, m) = divmod(m, 60);
TimeHMS { h, m, s }
}
pub fn h(&self) -> u64 {
self.h
}
pub fn m(&self) -> u64 {
self.m
}
pub fn s(&self) -> u64 {
self.s
}
}
impl fmt::Display for TimeHMS {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:0>2}:{:0>2}:{:0>2}", self.h, self.m, self.s)
}
}
fn divmod(x: u64, y: u64) -> (u64, u64) {
let quotient = x / y;
let remainder = x % y;
(quotient, remainder)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_divmod() {
let test_cases = vec![
(5, 2, (2, 1)),
(10, 3, (3, 1)),
(13, 5, (2, 3)),
(0, 5, (0, 0)),
(u64::MAX, 1, (u64::MAX, 0)),
(u64::MAX, u64::MAX, (1, 0)),
];
for (x, y, expected) in test_cases {
assert_eq!(divmod(x, y), expected);
}
}
#[test]
fn valid_args() {
let test_cases = vec![
(0, (0, 0, 0)),
(12345, (3, 25, 45)),
(123456789, (34293, 33, 9)),
];
for (input, expected) in test_cases {
let t = TimeHMS::new(input);
let (h, m, s) = expected;
assert_eq!(t.h, h);
assert_eq!(t.m, m);
assert_eq!(t.s, s);
}
}
#[test]
fn equal() {
let t1 = TimeHMS::new(3661);
let t2 = TimeHMS::new(3661);
assert_eq!(t1, t2);
}
#[test]
fn not_equal() {
let t1 = TimeHMS::new(3661);
let t2 = TimeHMS::new(3662);
assert_ne!(t1, t2);
}
}