|
17 | 17 |
|
18 | 18 | use crate::Weekday; |
19 | 19 | use core::{fmt, i32}; |
20 | | -use num_traits::FromPrimitive; |
21 | 20 |
|
22 | 21 | /// The internal date representation. This also includes the packed `Mdf` value. |
23 | 22 | pub(super) type DateImpl = i32; |
@@ -321,17 +320,17 @@ impl Of { |
321 | 320 | } |
322 | 321 |
|
323 | 322 | #[inline] |
324 | | - pub(super) fn weekday(&self) -> Weekday { |
| 323 | + pub(super) const fn weekday(&self) -> Weekday { |
325 | 324 | let Of(of) = *self; |
326 | | - Weekday::from_u32(((of >> 4) + (of & 0b111)) % 7).unwrap() |
| 325 | + weekday_from_u32_mod7((of >> 4) + (of & 0b111)) |
327 | 326 | } |
328 | 327 |
|
329 | 328 | #[inline] |
330 | 329 | pub(super) fn isoweekdate_raw(&self) -> (u32, Weekday) { |
331 | 330 | // week ordinal = ordinal + delta |
332 | 331 | let Of(of) = *self; |
333 | 332 | 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)) |
335 | 334 | } |
336 | 335 |
|
337 | 336 | #[cfg_attr(feature = "cargo-clippy", allow(clippy::wrong_self_convention))] |
@@ -467,11 +466,28 @@ impl fmt::Debug for Mdf { |
467 | 466 | } |
468 | 467 | } |
469 | 468 |
|
| 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 | + |
470 | 484 | #[cfg(test)] |
471 | 485 | mod tests { |
472 | 486 | use num_iter::range_inclusive; |
| 487 | + use num_traits::FromPrimitive; |
473 | 488 | use std::u32; |
474 | 489 |
|
| 490 | + use super::weekday_from_u32_mod7; |
475 | 491 | use super::{Mdf, Of}; |
476 | 492 | use super::{YearFlags, A, AG, B, BA, C, CB, D, DC, E, ED, F, FE, G, GF}; |
477 | 493 | use crate::Weekday; |
@@ -824,4 +840,12 @@ mod tests { |
824 | 840 | } |
825 | 841 | } |
826 | 842 | } |
| 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 | + } |
827 | 851 | } |
0 commit comments