Skip to main content

jiff_core/civil/
date.rs

1use crate::{
2    bounds::{self as b, RangeError},
3    civil::{self, DateTime, Weekday},
4    macros::{ctry, rbail, rtry, unwrapr},
5};
6
7/// 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}
23
24impl 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.
29    pub const MIN: Date = {
30        let min = UnixEpochDay::MIN.to_date();
31        if !(min.year() == -9999) {
    ::core::panicking::panic("assertion failed: min.year() == -9999")
};assert!(min.year() == -9999);
32        if !(min.month() == 1) {
    ::core::panicking::panic("assertion failed: min.month() == 1")
};assert!(min.month() == 1);
33        if !(min.day() == 1) {
    ::core::panicking::panic("assertion failed: min.day() == 1")
};assert!(min.day() == 1);
34        min
35    };
36
37    /// The maximum allowed Gregorian date.
38    ///
39    /// This is guaranteed to be equivalent to [`UnixEpochDay::MAX`] when
40    /// converted to a Unix epoch day.
41    pub const MAX: Date = {
42        let max = UnixEpochDay::MAX.to_date();
43        if !(max.year() == 9999) {
    ::core::panicking::panic("assertion failed: max.year() == 9999")
};assert!(max.year() == 9999);
44        if !(max.month() == 12) {
    ::core::panicking::panic("assertion failed: max.month() == 12")
};assert!(max.month() == 12);
45        if !(max.day() == 31) {
    ::core::panicking::panic("assertion failed: max.day() == 31")
};assert!(max.day() == 31);
46        max
47    };
48
49    // 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    */
70
71    /// 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]
81    pub const fn new(
82        year: i16,
83        month: i8,
84        day: i8,
85    ) -> Result<Date, RangeError> {
86        let 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));
87        let 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));
88        if day < 1 {
89            return Err(b::Day::error().into_range_error());rbail!(b::Day::error());
90        } else if day > 28 && day > civil::days_in_month(year, month) {
91            return Err(b::SpecialBoundsError::DateInvalidDay {
                year,
                month,
            }.into_range_error());rbail!(b::SpecialBoundsError::DateInvalidDay { year, month });
92        }
93        Ok(Date { year, month, day })
94    }
95
96    /// 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]
102    pub const fn new_constrain(
103        year: i16,
104        month: i8,
105        day: i8,
106    ) -> Result<Date, RangeError> {
107        let 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));
108        let 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));
109        let day = if day < 1 {
110            return Err(b::Day::error().into_range_error());rbail!(b::Day::error());
111        } else if day > 28 {
112            let days_in_month = civil::days_in_month(year, month);
113            if day <= days_in_month { day } else { days_in_month }
114        } else {
115            day
116        };
117        Ok(Date { year, month, day })
118    }
119
120    /// 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]
127    pub const fn from_day_of_year(
128        year: i16,
129        day: i16,
130    ) -> Result<Date, RangeError> {
131        let 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));
132        let 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));
133        let start = Date { year, month: 1, day: 1 }.to_unix_epoch_day();
134        let end = match start.checked_add(day as i32 - 1) {
135            Ok(end) => end.to_date(),
136            // This can only happen when `year=9999` and `day=366`.
137            Err(_) => {
138                return 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.
142        if year != end.year {
143            // Can only happen given day=366 and this is a leap year.
144            if true {
    if !(day == 366) {
        ::core::panicking::panic("assertion failed: day == 366")
    };
};debug_assert!(day == 366);
145            if true {
    if !!civil::is_leap_year(year) {
        ::core::panicking::panic("assertion failed: !civil::is_leap_year(year)")
    };
};debug_assert!(!civil::is_leap_year(year));
146            return Err(b::SpecialBoundsError::DateInvalidDayOfYear {
                year,
            }.into_range_error())rbail!(b::SpecialBoundsError::DateInvalidDayOfYear { year })
147        }
148        Ok(end)
149    }
150
151    /// 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]
159    pub const fn from_day_of_year_no_leap(
160        year: i16,
161        day: i16,
162    ) -> Result<Date, RangeError> {
163        let 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));
164        let 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));
165        if day >= 60 && civil::is_leap_year(year) {
166            day += 1;
167        }
168        // The boundary check above guarantees this always succeeds.
169        Ok(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    }
171
172    /// 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]
177    pub const fn year(self) -> i16 {
178        self.year
179    }
180
181    /// Returns the month component of this date.
182    ///
183    /// The value returned is guaranteed to be in the range `1..=12`.
184    #[inline]
185    pub const fn month(self) -> i8 {
186        self.month
187    }
188
189    /// 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]
194    pub const fn day(self) -> i8 {
195        self.day
196    }
197
198    /// Returns the weekday corresponding to this date.
199    #[inline]
200    pub const fn weekday(self) -> Weekday {
201        self.to_unix_epoch_day().weekday()
202    }
203
204    /// 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]
209    pub const fn day_of_year(self) -> i16 {
210        const DAYS_BY_MONTH_NO_LEAP: [i16; 14] =
211            [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365];
212        const DAYS_BY_MONTH_LEAP: [i16; 14] =
213            [0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366];
214        const TABLES: [[i16; 14]; 2] =
215            [DAYS_BY_MONTH_NO_LEAP, DAYS_BY_MONTH_LEAP];
216        TABLES[self.in_leap_year() as usize][self.month() as usize]
217            + (self.day() as i16)
218    }
219
220    /// 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]
230    pub const fn day_of_year_no_leap(self) -> Option<i16> {
231        let mut days = self.day_of_year();
232        if self.in_leap_year() {
233            // day=60 is Feb 29
234            if days == 60 {
235                return None;
236            } else if days > 60 {
237                days -= 1;
238            }
239        }
240        Some(days)
241    }
242
243    /// Returns the first date of the month for this date.
244    #[inline]
245    pub const fn first_of_month(self) -> Date {
246        Date { day: 1, ..self }
247    }
248
249    /// Returns the last date of the month for this date.
250    #[inline]
251    pub const fn last_of_month(self) -> Date {
252        Date { day: self.days_in_month(), ..self }
253    }
254
255    /// 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]
261    pub const fn days_in_month(self) -> i8 {
262        civil::days_in_month(self.year(), self.month())
263    }
264
265    /// Returns the first date of the year that this date resides in.
266    #[inline]
267    pub const fn first_of_year(self) -> Date {
268        Date { month: 1, day: 1, ..self }
269    }
270
271    /// Returns the last date of the year that this date resides in.
272    #[inline]
273    pub const fn last_of_year(self) -> Date {
274        Date { month: 12, day: 31, ..self }
275    }
276
277    /// 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]
281    pub const fn days_in_year(self) -> i16 {
282        if self.in_leap_year() { 366 } else { 365 }
283    }
284
285    /// Returns true when this date is in a leap year.
286    #[inline]
287    pub const fn in_leap_year(self) -> bool {
288        civil::is_leap_year(self.year())
289    }
290
291    /// Returns the day before this date.
292    ///
293    /// Returns an error when this is the minimal date.
294    #[inline]
295    pub const fn yesterday(self) -> Result<Date, RangeError> {
296        if self.day() == 1 {
297            if self.month() == 1 {
298                let year = match self.prev_year() { Ok(val) => val, Err(err) => return Err(err), }ctry!(self.prev_year());
299                return Ok(Date { year, month: 12, day: 31 });
300            }
301            let month = self.month() - 1;
302            let day = civil::days_in_month(self.year(), month);
303            return Ok(Date { month, day, ..self });
304        }
305        Ok(Date { day: self.day() - 1, ..self })
306    }
307
308    /// Returns the day after this date.
309    ///
310    /// Returns an error when this is the maximal date.
311    #[inline]
312    pub const fn tomorrow(self) -> Result<Date, RangeError> {
313        if self.day() >= 28 && self.day() == self.days_in_month() {
314            if self.month() == 12 {
315                let year = match self.next_year() { Ok(val) => val, Err(err) => return Err(err), }ctry!(self.next_year());
316                return Ok(Date { year, month: 1, day: 1 });
317            }
318            let month = self.month() + 1;
319            return Ok(Date { month, day: 1, ..self });
320        }
321        Ok(Date { day: self.day() + 1, ..self })
322    }
323
324    /// 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]
332    pub const fn nth_weekday_of_month(
333        &self,
334        nth: i8,
335        weekday: Weekday,
336    ) -> Result<Date, RangeError> {
337        let 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));
338        if nth == 0 {
339            return Err(b::NthWeekdayOfMonth::error().into_range_error());rbail!(b::NthWeekdayOfMonth::error());
340        } else if nth > 0 {
341            let first = self.first_of_month();
342            let first_weekday = first.weekday();
343            let diff = weekday.since(first_weekday);
344            let day = diff + 1 + (nth - 1) * 7;
345            Date::new(self.year(), self.month(), day)
346        } else {
347            let last = self.last_of_month();
348            let last_weekday = last.weekday();
349            let diff = last_weekday.since(weekday);
350            let day = last.day() - diff - (nth.abs() - 1) * 7;
351            Date::new(self.year(), self.month(), day)
352        }
353    }
354
355    /// 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]
366    pub const fn nth_weekday(
367        self,
368        nth: i32,
369        weekday: Weekday,
370    ) -> Result<Date, RangeError> {
371        self.to_unix_epoch_day().nth_weekday(nth, weekday)
372    }
373
374    /// 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]
379    pub(crate) const fn prev_year(self) -> Result<i16, RangeError> {
380        Ok(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    }
382
383    /// Returns the year one year from this date.
384    #[inline]
385    pub(crate) const fn next_year(self) -> Result<i16, RangeError> {
386        Ok(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    }
388
389    /// 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]
393    pub const fn checked_add(self, days: i32) -> Result<Date, RangeError> {
394        match days {
395            0 => Ok(self),
396            -1 => self.yesterday(),
397            1 => 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    }
401
402    /// 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]
406    pub const fn checked_sub(self, days: i32) -> Result<Date, RangeError> {
407        let Some(days) = days.checked_neg() else {
408            return Err(b::UnixEpochDays::error().into_range_error());rbail!(b::UnixEpochDays::error());
409        };
410        self.checked_add(days)
411    }
412
413    /// 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]
442    pub const fn until(self, other: Date) -> i32 {
443        -self.since(other)
444    }
445
446    /// 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]
474    pub const fn since(self, other: Date) -> i32 {
475        // Try to avoid conversions to Unix epoch days in some cases.
476        if self.year() == other.year() {
477            if self.month() == other.month() {
478                (self.day() - other.day()) as i32
479            } else {
480                (self.day_of_year() - other.day_of_year()) as i32
481            }
482        } else {
483            self.to_unix_epoch_day().since(other.to_unix_epoch_day())
484        }
485    }
486
487    /// Converts a Gregorian date to a Unix epoch day.
488    #[inline]
489    #[allow(non_upper_case_globals, non_snake_case)] // to mimic source
490    pub 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
494        const s: u32 = 82;
495        const K: u32 = 719468 + 146097 * s;
496        const L: u32 = 400 * s;
497
498        let year = self.year as u32;
499        let month = self.month as u32;
500        let day = self.day as u32;
501
502        let J = month <= 2;
503        let Y = year.wrapping_add(L).wrapping_sub(J as u32);
504        let M = if J { month + 12 } else { month };
505        let D = day - 1;
506        let C = Y / 100;
507
508        let y_star = 1461 * Y / 4 - C + C / 4;
509        let m_star = (979 * M - 2919) / 32;
510        let N = y_star + m_star + D;
511
512        let N_U = N.wrapping_sub(K);
513        let epoch_day = N_U as i32;
514        UnixEpochDay { day: epoch_day }
515    }
516
517    /// Converts this Gregorian date to an ISO 8601 week date.
518    #[inline]
519    pub const fn to_iso_week_date(self) -> ISOWeekDate {
520        let epoch_day = self.to_unix_epoch_day();
521        let mut year = self.year();
522        let mut epoch_day_year_start = iso_week_start_from_year(year);
523        if 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.
534            year -= 1;
535            epoch_day_year_start = iso_week_start_from_year(year);
536        } else if self.month() == 12 && self.day() >= 29 && year < b::Year::MAX
537        {
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`.
545            let epoch_day_next_year_week_start =
546                iso_week_start_from_year(year + 1);
547            if epoch_day.day() >= epoch_day_next_year_week_start.day() {
548                epoch_day_year_start = epoch_day_next_year_week_start;
549                year += 1;
550            }
551        }
552
553        // 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`.
556        let week =
557            (((epoch_day.day() - epoch_day_year_start.day()) / 7) + 1) as i8;
558        let weekday = epoch_day.weekday();
559
560        ISOWeekDate { year, week, weekday }
561    }
562
563    /// 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]
579    pub const fn at(
580        self,
581        hour: i8,
582        minute: i8,
583        second: i8,
584        subsec_nanosecond: i32,
585    ) -> DateTime {
586        DateTime::from_parts(
587            self,
588            civil::time(hour, minute, second, subsec_nanosecond),
589        )
590    }
591}
592
593impl core::fmt::Debug for Date {
594    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
595        if self.year() < 0 {
596            f.write_fmt(format_args!("-{0:06}", self.year().unsigned_abs()))write!(f, "-{:06}", self.year().unsigned_abs())?;
597        } else {
598            f.write_fmt(format_args!("{0:04}", self.year()))write!(f, "{:04}", self.year())?;
599        }
600        f.write_fmt(format_args!("-{0:02}-{1:02}", self.month(), self.day()))write!(f, "-{:02}-{:02}", self.month(), self.day())
601    }
602}
603
604/// 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::Sub for Date {
632    type Output = i32;
633
634    #[inline]
635    fn sub(self, rhs: Date) -> i32 {
636        self.since(rhs)
637    }
638}
639
640#[cfg(feature = "arbitrary")]
641impl<'a> arbitrary::Arbitrary<'a> for Date {
642    fn arbitrary(
643        u: &mut arbitrary::Unstructured<'a>,
644    ) -> arbitrary::Result<Date> {
645        let year = u.int_in_range(b::Year::MIN..=b::Year::MAX)?;
646        let month = u.int_in_range(b::Month::MIN..=b::Month::MAX)?;
647        let day = u.int_in_range(b::Day::MIN..=b::Day::MAX)?;
648        Ok(Date::new_constrain(year, month, day).unwrap())
649    }
650
651    fn 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}
659
660#[cfg(test)]
661impl quickcheck::Arbitrary for Date {
662    fn arbitrary(g: &mut quickcheck::Gen) -> Date {
663        let year = b::Year::arbitrary(g);
664        let month = b::Month::arbitrary(g);
665        let day = b::Day::arbitrary(g);
666        Date::new_constrain(year, month, day).unwrap()
667    }
668
669    fn 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}
679
680/// 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}
692
693impl 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.
698    pub const MIN: UnixEpochDay = UnixEpochDay { day: b::UnixEpochDays::MIN };
699
700    /// The maximum allowed Unix epoch day.
701    ///
702    /// This is guaranteed to be equivalent to [`Date::MAX`] when
703    /// converted to a Gregorian date.
704    pub const MAX: UnixEpochDay = UnixEpochDay { day: b::UnixEpochDays::MAX };
705
706    /// 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]
712    pub const fn new(day: i32) -> Result<UnixEpochDay, RangeError> {
713        let 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));
714        Ok(UnixEpochDay { day })
715    }
716
717    /// Returns the underlying day value.
718    ///
719    /// This is guaranteed to be in the [`UnixEpochDays`](b::UnixEpochDays)
720    /// range.
721    #[inline]
722    pub const fn day(self) -> i32 {
723        self.day
724    }
725
726    /// Returns the day of the week for this epoch day.
727    #[inline]
728    pub 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
739        let result = Weekday::from_monday_one_offset({
740            const M: u32 = {
741                // MSRV(1.73): Just use `n.div_ceil` instead.
742                const fn div_ceil(lhs: u64, rhs: u64) -> u64 {
743                    let d = lhs / rhs;
744                    let r = lhs % rhs;
745                    if r > 0 { d + 1 } else { d }
746                }
747
748                let n = div_ceil(1u64 << 32, 7) as u32;
749                if !(n == 613_566_757) {
    ::core::panicking::panic("assertion failed: n == 613_566_757")
};assert!(n == 613_566_757);
750                n
751            };
752            const Z: u32 = 0x90000000; // Magic add: see link above.
753            let rd: u32 = self.day() as u32;
754            (rd.wrapping_mul(M).wrapping_add(Z) >> 29) as i8
755        });
756        match 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    }
758
759    /// 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]
770    pub const fn nth_weekday(
771        self,
772        nth: i32,
773        weekday: Weekday,
774    ) -> Result<Date, RangeError> {
775        // ref: http://howardhinnant.github.io/date_algorithms.html#next_weekday
776
777        let 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));
778        if nth == 0 {
779            return Err(b::NthWeekday::error().into_range_error());rbail!(b::NthWeekday::error());
780        } else if nth > 0 {
781            let weekday_diff = weekday.since(self.weekday().next()) as i32;
782            let diff = (nth - 1) * 7 + weekday_diff;
783            let end = match self.checked_add(diff + 1) {
    Ok(val) => val,
    Err(err) => return Err(err),
}ctry!(self.checked_add(diff + 1));
784            Ok(end.to_date())
785        } else {
786            let weekday_diff = self.weekday().previous().since(weekday) as i32;
787            // OK because of the range on `NthWeekday`.
788            let nth = nth.abs();
789            // OK because of the range on `NthWeekday`.
790            let diff = -((nth - 1) * 7 + weekday_diff);
791            let end = match self.checked_add(diff - 1) {
    Ok(val) => val,
    Err(err) => return Err(err),
}ctry!(self.checked_add(diff - 1));
792            Ok(end.to_date())
793        }
794    }
795
796    /// 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]
801    pub const fn checked_add(
802        self,
803        days: i32,
804    ) -> Result<UnixEpochDay, RangeError> {
805        let 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));
806        Ok(UnixEpochDay { day })
807    }
808
809    /// 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]
814    pub const fn checked_sub(
815        self,
816        days: i32,
817    ) -> Result<UnixEpochDay, RangeError> {
818        let Some(days) = days.checked_neg() else {
819            return Err(b::UnixEpochDays::error().into_range_error());rbail!(b::UnixEpochDays::error());
820        };
821        self.checked_add(days)
822    }
823
824    /// 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]
853    pub const fn until(self, other: UnixEpochDay) -> i32 {
854        -self.since(other)
855    }
856
857    /// 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]
885    pub const fn since(self, other: UnixEpochDay) -> i32 {
886        self.day() - other.day()
887    }
888
889    /// Converts this Unix epoch day to a Gregorian date.
890    #[inline]
891    #[allow(non_upper_case_globals, non_snake_case)] // to mimic source
892    pub 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>
896        const s: u32 = 82;
897        const K: u32 = 719468 + 146097 * s;
898        const L: u32 = 400 * s;
899
900        let N_U = self.day as u32;
901        let N = N_U.wrapping_add(K);
902
903        let N_1 = 4 * N + 3;
904        let C = N_1 / 146097;
905        let N_C = (N_1 % 146097) / 4;
906
907        let N_2 = 4 * N_C + 3;
908        let P_2 = 2939745 * (N_2 as u64);
909        let Z = (P_2 / 4294967296) as u32;
910        let N_Y = (P_2 % 4294967296) as u32 / 2939745 / 4;
911        let Y = 100 * C + Z;
912
913        let N_3 = 2141 * N_Y + 197913;
914        let M = N_3 / 65536;
915        let D = (N_3 % 65536) / 2141;
916
917        let J = N_Y >= 306;
918        let year = Y.wrapping_sub(L).wrapping_add(J as u32) as i16;
919        let month = (if J { M - 12 } else { M }) as i8;
920        let day = (D + 1) as i8;
921        Date { year, month, day }
922    }
923}
924
925impl core::fmt::Debug for UnixEpochDay {
926    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
927        f.debug_tuple("UnixEpochDay").field(&self.day()).finish()
928    }
929}
930
931/// 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::Sub for UnixEpochDay {
959    type Output = i32;
960
961    #[inline]
962    fn sub(self, rhs: UnixEpochDay) -> i32 {
963        self.since(rhs)
964    }
965}
966
967/// 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}
978
979impl ISOWeekDate {
980    /// The minimum representable ISO week date.
981    pub const MIN: ISOWeekDate = ISOWeekDate {
982        year: b::ISOYear::MIN,
983        week: b::ISOWeek::MIN,
984        weekday: Weekday::Monday,
985    };
986
987    /// The maximum representable ISO week date.
988    pub const MAX: ISOWeekDate = ISOWeekDate {
989        year: b::ISOYear::MAX,
990        // Technical max is 52, but 9999 is not a leap year.
991        week: 52,
992        weekday: Weekday::Friday,
993    };
994
995    /// The zero ISO 8601 week date. It is the first day of the zeroth year.
996    pub const ZERO: ISOWeekDate =
997        ISOWeekDate { year: 0, week: 1, weekday: Weekday::Monday };
998
999    /// 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]
1004    pub const fn new(
1005        year: i16,
1006        week: i8,
1007        weekday: Weekday,
1008    ) -> Result<ISOWeekDate, RangeError> {
1009        let 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));
1010        let 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));
1011
1012        // 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.
1020        if 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);
1021        if 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);
1022        if week == 53 && !civil::is_long_iso_week_year(year) {
1023            return 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.
1034        if year == b::ISOYear::MAX
1035            && week == 52
1036            && weekday.to_monday_zero_offset()
1037                > Weekday::Friday.to_monday_zero_offset()
1038        {
1039            return Err(b::WeekdayMondayOne::error().into_range_error());rbail!(b::WeekdayMondayOne::error());
1040        }
1041        Ok(ISOWeekDate { year, week, weekday })
1042    }
1043
1044    /// 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]
1052    pub const fn new_constrain(
1053        year: i16,
1054        mut week: i8,
1055        mut weekday: Weekday,
1056    ) -> Result<ISOWeekDate, RangeError> {
1057        let 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));
1058        if week < 1 {
1059            return Err(b::ISOWeek::error().into_range_error());rbail!(b::ISOWeek::error());
1060        }
1061        let weeks_in_year =
1062            if civil::is_long_iso_week_year(year) { 53 } else { 52 };
1063        week = if week <= weeks_in_year { week } else { weeks_in_year };
1064        if year == b::ISOYear::MAX
1065            && week == 52
1066            && weekday.to_monday_zero_offset()
1067                > Weekday::Friday.to_monday_zero_offset()
1068        {
1069            weekday = Weekday::Friday;
1070        }
1071        Ok(ISOWeekDate { year, week, weekday })
1072    }
1073
1074    /// 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]
1079    pub const fn year(self) -> i16 {
1080        self.year
1081    }
1082
1083    /// 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]
1088    pub const fn week(self) -> i8 {
1089        self.week
1090    }
1091
1092    /// Returns the weekday component of this ISO 8601 week date.
1093    #[inline]
1094    pub const fn weekday(self) -> Weekday {
1095        self.weekday
1096    }
1097
1098    /// 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]
1111    pub 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.
1117        Ok(ISOWeekDate { weekday: Weekday::Monday, ..self })
1118    }
1119
1120    /// 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]
1130    pub const fn last_of_week(self) -> Result<ISOWeekDate, RangeError> {
1131        ISOWeekDate::new(self.year(), self.week(), Weekday::Sunday)
1132    }
1133
1134    /// 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]
1147    pub 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.
1153        Ok(ISOWeekDate { week: 1, weekday: Weekday::Monday, ..self })
1154    }
1155
1156    /// 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]
1166    pub const fn last_of_year(self) -> Result<ISOWeekDate, RangeError> {
1167        ISOWeekDate::new(self.year(), self.weeks_in_year(), Weekday::Sunday)
1168    }
1169
1170    /// 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]
1177    pub const fn days_in_year(self) -> i16 {
1178        if self.in_long_year() { 371 } else { 364 }
1179    }
1180
1181    /// 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]
1188    pub const fn weeks_in_year(self) -> i8 {
1189        civil::weeks_in_iso_week_year(self.year())
1190    }
1191
1192    /// 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]
1198    pub const fn in_long_year(self) -> bool {
1199        civil::is_long_iso_week_year(self.year())
1200    }
1201
1202    /// 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]
1208    pub 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.
1212        if 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        {
1216            return 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())
1221        if #[allow(non_exhaustive_omitted_patterns)] match self.weekday() {
    Weekday::Sunday => true,
    _ => false,
}matches!(self.weekday(), Weekday::Sunday) {
1222            if self.week() >= 52 && self.week() == self.weeks_in_year() {
1223                let year = self.year() + 1;
1224                return Ok(ISOWeekDate {
1225                    year,
1226                    week: 1,
1227                    weekday: Weekday::Monday,
1228                });
1229            }
1230            let week = self.week() + 1;
1231            return Ok(ISOWeekDate { week, weekday: Weekday::Monday, ..self });
1232        }
1233        Ok(ISOWeekDate { weekday: self.weekday().next(), ..self })
1234    }
1235
1236    /// 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]
1242    pub fn yesterday(self) -> Result<ISOWeekDate, RangeError> {
1243        if #[allow(non_exhaustive_omitted_patterns)] match self.weekday() {
    Weekday::Monday => true,
    _ => false,
}matches!(self.weekday(), Weekday::Monday) {
1244            if self.week() == 1 {
1245                let 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));
1246                let week = civil::weeks_in_iso_week_year(year);
1247                return Ok(ISOWeekDate {
1248                    year,
1249                    week,
1250                    weekday: Weekday::Sunday,
1251                });
1252            }
1253            let week = self.week() - 1;
1254            return Ok(ISOWeekDate { week, weekday: Weekday::Sunday, ..self });
1255        }
1256        Ok(ISOWeekDate { weekday: self.weekday().previous(), ..self })
1257    }
1258
1259    /// Converts this ISO 8601 week date to a Unix epoch day.
1260    #[inline]
1261    pub const fn to_unix_epoch_day(self) -> UnixEpochDay {
1262        let epoch_day_year = iso_week_start_from_year(self.year());
1263        let week = self.week() as i32;
1264        let weekday = self.weekday().to_monday_zero_offset() as i32;
1265        match 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    }
1270
1271    /// Converts this ISO 8601 week date to a Gregorian date.
1272    #[inline]
1273    pub const fn to_date(self) -> Date {
1274        self.to_unix_epoch_day().to_date()
1275    }
1276}
1277
1278impl core::fmt::Debug for ISOWeekDate {
1279    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1280        f.write_fmt(format_args!("{0:04}-W{1:02}-{2}", self.year, self.week,
        self.weekday.to_monday_one_offset()))write!(
1281            f,
1282            "{:04}-W{:02}-{}",
1283            self.year,
1284            self.week,
1285            self.weekday.to_monday_one_offset()
1286        )
1287    }
1288}
1289
1290impl Ord for ISOWeekDate {
1291    #[inline]
1292    fn cmp(&self, other: &ISOWeekDate) -> core::cmp::Ordering {
1293        (self.year(), self.week(), self.weekday().to_monday_one_offset()).cmp(
1294            &(
1295                other.year(),
1296                other.week(),
1297                other.weekday().to_monday_one_offset(),
1298            ),
1299        )
1300    }
1301}
1302
1303impl PartialOrd for ISOWeekDate {
1304    #[inline]
1305    fn partial_cmp(&self, other: &ISOWeekDate) -> Option<core::cmp::Ordering> {
1306        Some(self.cmp(other))
1307    }
1308}
1309
1310/// 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 {
1318    if 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.
1322    let epoch_day_in_first_week =
1323        Date { 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`.
1327    let diff_from_monday =
1328        epoch_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.
1334    match 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}
1339
1340#[cfg(feature = "arbitrary")]
1341impl<'a> arbitrary::Arbitrary<'a> for ISOWeekDate {
1342    fn arbitrary(
1343        u: &mut arbitrary::Unstructured<'a>,
1344    ) -> arbitrary::Result<ISOWeekDate> {
1345        let year = u.int_in_range(b::ISOYear::MIN..=b::ISOYear::MAX)?;
1346        let week = u.int_in_range(b::ISOWeek::MIN..=b::ISOWeek::MAX)?;
1347        let weekday = Weekday::arbitrary(u)?;
1348        Ok(ISOWeekDate::new_constrain(year, week, weekday).unwrap())
1349    }
1350
1351    fn 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}
1359
1360#[cfg(test)]
1361impl quickcheck::Arbitrary for ISOWeekDate {
1362    fn arbitrary(g: &mut quickcheck::Gen) -> ISOWeekDate {
1363        let year = b::ISOYear::arbitrary(g);
1364        let week = b::ISOWeek::arbitrary(g);
1365        let weekday = Weekday::arbitrary(g);
1366        ISOWeekDate::new_constrain(year, week, weekday).unwrap()
1367    }
1368
1369    fn 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}
1379
1380#[cfg(test)]
1381mod tests {
1382    use super::*;
1383
1384    fn date(year: i16, month: i8, day: i8) -> Date {
1385        Date::new(year, month, day).unwrap()
1386    }
1387
1388    fn week_date(year: i16, week: i8, weekday: Weekday) -> ISOWeekDate {
1389        ISOWeekDate::new(year, week, weekday).unwrap()
1390    }
1391
1392    #[test]
1393    fn iso_week_date_new_constrain() {
1394        assert_eq!(
1395            ISOWeekDate::new_constrain(2024, 60, Weekday::Monday).unwrap(),
1396            week_date(2024, 52, Weekday::Monday),
1397        );
1398    }
1399
1400    #[test]
1401    fn date_min() {
1402        assert_eq!(Date::MIN, date(-9999, 1, 1));
1403    }
1404
1405    #[test]
1406    fn date_max() {
1407        assert_eq!(Date::MAX, date(9999, 12, 31));
1408    }
1409
1410    #[test]
1411    fn unix_epoch_to_date_and_back_again_min_to_max() {
1412        for i in 0.. {
1413            let Ok(epoch_day) = UnixEpochDay::MIN.checked_add(i) else {
1414                break;
1415            };
1416            let date = epoch_day.to_date();
1417            let got = date.to_unix_epoch_day();
1418            assert_eq!(epoch_day, got);
1419        }
1420    }
1421
1422    #[test]
1423    fn unix_epoch_to_date_and_back_again_max_to_min() {
1424        for i in 0.. {
1425            let Ok(epoch_day) = UnixEpochDay::MAX.checked_sub(i) else {
1426                break;
1427            };
1428            let date = epoch_day.to_date();
1429            let got = date.to_unix_epoch_day();
1430            assert_eq!(epoch_day, got);
1431        }
1432    }
1433
1434    #[test]
1435    fn date_to_unix_epoch_and_back_again() {
1436        for year in b::Year::MIN..=b::Year::MAX {
1437            for month in b::Month::MIN..=b::Month::MAX {
1438                for day in b::Day::MIN..=civil::days_in_month(year, month) {
1439                    let d = date(year, month, day);
1440                    let epoch_day = d.to_unix_epoch_day();
1441                    let got = epoch_day.to_date();
1442                    assert_eq!(d, got);
1443                }
1444            }
1445        }
1446    }
1447
1448    #[test]
1449    fn date_to_week_date_and_back_again() {
1450        for year in b::Year::MIN..=b::Year::MAX {
1451            for month in b::Month::MIN..=b::Month::MAX {
1452                for day in b::Day::MIN..=civil::days_in_month(year, month) {
1453                    let d = date(year, month, day);
1454                    let wd = d.to_iso_week_date();
1455                    let got = wd.to_date();
1456                    assert_eq!(d, got);
1457                }
1458            }
1459        }
1460    }
1461
1462    #[test]
1463    fn date_to_day_of_year_and_back_again() {
1464        for year in b::Year::MIN..=b::Year::MAX {
1465            for month in b::Month::MIN..=b::Month::MAX {
1466                for day in b::Day::MIN..=civil::days_in_month(year, month) {
1467                    let d = date(year, month, day);
1468                    let doy = d.day_of_year();
1469                    let got = Date::from_day_of_year(year, doy);
1470                    assert_eq!(Ok(d), got);
1471                }
1472            }
1473        }
1474    }
1475
1476    #[test]
1477    fn day_of_year_in_non_leap_year() {
1478        let year = 2026;
1479        let mut doy = 1;
1480        for month in b::Month::MIN..=b::Month::MAX {
1481            for day in b::Day::MIN..=civil::days_in_month(year, month) {
1482                let d = Date::from_day_of_year(year, doy).unwrap();
1483                assert_eq!(d, date(year, month, day));
1484                assert_eq!(d.day_of_year(), doy);
1485                doy += 1;
1486            }
1487        }
1488    }
1489
1490    #[test]
1491    fn day_of_year_in_leap_year() {
1492        let year = 2024;
1493        let mut doy = 1;
1494        for month in b::Month::MIN..=b::Month::MAX {
1495            for day in b::Day::MIN..=civil::days_in_month(year, month) {
1496                let d = Date::from_day_of_year(year, doy).unwrap();
1497                assert_eq!(d, date(year, month, day));
1498                assert_eq!(d.day_of_year(), doy);
1499                doy += 1;
1500            }
1501        }
1502    }
1503
1504    #[test]
1505    fn day_of_year_no_leap_in_non_leap_year() {
1506        let year = 2026;
1507        let mut doy = 1;
1508        for month in b::Month::MIN..=b::Month::MAX {
1509            for day in b::Day::MIN..=civil::days_in_month(year, month) {
1510                let d = Date::from_day_of_year_no_leap(year, doy).unwrap();
1511                assert_eq!(d, date(year, month, day));
1512                assert_eq!(d.day_of_year_no_leap(), Some(doy));
1513                doy += 1;
1514            }
1515        }
1516    }
1517
1518    #[test]
1519    fn day_of_year_no_leap_in_leap_year() {
1520        let year = 2024;
1521        let mut doy = 1;
1522        for month in b::Month::MIN..=b::Month::MAX {
1523            for day in b::Day::MIN..=civil::days_in_month(year, month) {
1524                if month == 2 && day == 29 {
1525                    continue;
1526                }
1527                let d = Date::from_day_of_year_no_leap(year, doy).unwrap();
1528                assert_eq!(d, date(year, month, day));
1529                assert_eq!(d.day_of_year_no_leap(), Some(doy));
1530                doy += 1;
1531            }
1532        }
1533    }
1534
1535    #[test]
1536    fn date_to_day_of_year_no_leap_and_back_again() {
1537        for year in b::Year::MIN..=b::Year::MAX {
1538            for month in b::Month::MIN..=b::Month::MAX {
1539                for day in b::Day::MIN..=civil::days_in_month(year, month) {
1540                    if month == 2 && day == 29 {
1541                        continue;
1542                    }
1543                    let d = date(year, month, day);
1544                    let doy = d.day_of_year_no_leap().unwrap();
1545                    let got = Date::from_day_of_year_no_leap(year, doy);
1546                    assert_eq!(Ok(d), got);
1547                }
1548            }
1549        }
1550    }
1551
1552    #[test]
1553    fn unix_epoch_day_weekday() {
1554        let mk = |day| date(2026, 2, day).weekday();
1555        assert_eq!(mk(14), Weekday::Saturday);
1556        assert_eq!(mk(15), Weekday::Sunday);
1557        assert_eq!(mk(16), Weekday::Monday);
1558        assert_eq!(mk(17), Weekday::Tuesday);
1559        assert_eq!(mk(18), Weekday::Wednesday);
1560        assert_eq!(mk(19), Weekday::Thursday);
1561        assert_eq!(mk(20), Weekday::Friday);
1562        assert_eq!(mk(21), Weekday::Saturday);
1563    }
1564
1565    #[test]
1566    fn first_of_last_of() {
1567        for year in b::Year::MIN..=b::Year::MAX {
1568            for month in b::Month::MIN..=b::Month::MAX {
1569                for day in b::Day::MIN..=civil::days_in_month(year, month) {
1570                    let d = date(year, month, day);
1571
1572                    assert_eq!(d.first_of_month(), date(year, month, 1));
1573                    assert_eq!(
1574                        d.last_of_month(),
1575                        date(year, month, d.days_in_month())
1576                    );
1577
1578                    assert_eq!(d.first_of_year(), date(year, 1, 1));
1579                    assert_eq!(d.last_of_year(), date(year, 12, 31));
1580                }
1581            }
1582        }
1583    }
1584
1585    #[test]
1586    fn days_in() {
1587        for year in b::Year::MIN..=b::Year::MAX {
1588            for month in b::Month::MIN..=b::Month::MAX {
1589                for day in b::Day::MIN..=civil::days_in_month(year, month) {
1590                    let d = date(year, month, day);
1591
1592                    assert!([365, 366].contains(&d.days_in_year()));
1593                    assert!([28, 29, 30, 31].contains(&d.days_in_month()));
1594                }
1595            }
1596        }
1597    }
1598
1599    #[test]
1600    fn nth_weekday_of_month_various() {
1601        let d1 = date(2017, 3, 1);
1602        let wday = Weekday::Friday;
1603        assert_eq!(d1.nth_weekday_of_month(2, wday), Ok(date(2017, 3, 10)));
1604
1605        let d1 = date(2024, 3, 1);
1606        let wday = Weekday::Thursday;
1607        assert_eq!(d1.nth_weekday_of_month(-1, wday), Ok(date(2024, 3, 28)));
1608
1609        let d1 = date(2024, 3, 25);
1610        let wday = Weekday::Monday;
1611        assert!(d1.nth_weekday_of_month(5, wday).is_err());
1612        assert!(d1.nth_weekday_of_month(-5, wday).is_err());
1613
1614        let d1 = date(1998, 1, 1);
1615        let wday = Weekday::Saturday;
1616        assert_eq!(d1.nth_weekday_of_month(5, wday), Ok(date(1998, 1, 31)));
1617    }
1618
1619    #[test]
1620    fn nth_weekday_of_month_errors() {
1621        let d = date(2017, 3, 1);
1622        let wday = Weekday::Tuesday;
1623
1624        assert!(d.nth_weekday_of_month(0, wday).is_err());
1625        assert!(d.nth_weekday_of_month(5, wday).is_err());
1626        assert!(d.nth_weekday_of_month(-5, wday).is_err());
1627        assert!(d.nth_weekday_of_month(6, wday).is_err());
1628        assert!(d.nth_weekday_of_month(-6, wday).is_err());
1629        assert!(d.nth_weekday_of_month(i8::MIN, wday).is_err());
1630        assert!(d.nth_weekday_of_month(i8::MAX, wday).is_err());
1631
1632        assert_eq!(
1633            d.nth_weekday_of_month(5, Weekday::Friday),
1634            Ok(date(2017, 3, 31))
1635        );
1636        assert_eq!(
1637            d.nth_weekday_of_month(-5, Weekday::Friday),
1638            Ok(date(2017, 3, 3))
1639        );
1640    }
1641
1642    #[test]
1643    fn nth_weekday_of_month_near_minimum_date() {
1644        let d = date(-9999, 1, 1);
1645
1646        assert_eq!(
1647            d.nth_weekday_of_month(1, Weekday::Monday),
1648            Ok(date(-9999, 1, 1))
1649        );
1650        assert_eq!(
1651            d.nth_weekday_of_month(2, Weekday::Monday),
1652            Ok(date(-9999, 1, 8))
1653        );
1654        assert_eq!(
1655            d.nth_weekday_of_month(3, Weekday::Monday),
1656            Ok(date(-9999, 1, 15))
1657        );
1658        assert_eq!(
1659            d.nth_weekday_of_month(4, Weekday::Monday),
1660            Ok(date(-9999, 1, 22))
1661        );
1662        assert_eq!(
1663            d.nth_weekday_of_month(5, Weekday::Monday),
1664            Ok(date(-9999, 1, 29))
1665        );
1666
1667        assert_eq!(
1668            d.nth_weekday_of_month(-5, Weekday::Monday),
1669            Ok(date(-9999, 1, 1))
1670        );
1671        assert_eq!(
1672            d.nth_weekday_of_month(-4, Weekday::Monday),
1673            Ok(date(-9999, 1, 8))
1674        );
1675        assert_eq!(
1676            d.nth_weekday_of_month(-3, Weekday::Monday),
1677            Ok(date(-9999, 1, 15))
1678        );
1679        assert_eq!(
1680            d.nth_weekday_of_month(-2, Weekday::Monday),
1681            Ok(date(-9999, 1, 22))
1682        );
1683        assert_eq!(
1684            d.nth_weekday_of_month(-1, Weekday::Monday),
1685            Ok(date(-9999, 1, 29))
1686        );
1687    }
1688
1689    #[test]
1690    fn nth_weekday_of_month_near_maximum_date() {
1691        let d = date(9999, 12, 1);
1692
1693        assert_eq!(
1694            d.nth_weekday_of_month(1, Weekday::Friday),
1695            Ok(date(9999, 12, 3))
1696        );
1697        assert_eq!(
1698            d.nth_weekday_of_month(2, Weekday::Friday),
1699            Ok(date(9999, 12, 10))
1700        );
1701        assert_eq!(
1702            d.nth_weekday_of_month(3, Weekday::Friday),
1703            Ok(date(9999, 12, 17))
1704        );
1705        assert_eq!(
1706            d.nth_weekday_of_month(4, Weekday::Friday),
1707            Ok(date(9999, 12, 24))
1708        );
1709        assert_eq!(
1710            d.nth_weekday_of_month(5, Weekday::Friday),
1711            Ok(date(9999, 12, 31))
1712        );
1713
1714        assert_eq!(
1715            d.nth_weekday_of_month(-5, Weekday::Friday),
1716            Ok(date(9999, 12, 3))
1717        );
1718        assert_eq!(
1719            d.nth_weekday_of_month(-4, Weekday::Friday),
1720            Ok(date(9999, 12, 10))
1721        );
1722        assert_eq!(
1723            d.nth_weekday_of_month(-3, Weekday::Friday),
1724            Ok(date(9999, 12, 17))
1725        );
1726        assert_eq!(
1727            d.nth_weekday_of_month(-2, Weekday::Friday),
1728            Ok(date(9999, 12, 24))
1729        );
1730        assert_eq!(
1731            d.nth_weekday_of_month(-1, Weekday::Friday),
1732            Ok(date(9999, 12, 31))
1733        );
1734    }
1735
1736    #[test]
1737    fn nth_weekday_of_month_every_month_has_four_weekdays() {
1738        for year in b::Year::MIN..=b::Year::MAX {
1739            for month in b::Month::MIN..=b::Month::MAX {
1740                let d = date(year, month, 1);
1741                for weekday in Weekday::Sunday.cycle_forward().take(7) {
1742                    for nth in [-4, -3, -2, -1, 1, 2, 3, 4] {
1743                        assert!(d.nth_weekday_of_month(nth, weekday).is_ok());
1744                        // never valid
1745                        assert!(d.nth_weekday_of_month(0, weekday).is_err());
1746                        assert!(d.nth_weekday_of_month(6, weekday).is_err());
1747                        assert!(d.nth_weekday_of_month(-6, weekday).is_err());
1748                    }
1749                }
1750            }
1751        }
1752    }
1753
1754    #[test]
1755    fn nth_weekday_various() {
1756        let d = date(2024, 3, 10);
1757
1758        assert_eq!(d.nth_weekday(1, Weekday::Monday), Ok(date(2024, 3, 11)));
1759        assert_eq!(d.nth_weekday(1, Weekday::Sunday), Ok(date(2024, 3, 17)));
1760        assert_eq!(d.nth_weekday(2, Weekday::Thursday), Ok(date(2024, 3, 21)));
1761
1762        assert_eq!(d.nth_weekday(-1, Weekday::Monday), Ok(date(2024, 3, 4)));
1763        assert_eq!(d.nth_weekday(-1, Weekday::Sunday), Ok(date(2024, 3, 3)));
1764        assert_eq!(
1765            d.nth_weekday(-2, Weekday::Thursday),
1766            Ok(date(2024, 2, 29))
1767        );
1768
1769        let d = date(9999, 12, 24);
1770        assert_eq!(d.nth_weekday(1, Weekday::Friday), Ok(date(9999, 12, 31)));
1771        let d = date(9999, 12, 30);
1772        assert_eq!(d.nth_weekday(1, Weekday::Friday), Ok(date(9999, 12, 31)));
1773        let d = date(9999, 12, 31);
1774        assert_eq!(d.nth_weekday(-1, Weekday::Friday), Ok(date(9999, 12, 24)));
1775        assert!(d.nth_weekday(1, Weekday::Friday).is_err());
1776
1777        let d = date(-9999, 1, 8);
1778        assert_eq!(d.nth_weekday(-1, Weekday::Monday), Ok(date(-9999, 1, 1)));
1779        let d = date(-9999, 1, 2);
1780        assert_eq!(d.nth_weekday(-1, Weekday::Monday), Ok(date(-9999, 1, 1)));
1781        let d = date(-9999, 1, 1);
1782        assert_eq!(d.nth_weekday(1, Weekday::Monday), Ok(date(-9999, 1, 8)));
1783        assert!(d.nth_weekday(-1, Weekday::Monday).is_err());
1784    }
1785
1786    #[test]
1787    fn nth_weekday_errors() {
1788        let d = date(2024, 3, 10);
1789        assert!(d.nth_weekday(0, Weekday::Monday).is_err());
1790    }
1791
1792    #[test]
1793    fn nth_weekday_extreme() {
1794        let weeks = 1_043_497;
1795
1796        let d1 = date(-9999, 1, 1);
1797        let d2 = d1.nth_weekday(weeks, Weekday::Monday).unwrap();
1798        assert_eq!(d2, date(9999, 12, 27));
1799        assert!(d1.nth_weekday(weeks + 1, Weekday::Monday).is_err());
1800        assert!(d1.nth_weekday(i32::MIN, Weekday::Monday).is_err());
1801        assert!(d1.nth_weekday(i32::MAX, Weekday::Monday).is_err());
1802
1803        let d1 = date(9999, 12, 31);
1804        let d2 = d1.nth_weekday(-weeks, Weekday::Friday).unwrap();
1805        assert_eq!(d2, date(-9999, 1, 5));
1806        assert!(d1.nth_weekday(weeks - 1, Weekday::Friday).is_err());
1807        assert!(d1.nth_weekday(i32::MIN, Weekday::Friday).is_err());
1808        assert!(d1.nth_weekday(i32::MAX, Weekday::Friday).is_err());
1809    }
1810
1811    #[test]
1812    fn yesterday() {
1813        assert_eq!(date(2024, 7, 3).yesterday(), Ok(date(2024, 7, 2)));
1814        assert_eq!(date(2024, 7, 1).yesterday(), Ok(date(2024, 6, 30)));
1815        assert_eq!(date(2024, 6, 1).yesterday(), Ok(date(2024, 5, 31)));
1816        assert_eq!(date(2024, 3, 1).yesterday(), Ok(date(2024, 2, 29)));
1817        assert_eq!(date(2023, 3, 1).yesterday(), Ok(date(2023, 2, 28)));
1818        assert_eq!(date(2023, 1, 1).yesterday(), Ok(date(2022, 12, 31)));
1819        assert_eq!(date(-9999, 1, 2).yesterday(), Ok(date(-9999, 1, 1)));
1820        assert_eq!(date(9999, 12, 31).yesterday(), Ok(date(9999, 12, 30)));
1821
1822        assert!(date(-9999, 1, 1).yesterday().is_err());
1823    }
1824
1825    #[test]
1826    fn tomorrow() {
1827        assert_eq!(date(2024, 7, 3).tomorrow(), Ok(date(2024, 7, 4)));
1828        assert_eq!(date(2024, 6, 30).tomorrow(), Ok(date(2024, 7, 1)));
1829        assert_eq!(date(2024, 5, 30).tomorrow(), Ok(date(2024, 5, 31)));
1830        assert_eq!(date(2024, 5, 31).tomorrow(), Ok(date(2024, 6, 1)));
1831        assert_eq!(date(2024, 2, 28).tomorrow(), Ok(date(2024, 2, 29)));
1832        assert_eq!(date(2024, 2, 29).tomorrow(), Ok(date(2024, 3, 1)));
1833        assert_eq!(date(2023, 2, 28).tomorrow(), Ok(date(2023, 3, 1)));
1834        assert_eq!(date(2023, 12, 31).tomorrow(), Ok(date(2024, 1, 1)));
1835        assert_eq!(date(-9999, 1, 1).tomorrow(), Ok(date(-9999, 1, 2)));
1836        assert_eq!(date(9999, 12, 30).tomorrow(), Ok(date(9999, 12, 31)));
1837
1838        assert!(date(9999, 12, 31).tomorrow().is_err());
1839    }
1840
1841    #[test]
1842    fn iso_week_date_tomorrow() {
1843        assert_eq!(
1844            week_date(2024, 27, Weekday::Wednesday).tomorrow(),
1845            Ok(week_date(2024, 27, Weekday::Thursday)),
1846        );
1847        assert_eq!(
1848            week_date(2024, 27, Weekday::Sunday).tomorrow(),
1849            Ok(week_date(2024, 28, Weekday::Monday)),
1850        );
1851        assert_eq!(
1852            week_date(2024, 52, Weekday::Sunday).tomorrow(),
1853            Ok(week_date(2025, 1, Weekday::Monday)),
1854        );
1855        assert_eq!(
1856            week_date(2025, 1, Weekday::Monday).tomorrow(),
1857            Ok(week_date(2025, 1, Weekday::Tuesday)),
1858        );
1859        assert_eq!(
1860            week_date(2025, 1, Weekday::Tuesday).tomorrow(),
1861            Ok(week_date(2025, 1, Weekday::Wednesday)),
1862        );
1863        assert_eq!(
1864            week_date(2026, 52, Weekday::Sunday).tomorrow(),
1865            Ok(week_date(2026, 53, Weekday::Monday)),
1866        );
1867        assert_eq!(
1868            week_date(2026, 53, Weekday::Sunday).tomorrow(),
1869            Ok(week_date(2027, 1, Weekday::Monday)),
1870        );
1871        assert_eq!(
1872            week_date(-9999, 1, Weekday::Monday).tomorrow(),
1873            Ok(week_date(-9999, 1, Weekday::Tuesday)),
1874        );
1875        assert_eq!(
1876            week_date(9999, 52, Weekday::Thursday).tomorrow(),
1877            Ok(week_date(9999, 52, Weekday::Friday)),
1878        );
1879
1880        assert!(week_date(9999, 52, Weekday::Friday).tomorrow().is_err());
1881    }
1882
1883    #[test]
1884    fn iso_week_date_yesterday() {
1885        assert_eq!(
1886            week_date(2024, 27, Weekday::Thursday).yesterday(),
1887            Ok(week_date(2024, 27, Weekday::Wednesday)),
1888        );
1889        assert_eq!(
1890            week_date(2024, 28, Weekday::Monday).yesterday(),
1891            Ok(week_date(2024, 27, Weekday::Sunday)),
1892        );
1893        assert_eq!(
1894            week_date(2025, 1, Weekday::Monday).yesterday(),
1895            Ok(week_date(2024, 52, Weekday::Sunday)),
1896        );
1897        assert_eq!(
1898            week_date(2025, 1, Weekday::Tuesday).yesterday(),
1899            Ok(week_date(2025, 1, Weekday::Monday)),
1900        );
1901        assert_eq!(
1902            week_date(2025, 1, Weekday::Wednesday).yesterday(),
1903            Ok(week_date(2025, 1, Weekday::Tuesday)),
1904        );
1905        assert_eq!(
1906            week_date(2026, 53, Weekday::Monday).yesterday(),
1907            Ok(week_date(2026, 52, Weekday::Sunday)),
1908        );
1909        assert_eq!(
1910            week_date(2027, 1, Weekday::Monday).yesterday(),
1911            Ok(week_date(2026, 53, Weekday::Sunday)),
1912        );
1913        assert_eq!(
1914            week_date(9999, 12, Weekday::Friday).yesterday(),
1915            Ok(week_date(9999, 12, Weekday::Thursday)),
1916        );
1917        assert_eq!(
1918            week_date(-9999, 1, Weekday::Tuesday).yesterday(),
1919            Ok(week_date(-9999, 1, Weekday::Monday)),
1920        );
1921
1922        assert!(week_date(-9999, 1, Weekday::Monday).yesterday().is_err());
1923    }
1924
1925    #[test]
1926    fn add() {
1927        assert_eq!(date(2024, 7, 3).checked_add(-1), Ok(date(2024, 7, 2)));
1928        assert_eq!(date(2024, 7, 1).checked_add(-1), Ok(date(2024, 6, 30)));
1929        assert_eq!(date(2024, 6, 1).checked_add(-1), Ok(date(2024, 5, 31)));
1930        assert_eq!(date(2024, 3, 1).checked_add(-1), Ok(date(2024, 2, 29)));
1931        assert_eq!(date(2023, 3, 1).checked_add(-1), Ok(date(2023, 2, 28)));
1932        assert_eq!(date(2023, 1, 1).checked_add(-1), Ok(date(2022, 12, 31)));
1933        assert_eq!(date(-9999, 1, 2).checked_add(-1), Ok(date(-9999, 1, 1)));
1934        assert_eq!(date(9999, 12, 31).checked_add(-1), Ok(date(9999, 12, 30)));
1935
1936        assert_eq!(date(2024, 7, 3).checked_add(1), Ok(date(2024, 7, 4)));
1937        assert_eq!(date(2024, 6, 30).checked_add(1), Ok(date(2024, 7, 1)));
1938        assert_eq!(date(2024, 5, 30).checked_add(1), Ok(date(2024, 5, 31)));
1939        assert_eq!(date(2024, 5, 31).checked_add(1), Ok(date(2024, 6, 1)));
1940        assert_eq!(date(2024, 2, 28).checked_add(1), Ok(date(2024, 2, 29)));
1941        assert_eq!(date(2024, 2, 29).checked_add(1), Ok(date(2024, 3, 1)));
1942        assert_eq!(date(2023, 2, 28).checked_add(1), Ok(date(2023, 3, 1)));
1943        assert_eq!(date(2023, 12, 31).checked_add(1), Ok(date(2024, 1, 1)));
1944        assert_eq!(date(-9999, 1, 1).checked_add(1), Ok(date(-9999, 1, 2)));
1945        assert_eq!(date(9999, 12, 30).checked_add(1), Ok(date(9999, 12, 31)));
1946
1947        assert_eq!(date(2024, 7, 3).checked_add(2), Ok(date(2024, 7, 5)));
1948        assert_eq!(date(2024, 6, 29).checked_add(2), Ok(date(2024, 7, 1)));
1949        assert_eq!(date(2024, 5, 29).checked_add(2), Ok(date(2024, 5, 31)));
1950        assert_eq!(date(2024, 5, 30).checked_add(2), Ok(date(2024, 6, 1)));
1951        assert_eq!(date(2024, 2, 27).checked_add(2), Ok(date(2024, 2, 29)));
1952        assert_eq!(date(2024, 2, 28).checked_add(2), Ok(date(2024, 3, 1)));
1953        assert_eq!(date(2023, 2, 27).checked_add(2), Ok(date(2023, 3, 1)));
1954        assert_eq!(date(2023, 12, 30).checked_add(2), Ok(date(2024, 1, 1)));
1955        assert_eq!(date(-9999, 1, 1).checked_add(2), Ok(date(-9999, 1, 3)));
1956        assert_eq!(date(9999, 12, 29).checked_add(2), Ok(date(9999, 12, 31)));
1957
1958        let max_days = (b::UnixEpochDays::LEN - 1) as i32;
1959
1960        assert_eq!(
1961            date(-9999, 1, 1).checked_add(max_days),
1962            Ok(date(9999, 12, 31))
1963        );
1964        assert_eq!(
1965            date(9999, 12, 31).checked_add(-max_days),
1966            Ok(date(-9999, 1, 1))
1967        );
1968
1969        assert!(date(-9999, 1, 1).checked_add(-1).is_err());
1970        assert!(date(9999, 12, 31).checked_add(1).is_err());
1971        assert!(date(-9999, 1, 1).checked_add(max_days + 1).is_err());
1972        assert!(date(9999, 12, 31).checked_add(-(max_days + 1)).is_err());
1973    }
1974
1975    #[test]
1976    fn sub() {
1977        assert_eq!(date(-9999, 1, 1).checked_sub(-1), Ok(date(-9999, 1, 2)));
1978        assert_eq!(date(-9999, 1, 1).checked_sub(-2), Ok(date(-9999, 1, 3)));
1979
1980        assert!(date(-9999, 1, 1).checked_sub(1).is_err());
1981        assert!(date(-9999, 1, 1).checked_sub(i32::MIN).is_err());
1982        assert!(date(9999, 12, 31).checked_sub(i32::MAX).is_err());
1983    }
1984
1985    #[test]
1986    fn prev_year() {
1987        assert_eq!(date(2024, 2, 29).prev_year(), Ok(2023));
1988        assert_eq!(date(2024, 1, 1).prev_year(), Ok(2023));
1989        assert_eq!(date(2023, 12, 31).prev_year(), Ok(2022));
1990        assert_eq!(date(9999, 12, 31).prev_year(), Ok(9998));
1991
1992        assert!(date(-9999, 12, 31).prev_year().is_err());
1993        assert!(date(-9999, 1, 1).prev_year().is_err());
1994    }
1995
1996    #[test]
1997    fn next_year() {
1998        assert_eq!(date(2024, 2, 29).next_year(), Ok(2025));
1999        assert_eq!(date(2024, 1, 1).next_year(), Ok(2025));
2000        assert_eq!(date(2023, 12, 31).next_year(), Ok(2024));
2001        assert_eq!(date(-9999, 12, 31).next_year(), Ok(-9998));
2002
2003        assert!(date(9999, 12, 31).next_year().is_err());
2004        assert!(date(9999, 1, 1).next_year().is_err());
2005    }
2006
2007    #[test]
2008    fn to_iso_week_date_various() {
2009        assert_eq!(
2010            date(1995, 1, 1).to_iso_week_date(),
2011            week_date(1994, 52, Weekday::Sunday),
2012        );
2013        assert_eq!(
2014            date(1996, 12, 31).to_iso_week_date(),
2015            week_date(1997, 1, Weekday::Tuesday),
2016        );
2017        assert_eq!(
2018            date(2019, 12, 30).to_iso_week_date(),
2019            week_date(2020, 1, Weekday::Monday),
2020        );
2021        assert_eq!(
2022            date(2031, 12, 29).to_iso_week_date(),
2023            week_date(2032, 1, Weekday::Monday),
2024        );
2025        assert_eq!(
2026            date(2024, 3, 9).to_iso_week_date(),
2027            week_date(2024, 10, Weekday::Saturday),
2028        );
2029        assert_eq!(
2030            Date::MIN.to_iso_week_date(),
2031            week_date(-9999, 1, Weekday::Monday),
2032        );
2033        assert_eq!(
2034            Date::MAX.to_iso_week_date(),
2035            week_date(9999, 52, Weekday::Friday),
2036        );
2037    }
2038
2039    quickcheck::quickcheck! {
2040        fn prop_tomorrow_yesterday_is_identity(d: Date) -> quickcheck::TestResult {
2041            let Ok(yesterday) = d.yesterday() else {
2042                return quickcheck::TestResult::discard()
2043            };
2044            quickcheck::TestResult::from_bool(yesterday.tomorrow() == Ok(d))
2045        }
2046
2047        fn prop_yesterday_tomorrow_is_identity(d: Date) -> quickcheck::TestResult {
2048            let Ok(tomorrow) = d.tomorrow() else {
2049                return quickcheck::TestResult::discard()
2050            };
2051            quickcheck::TestResult::from_bool(tomorrow.yesterday() == Ok(d))
2052        }
2053
2054        fn prop_add_equals_sub(d1: Date, days: i32) -> quickcheck::TestResult {
2055            let Ok(d2) = d1.checked_add(days) else {
2056                return quickcheck::TestResult::discard();
2057            };
2058            quickcheck::TestResult::from_bool(d2.checked_sub(days) == Ok(d1))
2059        }
2060
2061        fn prop_all_long_years_have_53rd_week(year: i16) -> quickcheck::TestResult {
2062            if b::ISOYear::check(year).is_err() {
2063                return 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        }
2070
2071        fn prop_prev_day_is_less(wd: ISOWeekDate) -> quickcheck::TestResult {
2072            let Ok(prev_date) = wd.to_date().yesterday() else {
2073                return quickcheck::TestResult::discard();
2074            };
2075            quickcheck::TestResult::from_bool(
2076                prev_date.to_iso_week_date() < wd,
2077            )
2078        }
2079
2080        fn prop_next_day_is_greater(wd: ISOWeekDate) -> quickcheck::TestResult {
2081            let Ok(next_date) = wd.to_date().tomorrow() else {
2082                return quickcheck::TestResult::discard();
2083            };
2084            quickcheck::TestResult::from_bool(
2085                wd < next_date.to_iso_week_date(),
2086            )
2087        }
2088
2089        fn prop_iso_tomorrow_yesterday_is_identity(
2090            wd: ISOWeekDate
2091        ) -> quickcheck::TestResult {
2092            let Ok(yesterday) = wd.yesterday() else {
2093                return quickcheck::TestResult::discard()
2094            };
2095            quickcheck::TestResult::from_bool(yesterday.tomorrow() == Ok(wd))
2096        }
2097
2098        fn prop_iso_yesterday_tomorrow_is_identity(
2099            wd: ISOWeekDate
2100        ) -> quickcheck::TestResult {
2101            let Ok(tomorrow) = wd.tomorrow() else {
2102                return quickcheck::TestResult::discard()
2103            };
2104            quickcheck::TestResult::from_bool(tomorrow.yesterday() == Ok(wd))
2105        }
2106    }
2107}