You are on page 1of 4

 

 68 changes: 68 additions & 0 deletions68  tests/month.rs

 24 changes: 24 additions & 0 deletions24  tests/weekday.rs

Expand Up @@ -46,6 +46,30 @@ fn nth_next() {

assert_eq!(Monday.nth_next(u8::MAX), Thursday);
}

#[test]
fn nth_prev() {
assert_eq!(Sunday.nth_prev(0), Sunday);
assert_eq!(Sunday.nth_prev(1), Saturday);
assert_eq!(Sunday.nth_prev(2), Friday);
assert_eq!(Sunday.nth_prev(3), Thursday);
assert_eq!(Sunday.nth_prev(4), Wednesday);
assert_eq!(Sunday.nth_prev(5), Tuesday);
assert_eq!(Sunday.nth_prev(6), Monday);

assert_eq!(Monday.nth_prev(0), Monday);
assert_eq!(Monday.nth_prev(1), Sunday);
assert_eq!(Monday.nth_prev(2), Saturday);
assert_eq!(Monday.nth_prev(3), Friday);
assert_eq!(Monday.nth_prev(4), Thursday);
assert_eq!(Monday.nth_prev(5), Wednesday);
assert_eq!(Monday.nth_prev(6), Tuesday);

assert_eq!(Sunday.nth_prev(7), Sunday);
assert_eq!(Sunday.nth_prev(u8::MAX), Thursday);
assert_eq!(Monday.nth_prev(7), Monday);
assert_eq!(Monday.nth_prev(u8::MAX), Friday);
}

#[test]
fn number_from_monday() {
assert_eq!(Monday.number_from_monday(), 1);
Expand Down

 54 changes: 54 additions & 0 deletions54  time/src/month.rs

Expand Up @@ -97,6 +97,60 @@ impl Month {

December => January,


}
}

/// Get n-th next month.


///
/// ```rust
/// # use time::Month;
/// assert_eq!(Month::January.nth_next(4), Month::May);
/// assert_eq!(Month::July.nth_next(9), Month::April);
/// ```
pub const fn nth_next(self, n: u8) -> Self {
match (self as u8 - 1 + n % 12) % 12 {
0 => January,
1 => February,
2 => March,
3 => April,
4 => May,
5 => June,
6 => July,
7 => August,
8 => September,
9 => October,
10 => November,
val => {
debug_assert!(val == 11);
December
}
}
}

/// Get n-th previous month.


///
/// ```rust
/// # use time::Month;
/// assert_eq!(Month::January.nth_prev(4), Month::September);
/// assert_eq!(Month::July.nth_prev(9), Month::October);
/// ```
pub const fn nth_prev(self, n: u8) -> Self {
match self as i8 - 1 - (n % 12) as i8 {
1 | -11 => February,
2 | -10 => March,
3 | -9 => April,
4 | -8 => May,
5 | -7 => June,
6 | -6 => July,
7 | -5 => August,
8 | -4 => September,
9 | -3 => October,
10 | -2 => November,
11 | -1 => December,
val => {
debug_assert!(val == 0);
January
}
}
}
}

impl fmt::Display for Month {

Expand Down

 22 changes: 22 additions & 0 deletions22  time/src/weekday.rs

Expand Up @@ -88,6 +88,28 @@ impl Weekday {

}
}

/// Get n-th previous day.


///
/// ```rust
/// # use time::Weekday;
/// assert_eq!(Weekday::Monday.nth_prev(1), Weekday::Sunday);
/// assert_eq!(Weekday::Sunday.nth_prev(10), Weekday::Thursday);
/// ```
pub const fn nth_prev(self, n: u8) -> Self {
match self.number_days_from_monday() as i8 - (n % 7) as i8 {
1 | -6 => Tuesday,
2 | -5 => Wednesday,
3 | -4 => Thursday,
4 | -3 => Friday,
5 | -2 => Saturday,
6 | -1 => Sunday,
val => {
debug_assert!(val == 0);
Monday
}
}
}

/// Get the one-indexed number of days from Monday.


///
/// ```rust

You might also like