diff --git a/rust/clock/src/lib.rs b/rust/clock/src/lib.rs index d3f0573..176b58f 100644 --- a/rust/clock/src/lib.rs +++ b/rust/clock/src/lib.rs @@ -1,4 +1,4 @@ -use std::fmt::{Display, Formatter, self}; +use std::fmt::{self, Display, Formatter}; const HOURS_PER_DAY: i32 = 24; const MINUTES_PER_HOUR: i32 = 60; @@ -15,16 +15,12 @@ impl Clock { pub fn new(hours: i32, minutes: i32) -> Self { let since_midnight = MinutesSinceMidnight::new(minutes); let since_midnight = HOUR_SINCE_MIDNIGHT * hours + since_midnight; - Self { - since_midnight, - } + Self { since_midnight } } pub fn add_minutes(&self, minutes: i32) -> Self { let since_midnight = self.since_midnight + minutes; - Self { - since_midnight, - } + Self { since_midnight } } } @@ -47,6 +43,15 @@ impl RingI32 { const fn val(&self) -> i32 { self.0 } + + fn op(&self, rhs: i32, op: O) -> Self + where + O: FnOnce(i32, i32) -> i32, + { + let lhs = self.val(); + let rhs = rhs.rem_euclid(N); + Self(op(lhs, rhs).rem_euclid(N)) + } } impl Display for RingI32 { @@ -58,63 +63,55 @@ impl Display for RingI32 { impl std::ops::Add for RingI32 { type Output = Self; fn add(self, rhs: i32) -> Self { - let lhs = self.val(); - let rhs = rhs.rem_euclid(N); - Self((lhs + rhs).rem_euclid(N)) + self.op(rhs, i32::add) } } impl std::ops::Mul for RingI32 { type Output = Self; fn mul(self, rhs: i32) -> Self { - let lhs = self.val(); - let rhs = rhs.rem_euclid(N); - Self((lhs * rhs).rem_euclid(N)) + self.op(rhs, i32::mul) } } impl std::ops::Div for RingI32 { type Output = Self; fn div(self, rhs: i32) -> Self { - let lhs = self.val(); - let rhs = rhs.rem_euclid(N); - Self((lhs / rhs).rem_euclid(N)) + self.op(rhs, i32::div) } } impl std::ops::Rem for RingI32 { type Output = Self; fn rem(self, rhs: i32) -> Self { - let lhs = self.val(); - let rhs = rhs.rem_euclid(N); - Self((lhs % rhs).rem_euclid(N)) + self.op(rhs, i32::rem) } } impl std::ops::Add for RingI32 { type Output = Self; fn add(self, rhs: Self) -> Self { - self + rhs.val() + self.add(rhs.val()) } } impl std::ops::Mul for RingI32 { type Output = Self; fn mul(self, rhs: Self) -> Self { - self * rhs.val() + self.mul(rhs.val()) } } impl std::ops::Div for RingI32 { type Output = Self; fn div(self, rhs: Self) -> Self { - self / rhs.val() + self.div(rhs.val()) } } impl std::ops::Rem for RingI32 { type Output = Self; fn rem(self, rhs: Self) -> Self { - self % rhs.val() + self.rem(rhs.val()) } }