diff options
| author | Federico Igne <git@federicoigne.com> | 2020-07-08 18:17:06 +0200 |
|---|---|---|
| committer | Federico Igne <git@federicoigne.com> | 2021-11-03 18:55:00 +0000 |
| commit | 1bbdf8a1d5490737388d435831639938cec439e0 (patch) | |
| tree | a7f06ab016d7cd759cdf0022b1c222e9d437209c /clock/src | |
| parent | 12c8aedd5dfae75ec6bde982968bc77b70550374 (diff) | |
| download | exercism-1bbdf8a1d5490737388d435831639938cec439e0.tar.gz exercism-1bbdf8a1d5490737388d435831639938cec439e0.zip | |
[rust] Clock
Diffstat (limited to 'clock/src')
| -rw-r--r-- | clock/src/lib.rs | 44 |
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 @@ | |||
| 1 | use std::fmt; | ||
| 2 | use std::ops::Add; | ||
| 3 | |||
| 4 | #[derive(Debug, PartialEq, Clone, Copy)] | ||
| 5 | pub struct Clock { | ||
| 6 | hours: i32, | ||
| 7 | minutes: i32, | ||
| 8 | } | ||
| 9 | |||
| 10 | impl 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 | |||
| 16 | impl 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 | |||
| 31 | impl 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 | } | ||
