aboutsummaryrefslogtreecommitdiff
path: root/clock/src/lib.rs
diff options
context:
space:
mode:
Diffstat (limited to 'clock/src/lib.rs')
-rw-r--r--clock/src/lib.rs44
1 files changed, 44 insertions, 0 deletions
diff --git a/clock/src/lib.rs b/clock/src/lib.rs
new file mode 100644
index 0000000..3ae8a62
--- /dev/null
+++ b/clock/src/lib.rs
@@ -0,0 +1,44 @@
1use std::fmt;
2use std::ops::Add;
3
4#[derive(Debug, PartialEq, Clone, Copy)]
5pub struct Clock {
6 hours: i32,
7 minutes: i32,
8}
9
10impl fmt::Display for Clock {
11 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12 write!(f, "{:02}:{:02}", self.hours, self.minutes)
13 }
14}
15
16impl Add<i32> for Clock {
17 type Output = Self;
18
19 fn add(self, minutes: i32) -> Self {
20 Self::new(self.hours, self.minutes + minutes)
21 }
22}
23
24/* impl From<Clock> for String {
25 * fn from(c: Clock) -> String {
26 * format!("{}",c)
27 * }
28 * }
29 */
30
31impl Clock {
32 pub fn new(hours: i32, minutes: i32) -> Self {
33 let hours = hours + minutes / 60 - if minutes % 60 < 0 { 1 } else { 0 };
34 let hours = hours % 24;
35 let hours = hours + if hours < 0 { 24 } else { 0 };
36 let minutes = minutes % 60;
37 let minutes = minutes + if minutes < 0 { 60 } else { 0 };
38 Clock { hours, minutes }
39 }
40
41 pub fn add_minutes(self, minutes: i32) -> Self {
42 self + minutes
43 }
44}