From f765936ee35ad3881d8705ae56714f3d805a198f Mon Sep 17 00:00:00 2001 From: Kirill Ivanov Date: Thu, 8 Aug 2024 13:56:54 +0300 Subject: [PATCH] Add `checked_days` --- src/naive/mod.rs | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/src/naive/mod.rs b/src/naive/mod.rs index f0e5eb1f..56ff8d4a 100644 --- a/src/naive/mod.rs +++ b/src/naive/mod.rs @@ -166,7 +166,43 @@ impl NaiveWeek { #[inline] #[must_use] pub const fn days(&self) -> RangeInclusive { - self.first_day()..=self.last_day() + // `expect` doesn't work because `RangeInclusive` is not `Copy` + match self.checked_days() { + Some(val) => val, + None => panic!("{}", "first or last weekday is out of range for `NaiveDate`"), + } + } + + /// Returns an [`Option>`] representing the whole week bounded by + /// [checked_first_day](NaiveWeek::checked_first_day) and + /// [checked_last_day](NaiveWeek::checked_last_day) functions. + /// + /// Returns `None` if either of the boundaries are out of `NaiveDate`'s range + /// (more than ca. 262,000 years away from common era). + /// + /// + /// # Examples + /// + /// ``` + /// use chrono::{NaiveDate, Weekday}; + /// + /// let date = NaiveDate::MAX; + /// let week = date.week(Weekday::Mon); + /// let _days = match week.checked_days() { + /// Some(d) => d, + /// None => { + /// // error handling code + /// return; + /// } + /// }; + /// ``` + #[inline] + #[must_use] + pub const fn checked_days(&self) -> Option> { + match (self.checked_first_day(), self.checked_last_day()) { + (Some(first), Some(last)) => Some(first..=last), + (_, _) => None, + } } }