Skip to content

Commit

Permalink
weekday: wrapping arithmetics
Browse files Browse the repository at this point in the history
Signed-off-by: Guillaume W. Bres <guillaume.bressaix@gmail.com>
  • Loading branch information
gwbres committed Dec 2, 2022
1 parent 528ec08 commit fac8873
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
12 changes: 9 additions & 3 deletions src/weekday.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ impl Default for Weekday {

impl Weekday {
/// Max: last weekday <=> `Sunday`
pub const MAX: Self = Self::Sunday;
pub const MAX: u8 = 7;
}

impl From<u8> for Weekday {
fn from(u: u8) -> Self {
match u.rem_euclid(Self::MAX.into()) {
match u.rem_euclid(Self::MAX) {
0 => Self::Monday,
1 => Self::Tuesday,
2 => Self::Wednesday,
Expand All @@ -57,6 +57,12 @@ impl From<u8> for Weekday {
}
}

impl From<i8> for Weekday {
fn from(i: i8) -> Self {
Self::from((i.rem_euclid(Self::MAX as i8) +Self::MAX as i8) as u8)
}
}

impl From<Weekday> for u8 {
fn from(week: Weekday) -> Self {
match week {
Expand Down Expand Up @@ -112,7 +118,7 @@ impl Add<u8> for Weekday {
impl Sub<u8> for Weekday {
type Output = Self;
fn sub(self, rhs: u8) -> Self {
Self::from(self as u8 - rhs)
Self::from(self as i8 - rhs as i8)
}
}

Expand Down
23 changes: 18 additions & 5 deletions tests/weekday.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,24 @@ use std::f64::EPSILON;
#[test]
fn test_basic_ops() {
assert_eq!(Weekday::default(), Weekday::Monday);
let weekday = Weekday::default();
for i in 1..24 {
// test (+) wrapping
let add = weekday + i;

let monday = Weekday::default();
for i in 0..24 { // wrapping
let add = monday +i;
let expected: Weekday = i.rem_euclid(Weekday::MAX.into()).into();
assert_eq!(add, expected);
assert_eq!(add, expected, "test failed, expecting {:?} got {:?} for {:02} conversion", expected, add, i);
}

assert_eq!(monday-1, Weekday::Sunday);
assert_eq!(monday-2, Weekday::Saturday);
assert_eq!(monday-3, Weekday::Friday);
assert_eq!(monday-4, Weekday::Thursday);
assert_eq!(monday-5, Weekday::Wednesday);
assert_eq!(monday-6, Weekday::Tuesday);
assert_eq!(monday-7, monday);
assert_eq!(monday-8, Weekday::Sunday);
assert_eq!(monday-9, Weekday::Saturday);
assert_eq!(monday-13, Weekday::Tuesday);
assert_eq!(monday-14, monday);
assert_eq!(monday-15, Weekday::Sunday);
}

0 comments on commit fac8873

Please sign in to comment.