Skip to content

Commit

Permalink
Add test and some documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed May 5, 2023
1 parent a099b44 commit f92ac6b
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion src/naive/internals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,8 @@ const OL_TO_MDL: &[u8; MAX_OL as usize + 1] = &[
///
/// The whole bits except for the least 3 bits are referred as `Ol` (ordinal and leap flag),
/// which is an index to the `OL_TO_MDL` lookup table.
///
/// The methods implemented on `Of` always return a valid value.
#[derive(PartialEq, PartialOrd, Copy, Clone)]
pub(super) struct Of(u32);

Expand Down Expand Up @@ -384,13 +386,17 @@ impl fmt::Debug for Of {
/// The whole bits except for the least 3 bits are referred as `Mdl`
/// (month, day of month and leap flag),
/// which is an index to the `MDL_TO_OL` lookup table.
///
/// The methods implemented on `Mdf` do not always return a valid value.
/// Dates than can't exist, like February 30, can still be represented.
/// Use `Mdl::valid` to check whether the date is valid.
#[derive(PartialEq, PartialOrd, Copy, Clone)]
pub(super) struct Mdf(u32);

impl Mdf {
#[inline]
pub(super) const fn new(month: u32, day: u32, YearFlags(flags): YearFlags) -> Option<Mdf> {
match month <= 12 && day <= 31 {
match month >= 1 && month <= 12 && day >= 1 && day <= 31 {
true => Some(Mdf((month << 9) | (day << 4) | flags as u32)),
false => None,
}
Expand Down Expand Up @@ -829,4 +835,33 @@ mod tests {
}
}
}

#[test]
fn test_invalid_returns_none() {
let regular_year = YearFlags::from_year(2023);
let leap_year = YearFlags::from_year(2024);
assert!(Of::new(0, regular_year).is_none());
assert!(Of::new(366, regular_year).is_none());
assert!(Of::new(366, leap_year).is_some());
assert!(Of::new(367, regular_year).is_none());

assert!(Mdf::new(0, 1, regular_year).is_none());
assert!(Mdf::new(13, 1, regular_year).is_none());
assert!(Mdf::new(1, 0, regular_year).is_none());
assert!(Mdf::new(1, 32, regular_year).is_none());
assert!(Mdf::new(2, 31, regular_year).is_some());

assert!(Of::from_mdf(Mdf::new(2, 30, regular_year).unwrap()).is_none());
assert!(Of::from_mdf(Mdf::new(2, 30, leap_year).unwrap()).is_none());
assert!(Of::from_mdf(Mdf::new(2, 29, regular_year).unwrap()).is_none());
assert!(Of::from_mdf(Mdf::new(2, 29, leap_year).unwrap()).is_some());
assert!(Of::from_mdf(Mdf::new(2, 28, regular_year).unwrap()).is_some());

assert!(Of::new(365, regular_year).unwrap().succ().is_none());
assert!(Of::new(365, leap_year).unwrap().succ().is_some());
assert!(Of::new(366, leap_year).unwrap().succ().is_none());

assert!(Of::new(1, regular_year).unwrap().pred().is_none());
assert!(Of::new(1, leap_year).unwrap().pred().is_none());
}
}

0 comments on commit f92ac6b

Please sign in to comment.