Skip to content

Commit

Permalink
Make internal functions returning Weekday const
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Apr 29, 2023
1 parent 66f93f1 commit da835ae
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
7 changes: 3 additions & 4 deletions src/naive/internals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

use crate::Weekday;
use core::{fmt, i32};
use num_traits::FromPrimitive;

/// The internal date representation. This also includes the packed `Mdf` value.
pub(super) type DateImpl = i32;
Expand Down Expand Up @@ -320,17 +319,17 @@ impl Of {
}

#[inline]
pub(super) fn weekday(&self) -> Weekday {
pub(super) const fn weekday(&self) -> Weekday {
let Of(of) = *self;
Weekday::from_u32(((of >> 4) + (of & 0b111)) % 7).unwrap()
Weekday::from_u32_mod7((of >> 4) + (of & 0b111))
}

#[inline]
pub(super) fn isoweekdate_raw(&self) -> (u32, Weekday) {
// week ordinal = ordinal + delta
let Of(of) = *self;
let weekord = (of >> 4).wrapping_add(self.flags().isoweek_delta());
(weekord / 7, Weekday::from_u32(weekord % 7).unwrap())
(weekord / 7, Weekday::from_u32_mod7(weekord))
}

#[cfg_attr(feature = "cargo-clippy", allow(clippy::wrong_self_convention))]
Expand Down
19 changes: 17 additions & 2 deletions src/weekday.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,29 @@ pub enum Weekday {
}

impl Weekday {
/// Create a `Weekday` from an `u32`, with Monday = 0.
/// Infallible, takes `n & 7`.
#[inline]
pub(crate) const fn from_u32_mod7(n: u32) -> Weekday {
match n % 7 {
0 => Weekday::Mon,
1 => Weekday::Tue,
2 => Weekday::Wed,
3 => Weekday::Thu,
4 => Weekday::Fri,
5 => Weekday::Sat,
_ => Weekday::Sun,
}
}

/// The next day in the week.
///
/// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
/// ----------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
/// `w.succ()`: | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun` | `Mon`
#[inline]
#[must_use]
pub fn succ(&self) -> Weekday {
pub const fn succ(&self) -> Weekday {
match *self {
Weekday::Mon => Weekday::Tue,
Weekday::Tue => Weekday::Wed,
Expand All @@ -76,7 +91,7 @@ impl Weekday {
/// `w.pred()`: | `Sun` | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat`
#[inline]
#[must_use]
pub fn pred(&self) -> Weekday {
pub const fn pred(&self) -> Weekday {
match *self {
Weekday::Mon => Weekday::Sun,
Weekday::Tue => Weekday::Mon,
Expand Down

0 comments on commit da835ae

Please sign in to comment.