1use crate::{
2 bounds::{selfas b, RangeError},
3 civil::{self, DateTime, Weekday},
4 macros::{ctry, rbail, rtry, unwrapr},
5};
67/// A Gregorian civil date.
8///
9/// A Gregorian civil date can be infallibly converted to and from
10/// [`UnixEpochDay`] values.
11///
12/// Note that since this supports a year `0`, this technically implements the
13/// ISO 8601 proleptic calendar and not the Gregorian calendar. Notably, the
14/// Gregorian calendar does not have a year `0`. Therefore, a `Date` with a
15/// year `0` is equivalent to the Gregorian `1 BCE` year.
16#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Date {
}
#[automatically_derived]impl ::core::clone::Clone for Date {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<i16>;
let _: ::core::clone::AssertParamIsClone<i8>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for Date { }Copy, #[automatically_derived]impl ::core::cmp::Eq for Date {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<i16>;
let _: ::core::cmp::AssertParamIsEq<i8>;
}
}Eq, #[automatically_derived]impl ::core::hash::Hash for Date {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.year, state);
::core::hash::Hash::hash(&self.month, state);
::core::hash::Hash::hash(&self.day, state)
}
}Hash, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Date { }
#[automatically_derived]impl ::core::cmp::PartialEq for Date {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.year == other.year && self.month == other.month &&
self.day == other.day
}
}PartialEq, #[automatically_derived]impl ::core::cmp::PartialOrd for Date {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]impl ::core::cmp::Ord for Date {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
match ::core::cmp::Ord::cmp(&self.year, &other.year) {
::core::cmp::Ordering::Equal =>
match ::core::cmp::Ord::cmp(&self.month, &other.month) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(&self.day, &other.day),
cmp => cmp,
},
cmp => cmp,
}
}
}Ord)]
17#[cfg_attr(feature = "defmt", derive(defmt::Format))]
18pub struct Date {
19 year: i16,
20 month: i8,
21 day: i8,
22}
2324impl Date {
25/// The minimum allowed Gregorian date.
26 ///
27 /// This is guaranteed to be equivalent to [`UnixEpochDay::MIN`] when
28 /// converted to a Unix epoch day.
29pub const MIN: Date = {
30let min = UnixEpochDay::MIN.to_date();
31if !(min.year() == -9999) {
::core::panicking::panic("assertion failed: min.year() == -9999")
};assert!(min.year() == -9999);
32if !(min.month() == 1) {
::core::panicking::panic("assertion failed: min.month() == 1")
};assert!(min.month() == 1);
33if !(min.day() == 1) {
::core::panicking::panic("assertion failed: min.day() == 1")
};assert!(min.day() == 1);
34min35 };
3637/// The maximum allowed Gregorian date.
38 ///
39 /// This is guaranteed to be equivalent to [`UnixEpochDay::MAX`] when
40 /// converted to a Unix epoch day.
41pub const MAX: Date = {
42let max = UnixEpochDay::MAX.to_date();
43if !(max.year() == 9999) {
::core::panicking::panic("assertion failed: max.year() == 9999")
};assert!(max.year() == 9999);
44if !(max.month() == 12) {
::core::panicking::panic("assertion failed: max.month() == 12")
};assert!(max.month() == 12);
45if !(max.day() == 31) {
::core::panicking::panic("assertion failed: max.day() == 31")
};assert!(max.day() == 31);
46max47 };
4849// I'm hopeful we won't need a public unchecked constructor. But if
50 // we do, it cannot be marked safe. Otherwise callers cannot soundly rely
51 // on the values of, e.g., `Date::day()` being in range for memory safety.
52 /*
53 /// Returns a new `Date` without doing bounds checks on the values given.
54 ///
55 /// # Safety
56 ///
57 /// Callers must ensure that the year, month and day provided are a valid
58 /// Gregorian date **and** that `year` falls into the range specified by
59 /// [`Year`](b::Year).
60 ///
61 /// While memory safety may not be violated immediately from using an
62 /// invalid value, downstream callers may rely on the validity of routines
63 /// like `Date::month` for memory safety. If this routine was safe,
64 /// then such reliance would be unsound.
65 #[inline]
66 pub const unsafe fn new_unchecked(year: i16, month: i8, day: i8) -> Date {
67 Date { year, month, day }
68 }
69 */
7071/// Creates a new date in the Gregorian calendar.
72 ///
73 /// If the date is invalid or any of the values are out of their supported
74 /// ranges, then an error is returned.
75 ///
76 /// Note that, technically, the date returned is in the ISO 8601 proleptic
77 /// calendar. The only difference between it and the Gregorian calendar
78 /// is that ISO 8601 has a year `0`. ISO 8601's year `0` corresponds to
79 /// `-1 BCE` in the Gregorian calendar.
80#[inline]
81pub const fn new(
82 year: i16,
83 month: i8,
84 day: i8,
85 ) -> Result<Date, RangeError> {
86let year = match b::Year::checkc(year as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::Year::checkc(year as i64));
87let month = match b::Month::checkc(month as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::Month::checkc(month as i64));
88if day < 1 {
89return Err(b::Day::error().into_range_error());rbail!(b::Day::error());
90 } else if day > 28 && day > civil::days_in_month(year, month) {
91return Err(b::SpecialBoundsError::DateInvalidDay {
year,
month,
}.into_range_error());rbail!(b::SpecialBoundsError::DateInvalidDay { year, month });
92 }
93Ok(Date { year, month, day })
94 }
9596/// Like `Date::new`, but constrains the day value to the last day of
97 /// `month`.
98 ///
99 /// This still returns an error when `day < 1` or when `year` or `month`
100 /// are invalid.
101#[inline]
102pub const fn new_constrain(
103 year: i16,
104 month: i8,
105 day: i8,
106 ) -> Result<Date, RangeError> {
107let year = match b::Year::checkc(year as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::Year::checkc(year as i64));
108let month = match b::Month::checkc(month as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::Month::checkc(month as i64));
109let day = if day < 1 {
110return Err(b::Day::error().into_range_error());rbail!(b::Day::error());
111 } else if day > 28 {
112let days_in_month = civil::days_in_month(year, month);
113if day <= days_in_month { day } else { days_in_month }
114 } else {
115day116 };
117Ok(Date { year, month, day })
118 }
119120/// Returns the date corresponding to the day of the given year. The day
121 /// of the year should be a value in `1..=366`, with `366` only being valid
122 /// if `year` is a leap year.
123 ///
124 /// Returns an error if `year` is not in the range specified by
125 /// [`Year`](b::Year), or if `day` is invalid for the given year.
126#[inline]
127pub const fn from_day_of_year(
128 year: i16,
129 day: i16,
130 ) -> Result<Date, RangeError> {
131let year = match b::Year::checkc(year as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::Year::checkc(year as i64));
132let day = match b::DayOfYear::checkc(day as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::DayOfYear::checkc(day as i64));
133let start = Date { year, month: 1, day: 1 }.to_unix_epoch_day();
134let end = match start.checked_add(dayas i32 - 1) {
135Ok(end) => end.to_date(),
136// This can only happen when `year=9999` and `day=366`.
137Err(_) => {
138return Err(b::SpecialBoundsError::DateInvalidDayOfYear {
year,
}.into_range_error())rbail!(b::SpecialBoundsError::DateInvalidDayOfYear { year })139 }
140 };
141// If we overflowed into the next year, then `day` is too big.
142if year != end.year {
143// Can only happen given day=366 and this is a leap year.
144if true {
if !(day == 366) {
::core::panicking::panic("assertion failed: day == 366")
};
};debug_assert!(day == 366);
145if true {
if !!civil::is_leap_year(year) {
::core::panicking::panic("assertion failed: !civil::is_leap_year(year)")
};
};debug_assert!(!civil::is_leap_year(year));
146return Err(b::SpecialBoundsError::DateInvalidDayOfYear {
year,
}.into_range_error())rbail!(b::SpecialBoundsError::DateInvalidDayOfYear { year })147 }
148Ok(end)
149 }
150151/// Returns the date corresponding to the day of the given year. The day
152 /// of the year must be a value in `1..=365`, with February 29 being
153 /// completely ignored. That is, it is guaranteed that February 29 will
154 /// never be returned by this function. It is impossible.
155 ///
156 /// Returns an error if `year` is not in the range specified by
157 /// [`Year`](b::Year), or if `day` is outside the range `1..=365`.
158#[inline]
159pub const fn from_day_of_year_no_leap(
160 year: i16,
161 day: i16,
162 ) -> Result<Date, RangeError> {
163let year = match b::Year::checkc(year as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::Year::checkc(year as i64));
164let mut day = match b::DayOfYearNoLeap::checkc(day as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::DayOfYearNoLeap::checkc(day as i64));
165if day >= 60 && civil::is_leap_year(year) {
166day += 1;
167 }
168// The boundary check above guarantees this always succeeds.
169Ok(match Date::from_day_of_year(year, day) {
Ok(val) => val,
Err(_) => {
::core::panicking::panic_fmt(format_args!("valid day of year"));
}
}unwrapr!(Date::from_day_of_year(year, day), "valid day of year"))
170 }
171172/// Returns the year component of this date.
173 ///
174 /// The value returned is guaranteed to be in the range specified by
175 /// [`Year`](crate::bounds::Year).
176#[inline]
177pub const fn year(self) -> i16 {
178self.year
179 }
180181/// Returns the month component of this date.
182 ///
183 /// The value returned is guaranteed to be in the range `1..=12`.
184#[inline]
185pub const fn month(self) -> i8 {
186self.month
187 }
188189/// Returns the day component of this date.
190 ///
191 /// The value returned is guaranteed to be in the range
192 /// `1..=jiff_core::civil::days_in_month(date.year(), date.month())`.
193#[inline]
194pub const fn day(self) -> i8 {
195self.day
196 }
197198/// Returns the weekday corresponding to this date.
199#[inline]
200pub const fn weekday(self) -> Weekday {
201self.to_unix_epoch_day().weekday()
202 }
203204/// Returns the ordinal day of the year that this date resides in.
205 ///
206 /// For leap years, this always returns a value in the range `1..=366`.
207 /// Otherwise, the value is in the range `1..=365`.
208#[inline]
209pub const fn day_of_year(self) -> i16 {
210const DAYS_BY_MONTH_NO_LEAP: [i16; 14] =
211 [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365];
212const DAYS_BY_MONTH_LEAP: [i16; 14] =
213 [0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366];
214const TABLES: [[i16; 14]; 2] =
215 [DAYS_BY_MONTH_NO_LEAP, DAYS_BY_MONTH_LEAP];
216TABLES[self.in_leap_year() as usize][self.month() as usize]
217 + (self.day() as i16)
218 }
219220/// Returns the ordinal day of the year that this date resides in, but
221 /// ignores leap years.
222 ///
223 /// That is, the range of possible values returned by this routine is
224 /// `1..=365`, even if this date resides in a leap year. If this date is
225 /// February 29, then this routine returns `None`.
226 ///
227 /// The value `365` always corresponds to the last day in the year,
228 /// December 31, even for leap years.
229#[inline]
230pub const fn day_of_year_no_leap(self) -> Option<i16> {
231let mut days = self.day_of_year();
232if self.in_leap_year() {
233// day=60 is Feb 29
234if days == 60 {
235return None;
236 } else if days > 60 {
237days -= 1;
238 }
239 }
240Some(days)
241 }
242243/// Returns the first date of the month for this date.
244#[inline]
245pub const fn first_of_month(self) -> Date {
246Date { day: 1, ..self }
247 }
248249/// Returns the last date of the month for this date.
250#[inline]
251pub const fn last_of_month(self) -> Date {
252Date { day: self.days_in_month(), ..self }
253 }
254255/// Returns the total number of days in the the month in which this date
256 /// resides.
257 ///
258 /// This is guaranteed to always return one of the following values,
259 /// depending on the year and the month: 28, 29, 30 or 31.
260#[inline]
261pub const fn days_in_month(self) -> i8 {
262 civil::days_in_month(self.year(), self.month())
263 }
264265/// Returns the first date of the year that this date resides in.
266#[inline]
267pub const fn first_of_year(self) -> Date {
268Date { month: 1, day: 1, ..self }
269 }
270271/// Returns the last date of the year that this date resides in.
272#[inline]
273pub const fn last_of_year(self) -> Date {
274Date { month: 12, day: 31, ..self }
275 }
276277/// Returns the number of days in the year for this date.
278 ///
279 /// It is guaranteed that the value returned is either `365` or `366`.
280#[inline]
281pub const fn days_in_year(self) -> i16 {
282if self.in_leap_year() { 366 } else { 365 }
283 }
284285/// Returns true when this date is in a leap year.
286#[inline]
287pub const fn in_leap_year(self) -> bool {
288 civil::is_leap_year(self.year())
289 }
290291/// Returns the day before this date.
292 ///
293 /// Returns an error when this is the minimal date.
294#[inline]
295pub const fn yesterday(self) -> Result<Date, RangeError> {
296if self.day() == 1 {
297if self.month() == 1 {
298let year = match self.prev_year() { Ok(val) => val, Err(err) => return Err(err), }ctry!(self.prev_year());
299return Ok(Date { year, month: 12, day: 31 });
300 }
301let month = self.month() - 1;
302let day = civil::days_in_month(self.year(), month);
303return Ok(Date { month, day, ..self });
304 }
305Ok(Date { day: self.day() - 1, ..self })
306 }
307308/// Returns the day after this date.
309 ///
310 /// Returns an error when this is the maximal date.
311#[inline]
312pub const fn tomorrow(self) -> Result<Date, RangeError> {
313if self.day() >= 28 && self.day() == self.days_in_month() {
314if self.month() == 12 {
315let year = match self.next_year() { Ok(val) => val, Err(err) => return Err(err), }ctry!(self.next_year());
316return Ok(Date { year, month: 1, day: 1 });
317 }
318let month = self.month() + 1;
319return Ok(Date { month, day: 1, ..self });
320 }
321Ok(Date { day: self.day() + 1, ..self })
322 }
323324/// Returns the `nth` weekday of the month represented by this date.
325 ///
326 /// `nth` must be non-zero and otherwise in the range `-5..=5`. If it
327 /// isn't, an error is returned.
328 ///
329 /// This also returns an error if `abs(nth)==5` and there is no "5th"
330 /// weekday of this month.
331#[inline]
332pub const fn nth_weekday_of_month(
333&self,
334 nth: i8,
335 weekday: Weekday,
336 ) -> Result<Date, RangeError> {
337let nth = match b::NthWeekdayOfMonth::checkc(nth as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::NthWeekdayOfMonth::checkc(nth as i64));
338if nth == 0 {
339return Err(b::NthWeekdayOfMonth::error().into_range_error());rbail!(b::NthWeekdayOfMonth::error());
340 } else if nth > 0 {
341let first = self.first_of_month();
342let first_weekday = first.weekday();
343let diff = weekday.since(first_weekday);
344let day = diff + 1 + (nth - 1) * 7;
345Date::new(self.year(), self.month(), day)
346 } else {
347let last = self.last_of_month();
348let last_weekday = last.weekday();
349let diff = last_weekday.since(weekday);
350let day = last.day() - diff - (nth.abs() - 1) * 7;
351Date::new(self.year(), self.month(), day)
352 }
353 }
354355/// Returns the "nth" weekday from this date, not including itself.
356 ///
357 /// The `nth` parameter can be positive or negative. A positive value
358 /// computes the "nth" weekday starting at the day after this date and
359 /// going forwards in time. A negative value computes the "nth" weekday
360 /// starting at the day before this date and going backwards in time.
361 ///
362 /// For example, if this date's weekday is a Sunday and the first Sunday is
363 /// asked for (that is, `date.nth_weekday(1, Weekday::Sunday)`), then the
364 /// result is a week from this date corresponding to the following Sunday.
365#[inline]
366pub const fn nth_weekday(
367self,
368 nth: i32,
369 weekday: Weekday,
370 ) -> Result<Date, RangeError> {
371self.to_unix_epoch_day().nth_weekday(nth, weekday)
372 }
373374/// Returns the year one year before this date.
375 ///
376 /// Returns an error if this would result in a year outside the range
377 /// specified by [`Year`](b::Year).
378#[inline]
379pub(crate) const fn prev_year(self) -> Result<i16, RangeError> {
380Ok(match b::Year::checked_add(self.year(), -1) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::Year::checked_add(self.year(), -1)))
381 }
382383/// Returns the year one year from this date.
384#[inline]
385pub(crate) const fn next_year(self) -> Result<i16, RangeError> {
386Ok(match b::Year::checked_add(self.year(), 1) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::Year::checked_add(self.year(), 1)))
387 }
388389/// Adds the given number of days to this date.
390 ///
391 /// Returns an error if the result is outside the valid range of a `Date`.
392#[inline]
393pub const fn checked_add(self, days: i32) -> Result<Date, RangeError> {
394match days {
3950 => Ok(self),
396 -1 => self.yesterday(),
3971 => self.tomorrow(),
398 n => Ok(match self.to_unix_epoch_day().checked_add(n) {
Ok(val) => val,
Err(err) => return Err(err),
}ctry!(self.to_unix_epoch_day().checked_add(n)).to_date()),
399 }
400 }
401402/// Subtracts the given number of days to this date.
403 ///
404 /// Returns an error if the result is outside the valid range of a `Date`.
405#[inline]
406pub const fn checked_sub(self, days: i32) -> Result<Date, RangeError> {
407let Some(days) = days.checked_neg() else {
408return Err(b::UnixEpochDays::error().into_range_error());rbail!(b::UnixEpochDays::error());
409 };
410self.checked_add(days)
411 }
412413/// Returns the number of days from this date until `other`.
414 ///
415 /// This routine never overflows because of the enforced range on
416 /// `Date` values.
417 ///
418 /// # Example
419 ///
420 /// ```
421 /// use jiff_core::civil::date;
422 ///
423 /// let date1 = date(2023, 7, 1);
424 /// let date2 = date(2024, 7, 1);
425 /// assert_eq!(366, date1.until(date2));
426 ///
427 /// // The value will be negative when the dates are flipped:
428 /// assert_eq!(-366, date2.until(date1));
429 /// ```
430 ///
431 /// # Example: overflow isn't possible
432 ///
433 /// Even when using the minimum or maximum values:
434 ///
435 /// ```
436 /// use jiff_core::civil::Date;
437 ///
438 /// assert_eq!(7_304_483, Date::MIN.until(Date::MAX));
439 /// assert_eq!(-7_304_483, Date::MAX.until(Date::MIN));
440 /// ```
441#[inline]
442pub const fn until(self, other: Date) -> i32 {
443 -self.since(other)
444 }
445446/// Returns the number of days from this date since `other`.
447 ///
448 /// This routine never overflows because of the enforced range on
449 /// `Date` values.
450 ///
451 /// # Example
452 ///
453 /// ```
454 /// use jiff_core::civil::date;
455 ///
456 /// let date1 = date(2023, 7, 1);
457 /// let date2 = date(2024, 7, 1);
458 /// assert_eq!(366, date2.since(date1));
459 ///
460 /// // The value will be negative when the dates are flipped:
461 /// assert_eq!(-366, date1.since(date2));
462 /// ```
463 ///
464 /// # Example: overflow isn't possible
465 ///
466 /// Even when using the minimum or maximum values:
467 ///
468 /// ```
469 /// use jiff_core::civil::Date;
470 ///
471 /// assert_eq!(7_304_483, Date::MAX.since(Date::MIN));
472 /// ```
473#[inline]
474pub const fn since(self, other: Date) -> i32 {
475// Try to avoid conversions to Unix epoch days in some cases.
476if self.year() == other.year() {
477if self.month() == other.month() {
478 (self.day() - other.day()) as i32479 } else {
480 (self.day_of_year() - other.day_of_year()) as i32481 }
482 } else {
483self.to_unix_epoch_day().since(other.to_unix_epoch_day())
484 }
485 }
486487/// Converts a Gregorian date to a Unix epoch day.
488#[inline]
489 #[allow(non_upper_case_globals, non_snake_case)] // to mimic source
490pub const fn to_unix_epoch_day(self) -> UnixEpochDay {
491// This is Neri-Schneider. There's no branching or divisions.
492 //
493 // Ref: https://github.com/cassioneri/eaf/blob/684d3cc32d14eee371d0abe4f683d6d6a49ed5c1/algorithms/neri_schneider.hpp#L83
494const s: u32 = 82;
495const K: u32 = 719468 + 146097 * s;
496const L: u32 = 400 * s;
497498let year = self.year as u32;
499let month = self.month as u32;
500let day = self.day as u32;
501502let J = month <= 2;
503let Y = year.wrapping_add(L).wrapping_sub(Jas u32);
504let M = if J { month + 12 } else { month };
505let D = day - 1;
506let C = Y / 100;
507508let y_star = 1461 * Y / 4 - C + C / 4;
509let m_star = (979 * M - 2919) / 32;
510let N = y_star + m_star + D;
511512let N_U = N.wrapping_sub(K);
513let epoch_day = N_Uas i32;
514UnixEpochDay { day: epoch_day }
515 }
516517/// Converts this Gregorian date to an ISO 8601 week date.
518#[inline]
519pub const fn to_iso_week_date(self) -> ISOWeekDate {
520let epoch_day = self.to_unix_epoch_day();
521let mut year = self.year();
522let mut epoch_day_year_start = iso_week_start_from_year(year);
523if epoch_day.day() < epoch_day_year_start.day() {
524// If our date comes before the first day of the ISO 8601 year,
525 // then it must be the case that our date falls at the end of the
526 // previous ISO 8601 year. This can happen for Gregorian dates
527 // Jan 1, 2 or 3.
528 //
529 // And this subtraction is OK because `year - 1` is only a problem
530 // when `year=-9999`. But we can't be here when `year=-9999` since
531 // that would imply an `epoch_day` that occurs before the first day
532 // of this date's Gregorian year. That would in turn imply a date
533 // before `-9999-01-01`, which is impossible.
534year -= 1;
535epoch_day_year_start = iso_week_start_from_year(year);
536 } else if self.month() == 12 && self.day() >= 29 && year < b::Year::MAX537 {
538// Otherwise, it's possible for dates at the end of the Gregorian
539 // calendar year to actually have an ISO 8601 week year following
540 // the Gregorian calendar year. This can occur for only Dec 29, 30
541 // or 31. For `year=9999`, we don't need to do this check because
542 // in that specific instance, the last day of `9999` corresponds to
543 // `9999-W52-5`. So it's not possible for the ISO 8601 week year to
544 // be `10000`.
545let epoch_day_next_year_week_start =
546iso_week_start_from_year(year + 1);
547if epoch_day.day() >= epoch_day_next_year_week_start.day() {
548epoch_day_year_start = epoch_day_next_year_week_start;
549year += 1;
550 }
551 }
552553// OK because the biggest difference between epoch days here can be
554 // 370 (for a long year), and dividing that by 7 and adding 1 always
555 // fits into an `i8`.
556let week =
557 (((epoch_day.day() - epoch_day_year_start.day()) / 7) + 1) as i8;
558let weekday = epoch_day.weekday();
559560ISOWeekDate { year, week, weekday }
561 }
562563/// A convenience function for constructing a [`DateTime`] from this date
564 /// at the time given by its components.
565 ///
566 /// # Panics
567 ///
568 /// This panics if the provided values do not correspond to a valid `Time`.
569 /// All of the following conditions must be true:
570 ///
571 /// * `0 <= hour <= 23`
572 /// * `0 <= minute <= 59`
573 /// * `0 <= second <= 59`
574 /// * `0 <= subsec_nanosecond <= 999,999,999`
575 ///
576 /// Similarly, when used in a const context, invalid parameters will
577 /// prevent your Rust program from compiling.
578#[inline]
579pub const fn at(
580self,
581 hour: i8,
582 minute: i8,
583 second: i8,
584 subsec_nanosecond: i32,
585 ) -> DateTime {
586DateTime::from_parts(
587self,
588 civil::time(hour, minute, second, subsec_nanosecond),
589 )
590 }
591}
592593impl core::fmt::Debugfor Date {
594fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
595if self.year() < 0 {
596f.write_fmt(format_args!("-{0:06}", self.year().unsigned_abs()))write!(f, "-{:06}", self.year().unsigned_abs())?;
597 } else {
598f.write_fmt(format_args!("{0:04}", self.year()))write!(f, "{:04}", self.year())?;
599 }
600f.write_fmt(format_args!("-{0:02}-{1:02}", self.month(), self.day()))write!(f, "-{:02}-{:02}", self.month(), self.day())601 }
602}
603604/// Returns the number of days between two `Date` values.
605///
606/// This routine never overflows because of the enforced range on
607/// `Date` values.
608///
609/// # Example
610///
611/// ```
612/// use jiff_core::civil::date;
613///
614/// let date1 = date(2023, 7, 1);
615/// let date2 = date(2024, 7, 1);
616/// assert_eq!(366, date2 - date1);
617///
618/// // The value will be negative when the dates are flipped:
619/// assert_eq!(-366, date1 - date2);
620/// ```
621///
622/// # Example: overflow isn't possible
623///
624/// Even when using the minimum or maximum values:
625///
626/// ```
627/// use jiff_core::civil::Date;
628///
629/// assert_eq!(7_304_483, Date::MAX - Date::MIN);
630/// ```
631impl core::ops::Subfor Date {
632type Output = i32;
633634#[inline]
635fn sub(self, rhs: Date) -> i32 {
636self.since(rhs)
637 }
638}
639640#[cfg(feature = "arbitrary")]
641impl<'a> arbitrary::Arbitrary<'a> for Date {
642fn arbitrary(
643 u: &mut arbitrary::Unstructured<'a>,
644 ) -> arbitrary::Result<Date> {
645let year = u.int_in_range(b::Year::MIN..=b::Year::MAX)?;
646let month = u.int_in_range(b::Month::MIN..=b::Month::MAX)?;
647let day = u.int_in_range(b::Day::MIN..=b::Day::MAX)?;
648Ok(Date::new_constrain(year, month, day).unwrap())
649 }
650651fn size_hint(depth: usize) -> (usize, Option<usize>) {
652 arbitrary::size_hint::and_all(&[
653 <i16 as arbitrary::Arbitrary>::size_hint(depth),
654 <i8 as arbitrary::Arbitrary>::size_hint(depth),
655 <i8 as arbitrary::Arbitrary>::size_hint(depth),
656 ])
657 }
658}
659660#[cfg(test)]
661impl quickcheck::Arbitrary for Date {
662fn arbitrary(g: &mut quickcheck::Gen) -> Date {
663let year = b::Year::arbitrary(g);
664let month = b::Month::arbitrary(g);
665let day = b::Day::arbitrary(g);
666 Date::new_constrain(year, month, day).unwrap()
667 }
668669fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Date>> {
670 alloc::boxed::Box::new(
671 (self.year(), self.month(), self.day()).shrink().filter_map(
672 |(year, month, day)| {
673 Date::new_constrain(year, month, day).ok()
674 },
675 ),
676 )
677 }
678}
679680/// A civil date represented by a number of days since the Unix epoch
681/// (1970-01-01).
682///
683/// The date can be positive (occurs after 1970-01-01) or negative (occurs
684/// before 1970-01-01). A zero value corresponds to 1970-01-01.
685///
686/// Unix epoch days can be infallibly converted to and from [`Date`] values.
687#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for UnixEpochDay {
}
#[automatically_derived]impl ::core::clone::Clone for UnixEpochDay {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<i32>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for UnixEpochDay { }Copy, #[automatically_derived]impl ::core::cmp::Eq for UnixEpochDay {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<i32>;
}
}Eq, #[automatically_derived]impl ::core::hash::Hash for UnixEpochDay {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.day, state)
}
}Hash, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
UnixEpochDay {
}
#[automatically_derived]impl ::core::cmp::PartialEq for UnixEpochDay {
#[inline]
fn eq(&self, other: &Self) -> bool { self.day == other.day }
}PartialEq, #[automatically_derived]impl ::core::cmp::PartialOrd for UnixEpochDay {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]impl ::core::cmp::Ord for UnixEpochDay {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.day, &other.day)
}
}Ord)]
688#[cfg_attr(feature = "defmt", derive(defmt::Format))]
689pub struct UnixEpochDay {
690 day: i32,
691}
692693impl UnixEpochDay {
694/// The minimum allowed Unix epoch day.
695 ///
696 /// This is guaranteed to be equivalent to [`Date::MIN`] when
697 /// converted to a Gregorian date.
698pub const MIN: UnixEpochDay = UnixEpochDay { day: b::UnixEpochDays::MIN };
699700/// The maximum allowed Unix epoch day.
701 ///
702 /// This is guaranteed to be equivalent to [`Date::MAX`] when
703 /// converted to a Gregorian date.
704pub const MAX: UnixEpochDay = UnixEpochDay { day: b::UnixEpochDays::MAX };
705706/// Creates a new Unix epoch day.
707 ///
708 /// The day given must correspond to a number of days (positive or
709 /// negative) since the Unix epoch (1970-01-01). A value of `0` corresponds
710 /// to `1970-01-01`.
711#[inline]
712pub const fn new(day: i32) -> Result<UnixEpochDay, RangeError> {
713let day = match b::UnixEpochDays::checkc(day as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::UnixEpochDays::checkc(day as i64));
714Ok(UnixEpochDay { day })
715 }
716717/// Returns the underlying day value.
718 ///
719 /// This is guaranteed to be in the [`UnixEpochDays`](b::UnixEpochDays)
720 /// range.
721#[inline]
722pub const fn day(self) -> i32 {
723self.day
724 }
725726/// Returns the day of the week for this epoch day.
727#[inline]
728pub const fn weekday(&self) -> Weekday {
729// Fast technique to obtain weekday 1..7 (Mon..Sun)
730 // directly via an add-mul-shift. Relies on the fact
731 // that the Unix epoch was a Thursday and that 7 is a
732 // Mersenne number.
733 //
734 // Accurate over a limited range (-89478489 to 89478489)
735 // which is -243014-03-21 (Tue) to 246953-10-13 (Sat).
736 // This exceeds Jiff's range.
737 //
738 // Ref: https://www.benjoffe.com/fast-day-of-week
739let result = Weekday::from_monday_one_offset({
740const M: u32 = {
741// MSRV(1.73): Just use `n.div_ceil` instead.
742const fn div_ceil(lhs: u64, rhs: u64) -> u64 {
743let d = lhs / rhs;
744let r = lhs % rhs;
745if r > 0 { d + 1 } else { d }
746 }
747748let n = div_ceil(1u64 << 32, 7) as u32;
749if !(n == 613_566_757) {
::core::panicking::panic("assertion failed: n == 613_566_757")
};assert!(n == 613_566_757);
750n751 };
752const Z: u32 = 0x90000000; // Magic add: see link above.
753let rd: u32 = self.day() as u32;
754 (rd.wrapping_mul(M).wrapping_add(Z) >> 29) as i8755 });
756match result {
Ok(val) => val,
Err(_) => {
::core::panicking::panic_fmt(format_args!("weekday must be in range 1..=7"));
}
}unwrapr!(result, "weekday must be in range 1..=7")757 }
758759/// Returns the "nth" weekday from this date, not including itself.
760 ///
761 /// The `nth` parameter can be positive or negative. A positive value
762 /// computes the "nth" weekday starting at the day after this date and
763 /// going forwards in time. A negative value computes the "nth" weekday
764 /// starting at the day before this date and going backwards in time.
765 ///
766 /// For example, if this date's weekday is a Sunday and the first Sunday is
767 /// asked for (that is, `date.nth_weekday(1, Weekday::Sunday)`), then the
768 /// result is a week from this date corresponding to the following Sunday.
769#[inline]
770pub const fn nth_weekday(
771self,
772 nth: i32,
773 weekday: Weekday,
774 ) -> Result<Date, RangeError> {
775// ref: http://howardhinnant.github.io/date_algorithms.html#next_weekday
776777let nth = match b::NthWeekday::checkc(nth as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::NthWeekday::checkc(nth as i64));
778if nth == 0 {
779return Err(b::NthWeekday::error().into_range_error());rbail!(b::NthWeekday::error());
780 } else if nth > 0 {
781let weekday_diff = weekday.since(self.weekday().next()) as i32;
782let diff = (nth - 1) * 7 + weekday_diff;
783let end = match self.checked_add(diff + 1) {
Ok(val) => val,
Err(err) => return Err(err),
}ctry!(self.checked_add(diff + 1));
784Ok(end.to_date())
785 } else {
786let weekday_diff = self.weekday().previous().since(weekday) as i32;
787// OK because of the range on `NthWeekday`.
788let nth = nth.abs();
789// OK because of the range on `NthWeekday`.
790let diff = -((nth - 1) * 7 + weekday_diff);
791let end = match self.checked_add(diff - 1) {
Ok(val) => val,
Err(err) => return Err(err),
}ctry!(self.checked_add(diff - 1));
792Ok(end.to_date())
793 }
794 }
795796/// Add the given number of days to this Unix epoch day.
797 ///
798 /// If this would overflow an `i32` or result in an out-of-bounds Unix
799 /// epoch day, then this returns an error.
800#[inline]
801pub const fn checked_add(
802self,
803 days: i32,
804 ) -> Result<UnixEpochDay, RangeError> {
805let day = match b::UnixEpochDays::checked_add(self.day(), days) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::UnixEpochDays::checked_add(self.day(), days));
806Ok(UnixEpochDay { day })
807 }
808809/// Subtracts the given number of days from this Unix epoch day.
810 ///
811 /// If this would overflow an `i32` or result in an out-of-bounds Unix
812 /// epoch day, then this returns an error.
813#[inline]
814pub const fn checked_sub(
815self,
816 days: i32,
817 ) -> Result<UnixEpochDay, RangeError> {
818let Some(days) = days.checked_neg() else {
819return Err(b::UnixEpochDays::error().into_range_error());rbail!(b::UnixEpochDays::error());
820 };
821self.checked_add(days)
822 }
823824/// Returns the number of days from this date until `other`.
825 ///
826 /// This routine never overflows because of the enforced range on
827 /// `UnixEpochDay` values.
828 ///
829 /// # Example
830 ///
831 /// ```
832 /// use jiff_core::civil::date;
833 ///
834 /// let date1 = date(2023, 7, 1).to_unix_epoch_day();
835 /// let date2 = date(2024, 7, 1).to_unix_epoch_day();
836 /// assert_eq!(366, date1.until(date2));
837 ///
838 /// // The value will be negative when the dates are flipped:
839 /// assert_eq!(-366, date2.until(date1));
840 /// ```
841 ///
842 /// # Example: overflow isn't possible
843 ///
844 /// Even when using the minimum or maximum values:
845 ///
846 /// ```
847 /// use jiff_core::civil::UnixEpochDay;
848 ///
849 /// assert_eq!(7_304_483, UnixEpochDay::MIN.until(UnixEpochDay::MAX));
850 /// assert_eq!(-7_304_483, UnixEpochDay::MAX.until(UnixEpochDay::MIN));
851 /// ```
852#[inline]
853pub const fn until(self, other: UnixEpochDay) -> i32 {
854 -self.since(other)
855 }
856857/// Returns the number of days from this date since `other`.
858 ///
859 /// This routine never overflows because of the enforced range on
860 /// `UnixEpochDay` values.
861 ///
862 /// # Example
863 ///
864 /// ```
865 /// use jiff_core::civil::date;
866 ///
867 /// let date1 = date(2023, 7, 1).to_unix_epoch_day();
868 /// let date2 = date(2024, 7, 1).to_unix_epoch_day();
869 /// assert_eq!(366, date2.since(date1));
870 ///
871 /// // The value will be negative when the dates are flipped:
872 /// assert_eq!(-366, date1.since(date2));
873 /// ```
874 ///
875 /// # Example: overflow isn't possible
876 ///
877 /// Even when using the minimum or maximum values:
878 ///
879 /// ```
880 /// use jiff_core::civil::UnixEpochDay;
881 ///
882 /// assert_eq!(7_304_483, UnixEpochDay::MAX.since(UnixEpochDay::MIN));
883 /// ```
884#[inline]
885pub const fn since(self, other: UnixEpochDay) -> i32 {
886self.day() - other.day()
887 }
888889/// Converts this Unix epoch day to a Gregorian date.
890#[inline]
891 #[allow(non_upper_case_globals, non_snake_case)] // to mimic source
892pub const fn to_date(self) -> Date {
893// This is Neri-Schneider. There's no branching or divisions.
894 //
895 // Ref: <https://github.com/cassioneri/eaf/blob/684d3cc32d14eee371d0abe4f683d6d6a49ed5c1/algorithms/neri_schneider.hpp#L40C3-L40C34>
896const s: u32 = 82;
897const K: u32 = 719468 + 146097 * s;
898const L: u32 = 400 * s;
899900let N_U = self.day as u32;
901let N = N_U.wrapping_add(K);
902903let N_1 = 4 * N + 3;
904let C = N_1 / 146097;
905let N_C = (N_1 % 146097) / 4;
906907let N_2 = 4 * N_C + 3;
908let P_2 = 2939745 * (N_2as u64);
909let Z = (P_2 / 4294967296) as u32;
910let N_Y = (P_2 % 4294967296) as u32 / 2939745 / 4;
911let Y = 100 * C + Z;
912913let N_3 = 2141 * N_Y + 197913;
914let M = N_3 / 65536;
915let D = (N_3 % 65536) / 2141;
916917let J = N_Y >= 306;
918let year = Y.wrapping_sub(L).wrapping_add(Jas u32) as i16;
919let month = (if J { M - 12 } else { M }) as i8;
920let day = (D + 1) as i8;
921Date { year, month, day }
922 }
923}
924925impl core::fmt::Debugfor UnixEpochDay {
926fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
927f.debug_tuple("UnixEpochDay").field(&self.day()).finish()
928 }
929}
930931/// Returns the number of days between two `UnixEpochDay` values.
932///
933/// This routine never overflows because of the enforced range on
934/// `UnixEpochDay` values.
935///
936/// # Example
937///
938/// ```
939/// use jiff_core::civil::date;
940///
941/// let date1 = date(2023, 7, 1).to_unix_epoch_day();
942/// let date2 = date(2024, 7, 1).to_unix_epoch_day();
943/// assert_eq!(366, date2 - date1);
944///
945/// // The value will be negative when the dates are flipped:
946/// assert_eq!(-366, date1 - date2);
947/// ```
948///
949/// # Example: overflow isn't possible
950///
951/// Even when using the minimum or maximum values:
952///
953/// ```
954/// use jiff_core::civil::UnixEpochDay;
955///
956/// assert_eq!(7_304_483, UnixEpochDay::MAX - UnixEpochDay::MIN);
957/// ```
958impl core::ops::Subfor UnixEpochDay {
959type Output = i32;
960961#[inline]
962fn sub(self, rhs: UnixEpochDay) -> i32 {
963self.since(rhs)
964 }
965}
966967/// An ISO 8601 civil week date.
968///
969/// An ISO 8601 civil week date can be infallibly converted to and from
970/// Gregorian [`Date`] values.
971#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for ISOWeekDate {
}
#[automatically_derived]impl ::core::clone::Clone for ISOWeekDate {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<i16>;
let _: ::core::clone::AssertParamIsClone<i8>;
let _: ::core::clone::AssertParamIsClone<Weekday>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for ISOWeekDate { }Copy, #[automatically_derived]impl ::core::cmp::Eq for ISOWeekDate {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<i16>;
let _: ::core::cmp::AssertParamIsEq<i8>;
let _: ::core::cmp::AssertParamIsEq<Weekday>;
}
}Eq, #[automatically_derived]impl ::core::hash::Hash for ISOWeekDate {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.year, state);
::core::hash::Hash::hash(&self.week, state);
::core::hash::Hash::hash(&self.weekday, state)
}
}Hash, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
ISOWeekDate {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ISOWeekDate {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.year == other.year && self.week == other.week &&
self.weekday == other.weekday
}
}PartialEq)]
972#[cfg_attr(feature = "defmt", derive(defmt::Format))]
973pub struct ISOWeekDate {
974 year: i16,
975 week: i8,
976 weekday: Weekday,
977}
978979impl ISOWeekDate {
980/// The minimum representable ISO week date.
981pub const MIN: ISOWeekDate = ISOWeekDate {
982 year: b::ISOYear::MIN,
983 week: b::ISOWeek::MIN,
984 weekday: Weekday::Monday,
985 };
986987/// The maximum representable ISO week date.
988pub const MAX: ISOWeekDate = ISOWeekDate {
989 year: b::ISOYear::MAX,
990// Technical max is 52, but 9999 is not a leap year.
991week: 52,
992 weekday: Weekday::Friday,
993 };
994995/// The zero ISO 8601 week date. It is the first day of the zeroth year.
996pub const ZERO: ISOWeekDate =
997ISOWeekDate { year: 0, week: 1, weekday: Weekday::Monday };
998999/// Create a new ISO week date from its constituent parts.
1000 ///
1001 /// If the week date is invalid or any of the values are out of their
1002 /// supported ranges, then an error is returned.
1003#[inline]
1004pub const fn new(
1005 year: i16,
1006 week: i8,
1007 weekday: Weekday,
1008 ) -> Result<ISOWeekDate, RangeError> {
1009let year = match b::ISOYear::checkc(year as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::ISOYear::checkc(year as i64));
1010let week = match b::ISOWeek::checkc(week as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::ISOWeek::checkc(week as i64));
10111012// All combinations of years, weeks and weekdays allowed by our
1013 // range types are valid ISO week dates with one exception: a week
1014 // number of 53 is only valid for "long" years. Or years with an ISO
1015 // leap week. It turns out this only happens when the last day of the
1016 // year is a Thursday.
1017 //
1018 // Note that if the ranges in this crate are changed, this could be
1019 // a little trickier if the range of ISOYear is different from Year.
1020if true {
if !(b::Year::MIN == b::ISOYear::MIN) {
::core::panicking::panic("assertion failed: b::Year::MIN == b::ISOYear::MIN")
};
};debug_assert!(b::Year::MIN == b::ISOYear::MIN);
1021if true {
if !(b::Year::MAX == b::ISOYear::MAX) {
::core::panicking::panic("assertion failed: b::Year::MAX == b::ISOYear::MAX")
};
};debug_assert!(b::Year::MAX == b::ISOYear::MAX);
1022if week == 53 && !civil::is_long_iso_week_year(year) {
1023return Err(b::ISOWeek::error().into_range_error());rbail!(b::ISOWeek::error());
1024 }
1025// And also, the maximum Date constrains what we can utter with
1026 // ISOWeekDate so that we can preserve infallible conversions between
1027 // them. So since 9999-12-31 maps to 9999 W52 Friday, it follows that
1028 // Saturday and Sunday are not allowed when the year is at the maximum
1029 // value. So reject them.
1030 //
1031 // We don't need to worry about the minimum because the minimum date
1032 // (-9999-01-01) corresponds also to the minimum possible combination
1033 // of an ISO week date's fields: -9999 W01 Monday. Nice.
1034if year == b::ISOYear::MAX1035 && week == 52
1036&& weekday.to_monday_zero_offset()
1037 > Weekday::Friday.to_monday_zero_offset()
1038 {
1039return Err(b::WeekdayMondayOne::error().into_range_error());rbail!(b::WeekdayMondayOne::error());
1040 }
1041Ok(ISOWeekDate { year, week, weekday })
1042 }
10431044/// Like `ISOWeekDate::new`, but constrains out-of-bounds week and weekday
1045 /// values to their closest valid equivalent.
1046 ///
1047 /// For example, given `9999 W52 Saturday`, this will return
1048 /// `9999 W52 Friday`.
1049 ///
1050 /// This still returns an error when `week < 1` or when `year` is invalid.
1051#[inline]
1052pub const fn new_constrain(
1053 year: i16,
1054mut week: i8,
1055mut weekday: Weekday,
1056 ) -> Result<ISOWeekDate, RangeError> {
1057let year = match b::ISOYear::checkc(year as i64) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::ISOYear::checkc(year as i64));
1058if week < 1 {
1059return Err(b::ISOWeek::error().into_range_error());rbail!(b::ISOWeek::error());
1060 }
1061let weeks_in_year =
1062if civil::is_long_iso_week_year(year) { 53 } else { 52 };
1063week = if week <= weeks_in_year { week } else { weeks_in_year };
1064if year == b::ISOYear::MAX1065 && week == 52
1066&& weekday.to_monday_zero_offset()
1067 > Weekday::Friday.to_monday_zero_offset()
1068 {
1069weekday = Weekday::Friday;
1070 }
1071Ok(ISOWeekDate { year, week, weekday })
1072 }
10731074/// Returns the year component of this ISO 8601 week date.
1075 ///
1076 /// The value returned is guaranteed to be in the range specified by
1077 /// [`ISOYear`](crate::bounds::ISOYear).
1078#[inline]
1079pub const fn year(self) -> i16 {
1080self.year
1081 }
10821083/// Returns the week number component of this ISO 8601 week date.
1084 ///
1085 /// The value returned is guaranteed to be in the range specified by
1086 /// [`ISOWeek`](crate::bounds::ISOWeek).
1087#[inline]
1088pub const fn week(self) -> i8 {
1089self.week
1090 }
10911092/// Returns the weekday component of this ISO 8601 week date.
1093#[inline]
1094pub const fn weekday(self) -> Weekday {
1095self.weekday
1096 }
10971098/// Returns the ISO 8601 week date corresponding to the first day in the
1099 /// week of this week date. The date returned is guaranteed to have a
1100 /// weekday of [`Weekday::Monday`].
1101 ///
1102 /// # Errors
1103 ///
1104 /// Since `-9999-01-01` falls on a Monday, it follows that the minimum
1105 /// supported Gregorian date is exactly equivalent to the minimum supported
1106 /// ISO 8601 week date. This means that this routine can never actually
1107 /// fail, but only insomuch as the minimums line up. For that reason, and
1108 /// for consistency with [`ISOWeekDate::last_of_week`], the API is
1109 /// fallible.
1110#[inline]
1111pub const fn first_of_week(self) -> Result<ISOWeekDate, RangeError> {
1112// I believe this can never return an error because `Monday` is in
1113 // bounds for all possible year-and-week combinations. This is *only*
1114 // because -9999-01-01 corresponds to -9999-W01-Monday. Which is kinda
1115 // lucky. And I guess if we ever change the ranges, this could become
1116 // fallible.
1117Ok(ISOWeekDate { weekday: Weekday::Monday, ..self })
1118 }
11191120/// Returns the ISO 8601 week date corresponding to the last day in the
1121 /// week of this week date. The date returned is guaranteed to have a
1122 /// weekday of [`Weekday::Sunday`].
1123 ///
1124 /// # Errors
1125 ///
1126 /// This can return an error if the last day of the week exceeds Jiff's
1127 /// maximum Gregorian date of `9999-12-31`. It turns out this can happen
1128 /// since `9999-12-31` falls on a Friday.
1129#[inline]
1130pub const fn last_of_week(self) -> Result<ISOWeekDate, RangeError> {
1131ISOWeekDate::new(self.year(), self.week(), Weekday::Sunday)
1132 }
11331134/// Returns the ISO 8601 week date corresponding to the first day in the
1135 /// year of this week date. The date returned is guaranteed to have a
1136 /// weekday of [`Weekday::Monday`].
1137 ///
1138 /// # Errors
1139 ///
1140 /// Since `-9999-01-01` falls on a Monday, it follows that the minimum
1141 /// support Gregorian date is exactly equivalent to the minimum supported
1142 /// ISO 8601 week date. This means that this routine can never actually
1143 /// fail, but only insomuch as the minimums line up. For that reason, and
1144 /// for consistency with [`ISOWeekDate::last_of_year`], the API is
1145 /// fallible.
1146#[inline]
1147pub const fn first_of_year(self) -> Result<ISOWeekDate, RangeError> {
1148// I believe this can never return an error because `Monday` is in
1149 // bounds for all possible year-and-week combinations. This is *only*
1150 // because -9999-01-01 corresponds to -9999-W01-Monday. Which is kinda
1151 // lucky. And I guess if we ever change the ranges, this could become
1152 // fallible.
1153Ok(ISOWeekDate { week: 1, weekday: Weekday::Monday, ..self })
1154 }
11551156/// Returns the ISO 8601 week date corresponding to the last day in the
1157 /// year of this week date. The date returned is guaranteed to have a
1158 /// weekday of [`Weekday::Sunday`].
1159 ///
1160 /// # Errors
1161 ///
1162 /// This can return an error if the last day of the year exceeds Jiff's
1163 /// maximum Gregorian date of `9999-12-31`. It turns out this can happen
1164 /// since `9999-12-31` falls on a Friday.
1165#[inline]
1166pub const fn last_of_year(self) -> Result<ISOWeekDate, RangeError> {
1167ISOWeekDate::new(self.year(), self.weeks_in_year(), Weekday::Sunday)
1168 }
11691170/// Returns the total number of days in the year of this ISO 8601 week
1171 /// date.
1172 ///
1173 /// It is guaranteed that the value returned is either 364 or 371. The
1174 /// latter case occurs precisely when [`ISOWeekDate::in_long_year`]
1175 /// returns `true`.
1176#[inline]
1177pub const fn days_in_year(self) -> i16 {
1178if self.in_long_year() { 371 } else { 364 }
1179 }
11801181/// Returns the total number of weeks in the year of this ISO 8601 week
1182 /// date.
1183 ///
1184 /// It is guaranteed that the value returned is either 52 or 53. The
1185 /// latter case occurs precisely when [`ISOWeekDate::in_long_year`]
1186 /// returns `true`.
1187#[inline]
1188pub const fn weeks_in_year(self) -> i8 {
1189 civil::weeks_in_iso_week_year(self.year())
1190 }
11911192/// Returns true if and only if the year of this week date is a "long"
1193 /// year.
1194 ///
1195 /// A long year is one that contains precisely 53 weeks. All other years
1196 /// contain precisely 52 weeks.
1197#[inline]
1198pub const fn in_long_year(self) -> bool {
1199 civil::is_long_iso_week_year(self.year())
1200 }
12011202/// Returns the ISO 8601 date immediately following this one.
1203 ///
1204 /// # Errors
1205 ///
1206 /// This returns an error when this date is the maximum value.
1207#[inline]
1208pub const fn tomorrow(self) -> Result<ISOWeekDate, RangeError> {
1209// The maximum week date is `9999-W52-5`, which is a Friday. It doesn't
1210 // end on a Sunday, so adjusting the logic below to check for it is
1211 // a bit weird. So we just check here.
1212if self.year() == ISOWeekDate::MAX.year()
1213 && self.week() == ISOWeekDate::MAX.week()
1214 && #[allow(non_exhaustive_omitted_patterns)] match self.weekday() {
Weekday::Friday => true,
_ => false,
}matches!(self.weekday(), Weekday::Friday)1215 {
1216return Err(b::ISOYear::error().into_range_error());rbail!(b::ISOYear::error());
1217 }
1218// I suppose we could probably implement this in a more efficient
1219 // manner by avoiding the roundtrip through Gregorian dates.
1220 // self.to_date().tomorrow().map(|d| d.to_iso_week_date())
1221if #[allow(non_exhaustive_omitted_patterns)] match self.weekday() {
Weekday::Sunday => true,
_ => false,
}matches!(self.weekday(), Weekday::Sunday) {
1222if self.week() >= 52 && self.week() == self.weeks_in_year() {
1223let year = self.year() + 1;
1224return Ok(ISOWeekDate {
1225year,
1226 week: 1,
1227 weekday: Weekday::Monday,
1228 });
1229 }
1230let week = self.week() + 1;
1231return Ok(ISOWeekDate { week, weekday: Weekday::Monday, ..self });
1232 }
1233Ok(ISOWeekDate { weekday: self.weekday().next(), ..self })
1234 }
12351236/// Returns the ISO 8601 week date immediately preceding this one.
1237 ///
1238 /// # Errors
1239 ///
1240 /// This returns an error when this date is the minimum value.
1241#[inline]
1242pub fn yesterday(self) -> Result<ISOWeekDate, RangeError> {
1243if #[allow(non_exhaustive_omitted_patterns)] match self.weekday() {
Weekday::Monday => true,
_ => false,
}matches!(self.weekday(), Weekday::Monday) {
1244if self.week() == 1 {
1245let year = match b::ISOYear::checked_add(self.year(), -1) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::ISOYear::checked_add(self.year(), -1));
1246let week = civil::weeks_in_iso_week_year(year);
1247return Ok(ISOWeekDate {
1248year,
1249week,
1250 weekday: Weekday::Sunday,
1251 });
1252 }
1253let week = self.week() - 1;
1254return Ok(ISOWeekDate { week, weekday: Weekday::Sunday, ..self });
1255 }
1256Ok(ISOWeekDate { weekday: self.weekday().previous(), ..self })
1257 }
12581259/// Converts this ISO 8601 week date to a Unix epoch day.
1260#[inline]
1261pub const fn to_unix_epoch_day(self) -> UnixEpochDay {
1262let epoch_day_year = iso_week_start_from_year(self.year());
1263let week = self.week() as i32;
1264let weekday = self.weekday().to_monday_zero_offset() as i32;
1265match epoch_day_year.checked_add(((week - 1) * 7) + weekday) {
Ok(val) => val,
Err(_) => {
::core::panicking::panic_fmt(format_args!("all valid ISO 8601 dates convert to a valid Unix epoch day"));
}
}unwrapr!(
1266 epoch_day_year.checked_add(((week - 1) * 7) + weekday),
1267"all valid ISO 8601 dates convert to a valid Unix epoch day",
1268 )1269 }
12701271/// Converts this ISO 8601 week date to a Gregorian date.
1272#[inline]
1273pub const fn to_date(self) -> Date {
1274self.to_unix_epoch_day().to_date()
1275 }
1276}
12771278impl core::fmt::Debugfor ISOWeekDate {
1279fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1280f.write_fmt(format_args!("{0:04}-W{1:02}-{2}", self.year, self.week,
self.weekday.to_monday_one_offset()))write!(
1281f,
1282"{:04}-W{:02}-{}",
1283self.year,
1284self.week,
1285self.weekday.to_monday_one_offset()
1286 )1287 }
1288}
12891290impl Ordfor ISOWeekDate {
1291#[inline]
1292fn cmp(&self, other: &ISOWeekDate) -> core::cmp::Ordering {
1293 (self.year(), self.week(), self.weekday().to_monday_one_offset()).cmp(
1294&(
1295other.year(),
1296other.week(),
1297other.weekday().to_monday_one_offset(),
1298 ),
1299 )
1300 }
1301}
13021303impl PartialOrdfor ISOWeekDate {
1304#[inline]
1305fn partial_cmp(&self, other: &ISOWeekDate) -> Option<core::cmp::Ordering> {
1306Some(self.cmp(other))
1307 }
1308}
13091310/// Returns the Unix epoch day corresponding to the first day in the ISO 8601
1311/// week year given.
1312///
1313/// Callers must ensure that `year` is in the range specified by
1314/// [`Year`](b::Year).
1315///
1316/// Ref: http://howardhinnant.github.io/date_algorithms.html
1317const fn iso_week_start_from_year(year: i16) -> UnixEpochDay {
1318if true {
if !b::Year::checkc(year as i64).is_ok() {
::core::panicking::panic("assertion failed: b::Year::checkc(year as i64).is_ok()")
};
};debug_assert!(b::Year::checkc(year as i64).is_ok());
1319// A week's year always corresponds to the Gregorian year in which the
1320 // Thursday of that week falls. Therefore, Jan 4 is *always* in the first
1321 // week of any ISO week year.
1322let epoch_day_in_first_week =
1323Date { year, month: 1, day: 4 }.to_unix_epoch_day();
1324// The start of the first week is a Monday, so find the number of days
1325 // since Monday from a date that we know is in the first ISO week of
1326 // `year`.
1327let diff_from_monday =
1328epoch_day_in_first_week.weekday().since(Weekday::Monday);
1329// OK because `diff_from_monday` is never bigger than 6 and is always
1330 // positive. Therefore, the only case where this could plausibly fail
1331 // is when `year=-9999`. But in that specific case, -9999-01-01 is on a
1332 // Monday, so the diff is guaranteed to give us the minimal Unix epoch
1333 // day value.
1334match epoch_day_in_first_week.checked_sub(diff_from_monday as i32) {
Ok(val) => val,
Err(_) => {
::core::panicking::panic_fmt(format_args!("valid Unix epoch day"));
}
}unwrapr!(
1335 epoch_day_in_first_week.checked_sub(diff_from_monday as i32),
1336"valid Unix epoch day"
1337)1338}
13391340#[cfg(feature = "arbitrary")]
1341impl<'a> arbitrary::Arbitrary<'a> for ISOWeekDate {
1342fn arbitrary(
1343 u: &mut arbitrary::Unstructured<'a>,
1344 ) -> arbitrary::Result<ISOWeekDate> {
1345let year = u.int_in_range(b::ISOYear::MIN..=b::ISOYear::MAX)?;
1346let week = u.int_in_range(b::ISOWeek::MIN..=b::ISOWeek::MAX)?;
1347let weekday = Weekday::arbitrary(u)?;
1348Ok(ISOWeekDate::new_constrain(year, week, weekday).unwrap())
1349 }
13501351fn size_hint(depth: usize) -> (usize, Option<usize>) {
1352 arbitrary::size_hint::and_all(&[
1353 <i16 as arbitrary::Arbitrary>::size_hint(depth),
1354 <i8 as arbitrary::Arbitrary>::size_hint(depth),
1355 <Weekday as arbitrary::Arbitrary>::size_hint(depth),
1356 ])
1357 }
1358}
13591360#[cfg(test)]
1361impl quickcheck::Arbitrary for ISOWeekDate {
1362fn arbitrary(g: &mut quickcheck::Gen) -> ISOWeekDate {
1363let year = b::ISOYear::arbitrary(g);
1364let week = b::ISOWeek::arbitrary(g);
1365let weekday = Weekday::arbitrary(g);
1366 ISOWeekDate::new_constrain(year, week, weekday).unwrap()
1367 }
13681369fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = ISOWeekDate>> {
1370 alloc::boxed::Box::new(
1371 (self.year(), self.week(), self.weekday()).shrink().filter_map(
1372 |(year, week, weekday)| {
1373 ISOWeekDate::new_constrain(year, week, weekday).ok()
1374 },
1375 ),
1376 )
1377 }
1378}
13791380#[cfg(test)]
1381mod tests {
1382use super::*;
13831384fn date(year: i16, month: i8, day: i8) -> Date {
1385 Date::new(year, month, day).unwrap()
1386 }
13871388fn week_date(year: i16, week: i8, weekday: Weekday) -> ISOWeekDate {
1389 ISOWeekDate::new(year, week, weekday).unwrap()
1390 }
13911392#[test]
1393fn iso_week_date_new_constrain() {
1394assert_eq!(
1395 ISOWeekDate::new_constrain(2024, 60, Weekday::Monday).unwrap(),
1396 week_date(2024, 52, Weekday::Monday),
1397 );
1398 }
13991400#[test]
1401fn date_min() {
1402assert_eq!(Date::MIN, date(-9999, 1, 1));
1403 }
14041405#[test]
1406fn date_max() {
1407assert_eq!(Date::MAX, date(9999, 12, 31));
1408 }
14091410#[test]
1411fn unix_epoch_to_date_and_back_again_min_to_max() {
1412for i in 0.. {
1413let Ok(epoch_day) = UnixEpochDay::MIN.checked_add(i) else {
1414break;
1415 };
1416let date = epoch_day.to_date();
1417let got = date.to_unix_epoch_day();
1418assert_eq!(epoch_day, got);
1419 }
1420 }
14211422#[test]
1423fn unix_epoch_to_date_and_back_again_max_to_min() {
1424for i in 0.. {
1425let Ok(epoch_day) = UnixEpochDay::MAX.checked_sub(i) else {
1426break;
1427 };
1428let date = epoch_day.to_date();
1429let got = date.to_unix_epoch_day();
1430assert_eq!(epoch_day, got);
1431 }
1432 }
14331434#[test]
1435fn date_to_unix_epoch_and_back_again() {
1436for year in b::Year::MIN..=b::Year::MAX {
1437for month in b::Month::MIN..=b::Month::MAX {
1438for day in b::Day::MIN..=civil::days_in_month(year, month) {
1439let d = date(year, month, day);
1440let epoch_day = d.to_unix_epoch_day();
1441let got = epoch_day.to_date();
1442assert_eq!(d, got);
1443 }
1444 }
1445 }
1446 }
14471448#[test]
1449fn date_to_week_date_and_back_again() {
1450for year in b::Year::MIN..=b::Year::MAX {
1451for month in b::Month::MIN..=b::Month::MAX {
1452for day in b::Day::MIN..=civil::days_in_month(year, month) {
1453let d = date(year, month, day);
1454let wd = d.to_iso_week_date();
1455let got = wd.to_date();
1456assert_eq!(d, got);
1457 }
1458 }
1459 }
1460 }
14611462#[test]
1463fn date_to_day_of_year_and_back_again() {
1464for year in b::Year::MIN..=b::Year::MAX {
1465for month in b::Month::MIN..=b::Month::MAX {
1466for day in b::Day::MIN..=civil::days_in_month(year, month) {
1467let d = date(year, month, day);
1468let doy = d.day_of_year();
1469let got = Date::from_day_of_year(year, doy);
1470assert_eq!(Ok(d), got);
1471 }
1472 }
1473 }
1474 }
14751476#[test]
1477fn day_of_year_in_non_leap_year() {
1478let year = 2026;
1479let mut doy = 1;
1480for month in b::Month::MIN..=b::Month::MAX {
1481for day in b::Day::MIN..=civil::days_in_month(year, month) {
1482let d = Date::from_day_of_year(year, doy).unwrap();
1483assert_eq!(d, date(year, month, day));
1484assert_eq!(d.day_of_year(), doy);
1485 doy += 1;
1486 }
1487 }
1488 }
14891490#[test]
1491fn day_of_year_in_leap_year() {
1492let year = 2024;
1493let mut doy = 1;
1494for month in b::Month::MIN..=b::Month::MAX {
1495for day in b::Day::MIN..=civil::days_in_month(year, month) {
1496let d = Date::from_day_of_year(year, doy).unwrap();
1497assert_eq!(d, date(year, month, day));
1498assert_eq!(d.day_of_year(), doy);
1499 doy += 1;
1500 }
1501 }
1502 }
15031504#[test]
1505fn day_of_year_no_leap_in_non_leap_year() {
1506let year = 2026;
1507let mut doy = 1;
1508for month in b::Month::MIN..=b::Month::MAX {
1509for day in b::Day::MIN..=civil::days_in_month(year, month) {
1510let d = Date::from_day_of_year_no_leap(year, doy).unwrap();
1511assert_eq!(d, date(year, month, day));
1512assert_eq!(d.day_of_year_no_leap(), Some(doy));
1513 doy += 1;
1514 }
1515 }
1516 }
15171518#[test]
1519fn day_of_year_no_leap_in_leap_year() {
1520let year = 2024;
1521let mut doy = 1;
1522for month in b::Month::MIN..=b::Month::MAX {
1523for day in b::Day::MIN..=civil::days_in_month(year, month) {
1524if month == 2 && day == 29 {
1525continue;
1526 }
1527let d = Date::from_day_of_year_no_leap(year, doy).unwrap();
1528assert_eq!(d, date(year, month, day));
1529assert_eq!(d.day_of_year_no_leap(), Some(doy));
1530 doy += 1;
1531 }
1532 }
1533 }
15341535#[test]
1536fn date_to_day_of_year_no_leap_and_back_again() {
1537for year in b::Year::MIN..=b::Year::MAX {
1538for month in b::Month::MIN..=b::Month::MAX {
1539for day in b::Day::MIN..=civil::days_in_month(year, month) {
1540if month == 2 && day == 29 {
1541continue;
1542 }
1543let d = date(year, month, day);
1544let doy = d.day_of_year_no_leap().unwrap();
1545let got = Date::from_day_of_year_no_leap(year, doy);
1546assert_eq!(Ok(d), got);
1547 }
1548 }
1549 }
1550 }
15511552#[test]
1553fn unix_epoch_day_weekday() {
1554let mk = |day| date(2026, 2, day).weekday();
1555assert_eq!(mk(14), Weekday::Saturday);
1556assert_eq!(mk(15), Weekday::Sunday);
1557assert_eq!(mk(16), Weekday::Monday);
1558assert_eq!(mk(17), Weekday::Tuesday);
1559assert_eq!(mk(18), Weekday::Wednesday);
1560assert_eq!(mk(19), Weekday::Thursday);
1561assert_eq!(mk(20), Weekday::Friday);
1562assert_eq!(mk(21), Weekday::Saturday);
1563 }
15641565#[test]
1566fn first_of_last_of() {
1567for year in b::Year::MIN..=b::Year::MAX {
1568for month in b::Month::MIN..=b::Month::MAX {
1569for day in b::Day::MIN..=civil::days_in_month(year, month) {
1570let d = date(year, month, day);
15711572assert_eq!(d.first_of_month(), date(year, month, 1));
1573assert_eq!(
1574 d.last_of_month(),
1575 date(year, month, d.days_in_month())
1576 );
15771578assert_eq!(d.first_of_year(), date(year, 1, 1));
1579assert_eq!(d.last_of_year(), date(year, 12, 31));
1580 }
1581 }
1582 }
1583 }
15841585#[test]
1586fn days_in() {
1587for year in b::Year::MIN..=b::Year::MAX {
1588for month in b::Month::MIN..=b::Month::MAX {
1589for day in b::Day::MIN..=civil::days_in_month(year, month) {
1590let d = date(year, month, day);
15911592assert!([365, 366].contains(&d.days_in_year()));
1593assert!([28, 29, 30, 31].contains(&d.days_in_month()));
1594 }
1595 }
1596 }
1597 }
15981599#[test]
1600fn nth_weekday_of_month_various() {
1601let d1 = date(2017, 3, 1);
1602let wday = Weekday::Friday;
1603assert_eq!(d1.nth_weekday_of_month(2, wday), Ok(date(2017, 3, 10)));
16041605let d1 = date(2024, 3, 1);
1606let wday = Weekday::Thursday;
1607assert_eq!(d1.nth_weekday_of_month(-1, wday), Ok(date(2024, 3, 28)));
16081609let d1 = date(2024, 3, 25);
1610let wday = Weekday::Monday;
1611assert!(d1.nth_weekday_of_month(5, wday).is_err());
1612assert!(d1.nth_weekday_of_month(-5, wday).is_err());
16131614let d1 = date(1998, 1, 1);
1615let wday = Weekday::Saturday;
1616assert_eq!(d1.nth_weekday_of_month(5, wday), Ok(date(1998, 1, 31)));
1617 }
16181619#[test]
1620fn nth_weekday_of_month_errors() {
1621let d = date(2017, 3, 1);
1622let wday = Weekday::Tuesday;
16231624assert!(d.nth_weekday_of_month(0, wday).is_err());
1625assert!(d.nth_weekday_of_month(5, wday).is_err());
1626assert!(d.nth_weekday_of_month(-5, wday).is_err());
1627assert!(d.nth_weekday_of_month(6, wday).is_err());
1628assert!(d.nth_weekday_of_month(-6, wday).is_err());
1629assert!(d.nth_weekday_of_month(i8::MIN, wday).is_err());
1630assert!(d.nth_weekday_of_month(i8::MAX, wday).is_err());
16311632assert_eq!(
1633 d.nth_weekday_of_month(5, Weekday::Friday),
1634Ok(date(2017, 3, 31))
1635 );
1636assert_eq!(
1637 d.nth_weekday_of_month(-5, Weekday::Friday),
1638Ok(date(2017, 3, 3))
1639 );
1640 }
16411642#[test]
1643fn nth_weekday_of_month_near_minimum_date() {
1644let d = date(-9999, 1, 1);
16451646assert_eq!(
1647 d.nth_weekday_of_month(1, Weekday::Monday),
1648Ok(date(-9999, 1, 1))
1649 );
1650assert_eq!(
1651 d.nth_weekday_of_month(2, Weekday::Monday),
1652Ok(date(-9999, 1, 8))
1653 );
1654assert_eq!(
1655 d.nth_weekday_of_month(3, Weekday::Monday),
1656Ok(date(-9999, 1, 15))
1657 );
1658assert_eq!(
1659 d.nth_weekday_of_month(4, Weekday::Monday),
1660Ok(date(-9999, 1, 22))
1661 );
1662assert_eq!(
1663 d.nth_weekday_of_month(5, Weekday::Monday),
1664Ok(date(-9999, 1, 29))
1665 );
16661667assert_eq!(
1668 d.nth_weekday_of_month(-5, Weekday::Monday),
1669Ok(date(-9999, 1, 1))
1670 );
1671assert_eq!(
1672 d.nth_weekday_of_month(-4, Weekday::Monday),
1673Ok(date(-9999, 1, 8))
1674 );
1675assert_eq!(
1676 d.nth_weekday_of_month(-3, Weekday::Monday),
1677Ok(date(-9999, 1, 15))
1678 );
1679assert_eq!(
1680 d.nth_weekday_of_month(-2, Weekday::Monday),
1681Ok(date(-9999, 1, 22))
1682 );
1683assert_eq!(
1684 d.nth_weekday_of_month(-1, Weekday::Monday),
1685Ok(date(-9999, 1, 29))
1686 );
1687 }
16881689#[test]
1690fn nth_weekday_of_month_near_maximum_date() {
1691let d = date(9999, 12, 1);
16921693assert_eq!(
1694 d.nth_weekday_of_month(1, Weekday::Friday),
1695Ok(date(9999, 12, 3))
1696 );
1697assert_eq!(
1698 d.nth_weekday_of_month(2, Weekday::Friday),
1699Ok(date(9999, 12, 10))
1700 );
1701assert_eq!(
1702 d.nth_weekday_of_month(3, Weekday::Friday),
1703Ok(date(9999, 12, 17))
1704 );
1705assert_eq!(
1706 d.nth_weekday_of_month(4, Weekday::Friday),
1707Ok(date(9999, 12, 24))
1708 );
1709assert_eq!(
1710 d.nth_weekday_of_month(5, Weekday::Friday),
1711Ok(date(9999, 12, 31))
1712 );
17131714assert_eq!(
1715 d.nth_weekday_of_month(-5, Weekday::Friday),
1716Ok(date(9999, 12, 3))
1717 );
1718assert_eq!(
1719 d.nth_weekday_of_month(-4, Weekday::Friday),
1720Ok(date(9999, 12, 10))
1721 );
1722assert_eq!(
1723 d.nth_weekday_of_month(-3, Weekday::Friday),
1724Ok(date(9999, 12, 17))
1725 );
1726assert_eq!(
1727 d.nth_weekday_of_month(-2, Weekday::Friday),
1728Ok(date(9999, 12, 24))
1729 );
1730assert_eq!(
1731 d.nth_weekday_of_month(-1, Weekday::Friday),
1732Ok(date(9999, 12, 31))
1733 );
1734 }
17351736#[test]
1737fn nth_weekday_of_month_every_month_has_four_weekdays() {
1738for year in b::Year::MIN..=b::Year::MAX {
1739for month in b::Month::MIN..=b::Month::MAX {
1740let d = date(year, month, 1);
1741for weekday in Weekday::Sunday.cycle_forward().take(7) {
1742for nth in [-4, -3, -2, -1, 1, 2, 3, 4] {
1743assert!(d.nth_weekday_of_month(nth, weekday).is_ok());
1744// never valid
1745assert!(d.nth_weekday_of_month(0, weekday).is_err());
1746assert!(d.nth_weekday_of_month(6, weekday).is_err());
1747assert!(d.nth_weekday_of_month(-6, weekday).is_err());
1748 }
1749 }
1750 }
1751 }
1752 }
17531754#[test]
1755fn nth_weekday_various() {
1756let d = date(2024, 3, 10);
17571758assert_eq!(d.nth_weekday(1, Weekday::Monday), Ok(date(2024, 3, 11)));
1759assert_eq!(d.nth_weekday(1, Weekday::Sunday), Ok(date(2024, 3, 17)));
1760assert_eq!(d.nth_weekday(2, Weekday::Thursday), Ok(date(2024, 3, 21)));
17611762assert_eq!(d.nth_weekday(-1, Weekday::Monday), Ok(date(2024, 3, 4)));
1763assert_eq!(d.nth_weekday(-1, Weekday::Sunday), Ok(date(2024, 3, 3)));
1764assert_eq!(
1765 d.nth_weekday(-2, Weekday::Thursday),
1766Ok(date(2024, 2, 29))
1767 );
17681769let d = date(9999, 12, 24);
1770assert_eq!(d.nth_weekday(1, Weekday::Friday), Ok(date(9999, 12, 31)));
1771let d = date(9999, 12, 30);
1772assert_eq!(d.nth_weekday(1, Weekday::Friday), Ok(date(9999, 12, 31)));
1773let d = date(9999, 12, 31);
1774assert_eq!(d.nth_weekday(-1, Weekday::Friday), Ok(date(9999, 12, 24)));
1775assert!(d.nth_weekday(1, Weekday::Friday).is_err());
17761777let d = date(-9999, 1, 8);
1778assert_eq!(d.nth_weekday(-1, Weekday::Monday), Ok(date(-9999, 1, 1)));
1779let d = date(-9999, 1, 2);
1780assert_eq!(d.nth_weekday(-1, Weekday::Monday), Ok(date(-9999, 1, 1)));
1781let d = date(-9999, 1, 1);
1782assert_eq!(d.nth_weekday(1, Weekday::Monday), Ok(date(-9999, 1, 8)));
1783assert!(d.nth_weekday(-1, Weekday::Monday).is_err());
1784 }
17851786#[test]
1787fn nth_weekday_errors() {
1788let d = date(2024, 3, 10);
1789assert!(d.nth_weekday(0, Weekday::Monday).is_err());
1790 }
17911792#[test]
1793fn nth_weekday_extreme() {
1794let weeks = 1_043_497;
17951796let d1 = date(-9999, 1, 1);
1797let d2 = d1.nth_weekday(weeks, Weekday::Monday).unwrap();
1798assert_eq!(d2, date(9999, 12, 27));
1799assert!(d1.nth_weekday(weeks + 1, Weekday::Monday).is_err());
1800assert!(d1.nth_weekday(i32::MIN, Weekday::Monday).is_err());
1801assert!(d1.nth_weekday(i32::MAX, Weekday::Monday).is_err());
18021803let d1 = date(9999, 12, 31);
1804let d2 = d1.nth_weekday(-weeks, Weekday::Friday).unwrap();
1805assert_eq!(d2, date(-9999, 1, 5));
1806assert!(d1.nth_weekday(weeks - 1, Weekday::Friday).is_err());
1807assert!(d1.nth_weekday(i32::MIN, Weekday::Friday).is_err());
1808assert!(d1.nth_weekday(i32::MAX, Weekday::Friday).is_err());
1809 }
18101811#[test]
1812fn yesterday() {
1813assert_eq!(date(2024, 7, 3).yesterday(), Ok(date(2024, 7, 2)));
1814assert_eq!(date(2024, 7, 1).yesterday(), Ok(date(2024, 6, 30)));
1815assert_eq!(date(2024, 6, 1).yesterday(), Ok(date(2024, 5, 31)));
1816assert_eq!(date(2024, 3, 1).yesterday(), Ok(date(2024, 2, 29)));
1817assert_eq!(date(2023, 3, 1).yesterday(), Ok(date(2023, 2, 28)));
1818assert_eq!(date(2023, 1, 1).yesterday(), Ok(date(2022, 12, 31)));
1819assert_eq!(date(-9999, 1, 2).yesterday(), Ok(date(-9999, 1, 1)));
1820assert_eq!(date(9999, 12, 31).yesterday(), Ok(date(9999, 12, 30)));
18211822assert!(date(-9999, 1, 1).yesterday().is_err());
1823 }
18241825#[test]
1826fn tomorrow() {
1827assert_eq!(date(2024, 7, 3).tomorrow(), Ok(date(2024, 7, 4)));
1828assert_eq!(date(2024, 6, 30).tomorrow(), Ok(date(2024, 7, 1)));
1829assert_eq!(date(2024, 5, 30).tomorrow(), Ok(date(2024, 5, 31)));
1830assert_eq!(date(2024, 5, 31).tomorrow(), Ok(date(2024, 6, 1)));
1831assert_eq!(date(2024, 2, 28).tomorrow(), Ok(date(2024, 2, 29)));
1832assert_eq!(date(2024, 2, 29).tomorrow(), Ok(date(2024, 3, 1)));
1833assert_eq!(date(2023, 2, 28).tomorrow(), Ok(date(2023, 3, 1)));
1834assert_eq!(date(2023, 12, 31).tomorrow(), Ok(date(2024, 1, 1)));
1835assert_eq!(date(-9999, 1, 1).tomorrow(), Ok(date(-9999, 1, 2)));
1836assert_eq!(date(9999, 12, 30).tomorrow(), Ok(date(9999, 12, 31)));
18371838assert!(date(9999, 12, 31).tomorrow().is_err());
1839 }
18401841#[test]
1842fn iso_week_date_tomorrow() {
1843assert_eq!(
1844 week_date(2024, 27, Weekday::Wednesday).tomorrow(),
1845Ok(week_date(2024, 27, Weekday::Thursday)),
1846 );
1847assert_eq!(
1848 week_date(2024, 27, Weekday::Sunday).tomorrow(),
1849Ok(week_date(2024, 28, Weekday::Monday)),
1850 );
1851assert_eq!(
1852 week_date(2024, 52, Weekday::Sunday).tomorrow(),
1853Ok(week_date(2025, 1, Weekday::Monday)),
1854 );
1855assert_eq!(
1856 week_date(2025, 1, Weekday::Monday).tomorrow(),
1857Ok(week_date(2025, 1, Weekday::Tuesday)),
1858 );
1859assert_eq!(
1860 week_date(2025, 1, Weekday::Tuesday).tomorrow(),
1861Ok(week_date(2025, 1, Weekday::Wednesday)),
1862 );
1863assert_eq!(
1864 week_date(2026, 52, Weekday::Sunday).tomorrow(),
1865Ok(week_date(2026, 53, Weekday::Monday)),
1866 );
1867assert_eq!(
1868 week_date(2026, 53, Weekday::Sunday).tomorrow(),
1869Ok(week_date(2027, 1, Weekday::Monday)),
1870 );
1871assert_eq!(
1872 week_date(-9999, 1, Weekday::Monday).tomorrow(),
1873Ok(week_date(-9999, 1, Weekday::Tuesday)),
1874 );
1875assert_eq!(
1876 week_date(9999, 52, Weekday::Thursday).tomorrow(),
1877Ok(week_date(9999, 52, Weekday::Friday)),
1878 );
18791880assert!(week_date(9999, 52, Weekday::Friday).tomorrow().is_err());
1881 }
18821883#[test]
1884fn iso_week_date_yesterday() {
1885assert_eq!(
1886 week_date(2024, 27, Weekday::Thursday).yesterday(),
1887Ok(week_date(2024, 27, Weekday::Wednesday)),
1888 );
1889assert_eq!(
1890 week_date(2024, 28, Weekday::Monday).yesterday(),
1891Ok(week_date(2024, 27, Weekday::Sunday)),
1892 );
1893assert_eq!(
1894 week_date(2025, 1, Weekday::Monday).yesterday(),
1895Ok(week_date(2024, 52, Weekday::Sunday)),
1896 );
1897assert_eq!(
1898 week_date(2025, 1, Weekday::Tuesday).yesterday(),
1899Ok(week_date(2025, 1, Weekday::Monday)),
1900 );
1901assert_eq!(
1902 week_date(2025, 1, Weekday::Wednesday).yesterday(),
1903Ok(week_date(2025, 1, Weekday::Tuesday)),
1904 );
1905assert_eq!(
1906 week_date(2026, 53, Weekday::Monday).yesterday(),
1907Ok(week_date(2026, 52, Weekday::Sunday)),
1908 );
1909assert_eq!(
1910 week_date(2027, 1, Weekday::Monday).yesterday(),
1911Ok(week_date(2026, 53, Weekday::Sunday)),
1912 );
1913assert_eq!(
1914 week_date(9999, 12, Weekday::Friday).yesterday(),
1915Ok(week_date(9999, 12, Weekday::Thursday)),
1916 );
1917assert_eq!(
1918 week_date(-9999, 1, Weekday::Tuesday).yesterday(),
1919Ok(week_date(-9999, 1, Weekday::Monday)),
1920 );
19211922assert!(week_date(-9999, 1, Weekday::Monday).yesterday().is_err());
1923 }
19241925#[test]
1926fn add() {
1927assert_eq!(date(2024, 7, 3).checked_add(-1), Ok(date(2024, 7, 2)));
1928assert_eq!(date(2024, 7, 1).checked_add(-1), Ok(date(2024, 6, 30)));
1929assert_eq!(date(2024, 6, 1).checked_add(-1), Ok(date(2024, 5, 31)));
1930assert_eq!(date(2024, 3, 1).checked_add(-1), Ok(date(2024, 2, 29)));
1931assert_eq!(date(2023, 3, 1).checked_add(-1), Ok(date(2023, 2, 28)));
1932assert_eq!(date(2023, 1, 1).checked_add(-1), Ok(date(2022, 12, 31)));
1933assert_eq!(date(-9999, 1, 2).checked_add(-1), Ok(date(-9999, 1, 1)));
1934assert_eq!(date(9999, 12, 31).checked_add(-1), Ok(date(9999, 12, 30)));
19351936assert_eq!(date(2024, 7, 3).checked_add(1), Ok(date(2024, 7, 4)));
1937assert_eq!(date(2024, 6, 30).checked_add(1), Ok(date(2024, 7, 1)));
1938assert_eq!(date(2024, 5, 30).checked_add(1), Ok(date(2024, 5, 31)));
1939assert_eq!(date(2024, 5, 31).checked_add(1), Ok(date(2024, 6, 1)));
1940assert_eq!(date(2024, 2, 28).checked_add(1), Ok(date(2024, 2, 29)));
1941assert_eq!(date(2024, 2, 29).checked_add(1), Ok(date(2024, 3, 1)));
1942assert_eq!(date(2023, 2, 28).checked_add(1), Ok(date(2023, 3, 1)));
1943assert_eq!(date(2023, 12, 31).checked_add(1), Ok(date(2024, 1, 1)));
1944assert_eq!(date(-9999, 1, 1).checked_add(1), Ok(date(-9999, 1, 2)));
1945assert_eq!(date(9999, 12, 30).checked_add(1), Ok(date(9999, 12, 31)));
19461947assert_eq!(date(2024, 7, 3).checked_add(2), Ok(date(2024, 7, 5)));
1948assert_eq!(date(2024, 6, 29).checked_add(2), Ok(date(2024, 7, 1)));
1949assert_eq!(date(2024, 5, 29).checked_add(2), Ok(date(2024, 5, 31)));
1950assert_eq!(date(2024, 5, 30).checked_add(2), Ok(date(2024, 6, 1)));
1951assert_eq!(date(2024, 2, 27).checked_add(2), Ok(date(2024, 2, 29)));
1952assert_eq!(date(2024, 2, 28).checked_add(2), Ok(date(2024, 3, 1)));
1953assert_eq!(date(2023, 2, 27).checked_add(2), Ok(date(2023, 3, 1)));
1954assert_eq!(date(2023, 12, 30).checked_add(2), Ok(date(2024, 1, 1)));
1955assert_eq!(date(-9999, 1, 1).checked_add(2), Ok(date(-9999, 1, 3)));
1956assert_eq!(date(9999, 12, 29).checked_add(2), Ok(date(9999, 12, 31)));
19571958let max_days = (b::UnixEpochDays::LEN - 1) as i32;
19591960assert_eq!(
1961 date(-9999, 1, 1).checked_add(max_days),
1962Ok(date(9999, 12, 31))
1963 );
1964assert_eq!(
1965 date(9999, 12, 31).checked_add(-max_days),
1966Ok(date(-9999, 1, 1))
1967 );
19681969assert!(date(-9999, 1, 1).checked_add(-1).is_err());
1970assert!(date(9999, 12, 31).checked_add(1).is_err());
1971assert!(date(-9999, 1, 1).checked_add(max_days + 1).is_err());
1972assert!(date(9999, 12, 31).checked_add(-(max_days + 1)).is_err());
1973 }
19741975#[test]
1976fn sub() {
1977assert_eq!(date(-9999, 1, 1).checked_sub(-1), Ok(date(-9999, 1, 2)));
1978assert_eq!(date(-9999, 1, 1).checked_sub(-2), Ok(date(-9999, 1, 3)));
19791980assert!(date(-9999, 1, 1).checked_sub(1).is_err());
1981assert!(date(-9999, 1, 1).checked_sub(i32::MIN).is_err());
1982assert!(date(9999, 12, 31).checked_sub(i32::MAX).is_err());
1983 }
19841985#[test]
1986fn prev_year() {
1987assert_eq!(date(2024, 2, 29).prev_year(), Ok(2023));
1988assert_eq!(date(2024, 1, 1).prev_year(), Ok(2023));
1989assert_eq!(date(2023, 12, 31).prev_year(), Ok(2022));
1990assert_eq!(date(9999, 12, 31).prev_year(), Ok(9998));
19911992assert!(date(-9999, 12, 31).prev_year().is_err());
1993assert!(date(-9999, 1, 1).prev_year().is_err());
1994 }
19951996#[test]
1997fn next_year() {
1998assert_eq!(date(2024, 2, 29).next_year(), Ok(2025));
1999assert_eq!(date(2024, 1, 1).next_year(), Ok(2025));
2000assert_eq!(date(2023, 12, 31).next_year(), Ok(2024));
2001assert_eq!(date(-9999, 12, 31).next_year(), Ok(-9998));
20022003assert!(date(9999, 12, 31).next_year().is_err());
2004assert!(date(9999, 1, 1).next_year().is_err());
2005 }
20062007#[test]
2008fn to_iso_week_date_various() {
2009assert_eq!(
2010 date(1995, 1, 1).to_iso_week_date(),
2011 week_date(1994, 52, Weekday::Sunday),
2012 );
2013assert_eq!(
2014 date(1996, 12, 31).to_iso_week_date(),
2015 week_date(1997, 1, Weekday::Tuesday),
2016 );
2017assert_eq!(
2018 date(2019, 12, 30).to_iso_week_date(),
2019 week_date(2020, 1, Weekday::Monday),
2020 );
2021assert_eq!(
2022 date(2031, 12, 29).to_iso_week_date(),
2023 week_date(2032, 1, Weekday::Monday),
2024 );
2025assert_eq!(
2026 date(2024, 3, 9).to_iso_week_date(),
2027 week_date(2024, 10, Weekday::Saturday),
2028 );
2029assert_eq!(
2030 Date::MIN.to_iso_week_date(),
2031 week_date(-9999, 1, Weekday::Monday),
2032 );
2033assert_eq!(
2034 Date::MAX.to_iso_week_date(),
2035 week_date(9999, 52, Weekday::Friday),
2036 );
2037 }
20382039quickcheck::quickcheck! {
2040fn prop_tomorrow_yesterday_is_identity(d: Date) -> quickcheck::TestResult {
2041let Ok(yesterday) = d.yesterday() else {
2042return quickcheck::TestResult::discard()
2043 };
2044 quickcheck::TestResult::from_bool(yesterday.tomorrow() == Ok(d))
2045 }
20462047fn prop_yesterday_tomorrow_is_identity(d: Date) -> quickcheck::TestResult {
2048let Ok(tomorrow) = d.tomorrow() else {
2049return quickcheck::TestResult::discard()
2050 };
2051 quickcheck::TestResult::from_bool(tomorrow.yesterday() == Ok(d))
2052 }
20532054fn prop_add_equals_sub(d1: Date, days: i32) -> quickcheck::TestResult {
2055let Ok(d2) = d1.checked_add(days) else {
2056return quickcheck::TestResult::discard();
2057 };
2058 quickcheck::TestResult::from_bool(d2.checked_sub(days) == Ok(d1))
2059 }
20602061fn prop_all_long_years_have_53rd_week(year: i16) -> quickcheck::TestResult {
2062if b::ISOYear::check(year).is_err() {
2063return quickcheck::TestResult::discard();
2064 }
2065 quickcheck::TestResult::from_bool(
2066 !civil::is_long_iso_week_year(year)
2067 || ISOWeekDate::new(year, 53, Weekday::Sunday).is_ok()
2068 )
2069 }
20702071fn prop_prev_day_is_less(wd: ISOWeekDate) -> quickcheck::TestResult {
2072let Ok(prev_date) = wd.to_date().yesterday() else {
2073return quickcheck::TestResult::discard();
2074 };
2075 quickcheck::TestResult::from_bool(
2076 prev_date.to_iso_week_date() < wd,
2077 )
2078 }
20792080fn prop_next_day_is_greater(wd: ISOWeekDate) -> quickcheck::TestResult {
2081let Ok(next_date) = wd.to_date().tomorrow() else {
2082return quickcheck::TestResult::discard();
2083 };
2084 quickcheck::TestResult::from_bool(
2085 wd < next_date.to_iso_week_date(),
2086 )
2087 }
20882089fn prop_iso_tomorrow_yesterday_is_identity(
2090 wd: ISOWeekDate
2091 ) -> quickcheck::TestResult {
2092let Ok(yesterday) = wd.yesterday() else {
2093return quickcheck::TestResult::discard()
2094 };
2095 quickcheck::TestResult::from_bool(yesterday.tomorrow() == Ok(wd))
2096 }
20972098fn prop_iso_yesterday_tomorrow_is_identity(
2099 wd: ISOWeekDate
2100 ) -> quickcheck::TestResult {
2101let Ok(tomorrow) = wd.tomorrow() else {
2102return quickcheck::TestResult::discard()
2103 };
2104 quickcheck::TestResult::from_bool(tomorrow.yesterday() == Ok(wd))
2105 }
2106 }
2107}