From 02481656966b0a8dfc95cf3c22bcc049660ff7d4 Mon Sep 17 00:00:00 2001 From: Federico Igne Date: Sat, 26 Dec 2020 17:48:38 +0000 Subject: Move Rust exercises in a subdirectory --- rust/clock/src/lib.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 rust/clock/src/lib.rs (limited to 'rust/clock/src/lib.rs') diff --git a/rust/clock/src/lib.rs b/rust/clock/src/lib.rs new file mode 100644 index 0000000..3ae8a62 --- /dev/null +++ b/rust/clock/src/lib.rs @@ -0,0 +1,44 @@ +use std::fmt; +use std::ops::Add; + +#[derive(Debug, PartialEq, Clone, Copy)] +pub struct Clock { + hours: i32, + minutes: i32, +} + +impl fmt::Display for Clock { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:02}:{:02}", self.hours, self.minutes) + } +} + +impl Add for Clock { + type Output = Self; + + fn add(self, minutes: i32) -> Self { + Self::new(self.hours, self.minutes + minutes) + } +} + +/* impl From for String { + * fn from(c: Clock) -> String { + * format!("{}",c) + * } + * } + */ + +impl Clock { + pub fn new(hours: i32, minutes: i32) -> Self { + let hours = hours + minutes / 60 - if minutes % 60 < 0 { 1 } else { 0 }; + let hours = hours % 24; + let hours = hours + if hours < 0 { 24 } else { 0 }; + let minutes = minutes % 60; + let minutes = minutes + if minutes < 0 { 60 } else { 0 }; + Clock { hours, minutes } + } + + pub fn add_minutes(self, minutes: i32) -> Self { + self + minutes + } +} -- cgit v1.2.3