Skip to content

Commit 910e534

Browse files
committed
Make internal functions returning Weekday const
1 parent 1e17279 commit 910e534

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

src/naive/internals.rs

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717

1818
use crate::Weekday;
1919
use core::{fmt, i32};
20-
use num_traits::FromPrimitive;
2120

2221
/// The internal date representation. This also includes the packed `Mdf` value.
2322
pub(super) type DateImpl = i32;
@@ -321,17 +320,17 @@ impl Of {
321320
}
322321

323322
#[inline]
324-
pub(super) fn weekday(&self) -> Weekday {
323+
pub(super) const fn weekday(&self) -> Weekday {
325324
let Of(of) = *self;
326-
Weekday::from_u32(((of >> 4) + (of & 0b111)) % 7).unwrap()
325+
weekday_from_u32_mod7((of >> 4) + (of & 0b111))
327326
}
328327

329328
#[inline]
330329
pub(super) fn isoweekdate_raw(&self) -> (u32, Weekday) {
331330
// week ordinal = ordinal + delta
332331
let Of(of) = *self;
333332
let weekord = (of >> 4).wrapping_add(self.flags().isoweek_delta());
334-
(weekord / 7, Weekday::from_u32(weekord % 7).unwrap())
333+
(weekord / 7, weekday_from_u32_mod7(weekord))
335334
}
336335

337336
#[cfg_attr(feature = "cargo-clippy", allow(clippy::wrong_self_convention))]
@@ -467,11 +466,28 @@ impl fmt::Debug for Mdf {
467466
}
468467
}
469468

469+
/// Create a `Weekday` from an `u32`, with Monday = 0.
470+
/// Infallible, takes `n % 7`.
471+
#[inline]
472+
const fn weekday_from_u32_mod7(n: u32) -> Weekday {
473+
match n % 7 {
474+
0 => Weekday::Mon,
475+
1 => Weekday::Tue,
476+
2 => Weekday::Wed,
477+
3 => Weekday::Thu,
478+
4 => Weekday::Fri,
479+
5 => Weekday::Sat,
480+
_ => Weekday::Sun,
481+
}
482+
}
483+
470484
#[cfg(test)]
471485
mod tests {
472486
use num_iter::range_inclusive;
487+
use num_traits::FromPrimitive;
473488
use std::u32;
474489

490+
use super::weekday_from_u32_mod7;
475491
use super::{Mdf, Of};
476492
use super::{YearFlags, A, AG, B, BA, C, CB, D, DC, E, ED, F, FE, G, GF};
477493
use crate::Weekday;
@@ -824,4 +840,12 @@ mod tests {
824840
}
825841
}
826842
}
843+
844+
#[test]
845+
fn test_weekday_from_u32_mod7() {
846+
for i in 0..=1000 {
847+
assert_eq!(weekday_from_u32_mod7(i), Weekday::from_u32(i % 7).unwrap());
848+
}
849+
assert_eq!(weekday_from_u32_mod7(u32::MAX), Weekday::Thu);
850+
}
827851
}

0 commit comments

Comments
 (0)