Debian Codegraph @

debian/rust-vendor/icu_calendar/src/date.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 use crate::calendar_arithmetic::VALID_RD_RANGE;
6 use crate::error::{DateAddError, DateError, DateFromFieldsError, DateNewError};
7 use crate::options::DateFromFieldsOptions;
8 use crate::options::{DateAddOptions, DateDifferenceOptions};
9 use crate::types::{CyclicYear, EraYear, IsoWeekOfYear};
10 use crate::week::{RelativeUnit, WeekCalculator, WeekOf};
11 use crate::{Calendar, Iso, types};
12 #[cfg(feature = "alloc")]
13 use alloc::rc::Rc;
14 #[cfg(feature = "alloc")]
15 use alloc::sync::Arc;
16 use calendrical_calculations::rata_die::RataDie;
17 use core::fmt;
18 use core::ops::Deref;
19
20 /// Types that contain a calendar
21 ///
22 /// This allows one to use [`Date`] with wrappers around calendars,
23 /// e.g. reference counted calendars.
24 pub trait AsCalendar {
25 /// The calendar being wrapped
26 type Calendar: Calendar;
27 /// Obtain the inner calendar
28 fn as_calendar(&self) -> &Self::Calendar;
29 }
30
31 impl<C: Calendar> AsCalendar for C {
32 type Calendar = C;
33 #[inline]
34 fn as_calendar(&self) -> &Self {
35 self
36 }
37 }
38
39 #[cfg(feature = "alloc")]
40 /// ✨ *Enabled with the `alloc` Cargo feature.*
41 impl<C: AsCalendar> AsCalendar for Rc<C> {
42 type Calendar = C::Calendar;
43 #[inline]
44 fn as_calendar(&self) -> &Self::Calendar {
45 self.as_ref().as_calendar()
46 }
47 }
48
49 #[cfg(feature = "alloc")]
50 /// ✨ *Enabled with the `alloc` Cargo feature.*
51 impl<C: AsCalendar> AsCalendar for Arc<C> {
52 type Calendar = C::Calendar;
53 #[inline]
54 fn as_calendar(&self) -> &Self::Calendar {
55 self.as_ref().as_calendar()
56 }
57 }
58
59 /// This exists as a wrapper around `&'a T` so that
60 /// `Date<&'a C>` is possible for calendar `C`.
61 ///
62 /// Unfortunately,
63 /// [`AsCalendar`] cannot be implemented on `&'a T` directly because
64 /// `&'a T` is `#[fundamental]` and the impl would clash with the one above with
65 /// `AsCalendar` for `C: Calendar`.
66 ///
67 /// Use `Date<Ref<'a, C>>` where you would use `Date<&'a C>`
68 #[allow(clippy::exhaustive_structs)] // newtype
69 #[derive(PartialEq, Eq, Debug)]
70 pub struct Ref<'a, C>(pub &'a C);
71
72 impl<C> Copy for Ref<'_, C> {}
73
74 impl<C> Clone for Ref<'_, C> {
75 fn clone(&self) -> Self {
76 *self
77 }
78 }
79
80 impl<C: AsCalendar> AsCalendar for Ref<'_, C> {
81 type Calendar = C::Calendar;
82 #[inline]
83 fn as_calendar(&self) -> &Self::Calendar {
84 self.0.as_calendar()
85 }
86 }
87
88 impl<C> Deref for Ref<'_, C> {
89 type Target = C;
90 fn deref(&self) -> &C {
91 self.0
92 }
93 }
94
95 /// A date for a given calendar.
96 ///
97 /// **The primary definition of this type is in the [`icu_calendar`](https://docs.rs/icu_calendar) crate. Other ICU4X crates re-export it for convenience.**
98 ///
99 /// Options to create one of these:
100 ///
101 /// 1. Generically from fields via [`Self::try_from_fields()`] or [`Self::try_new()`]
102 /// 2. With calendar-specific constructors, e.g. [`Self::try_new_chinese_traditional()`]
103 /// 3. From a RFC 9557 string via [`Self::try_from_str()`]
104 /// 4. From a [`RataDie`] via [`Self::from_rata_die()`]
105 ///
106 /// # Date ranges
107 ///
108 /// *Most* `Date` constructors will refuse to construct dates from `year` values outside of the range
109 /// `-9999..=9999`, however since that is a per-calendar value, it is possible to escape that range
110 /// by changing the era/calendar. Furthermore, this is not the case for [`Date::try_from_fields`] and
111 /// date arithmetic APIs: these APIs let you construct dates outside of that range.
112 ///
113 /// The `Date` type has a fundamental range invariant as well, and it's not possible to construct
114 /// dates outside of that range, regardless of the calendar.
115 /// APIs will return an `Overflow` error (e.g. `DateAddError::Overflow`) in these cases, or clamp
116 /// in the case of `Date::from_rata_die()`.
117 ///
118 /// This range is currently dates with an ISO year between `-999_999..=999_999`, but
119 /// we reserve the right to change these bounds in the future.
120 ///
121 /// Since `icu_calendar` is intended to be usable by implementors of the ECMA Temporal specification,
122 /// this range will never be smaller than Temporal's validity range, which roughly maps to ISO years
123 /// -271,821 to 275,760 (precisely speaking, it is ± 100,000,000 days from January 1, 1970).
124 ///
125 /// # Examples
126 ///
127 /// ```rust
128 /// use icu::calendar::Date;
129 ///
130 /// // Example: creation of ISO date from integers.
131 /// let date_iso = Date::try_new_iso(1970, 1, 2)
132 /// .expect("Failed to initialize ISO Date instance.");
133 ///
134 /// assert_eq!(date_iso.era_year().year, 1970);
135 /// assert_eq!(date_iso.month().ordinal, 1);
136 /// assert_eq!(date_iso.day_of_month().0, 2);
137 /// ```
138 pub struct Date<A: AsCalendar> {
139 inner: <A::Calendar as Calendar>::DateInner,
140 calendar: A,
141 }
142
143 impl<A: AsCalendar> Date<A> {
144 /// Construct a [`Date`] from from era, year, month, and day fields, and a calendar.
145 ///
146 /// The year is interpreted as an [`extended_year`](Date::extended_year) if no era is provided.
147 ///
148 /// This function accepts years in the range `-9999..=9999`.
149 #[inline]
150 #[deprecated(since = "2.2.0", note = "use `Date::try_new`")]
151 pub fn try_new_from_codes(
152 era: Option<&str>,
153 year: i32,
154 month_code: types::MonthCode,
155 day: u8,
156 calendar: A,
157 ) -> Result<Self, DateError> {
158 #[allow(deprecated, reason = "internal usage")]
159 let inner = calendar
160 .as_calendar()
161 .from_codes(era, year, month_code, day)?;
162
163 Ok(Date::from_raw(inner, calendar))
164 }
165
166 /// Construct a [`Date`] from era, year, month, and day fields, and a calendar.
167 ///
168 /// This function accepts years in the range `-9999..=9999`.
169 ///
170 /// # Examples
171 ///
172 /// ```rust
173 /// use icu::calendar::Date;
174 /// use icu::calendar::Iso;
175 /// use icu::calendar::types::{Month, YearInput};
176 ///
177 /// // Example: creation of ISO date from integers.
178 /// let date_iso = Date::try_new(1970.into(), Month::new(1), 2, Iso)
179 /// .expect("Failed to initialize ISO Date instance.");
180 ///
181 /// // Shorthand using From impls:
182 /// assert_eq!(
183 /// date_iso,
184 /// Date::try_new(1970.into(), 1.into(), 2, Iso).unwrap()
185 /// );
186 ///
187 /// assert_eq!(date_iso.era_year().year, 1970);
188 /// assert_eq!(date_iso.month().ordinal, 1);
189 /// assert_eq!(date_iso.day_of_month().0, 2);
190 /// ```
191 #[inline]
192 pub fn try_new(
193 year: types::YearInput,
194 month: types::Month,
195 day: u8,
196 calendar: A,
197 ) -> Result<Self, DateNewError> {
198 let inner = calendar.as_calendar().new_date(year, month, day)?;
199 Ok(Date::from_raw(inner, calendar))
200 }
201
202 /// Construct a [`Date`] from from a bag of fields and a calendar.
203 ///
204 /// This function allows specifying the year as either extended year or era + era year,
205 /// and the month as either ordinal or month code. It can constrain out-of-bounds values
206 /// and fill in missing fields. See [`DateFromFieldsOptions`] for more information.
207 ///
208 /// This API will not construct dates outside of the fundamental range described on the [`Date`] type
209 /// instead returning [`DateFromFieldsError::Overflow`].
210 ///
211 /// # Examples
212 ///
213 /// ```
214 /// use icu::calendar::Date;
215 /// use icu::calendar::cal::Gregorian;
216 /// use icu::calendar::types::DateFields;
217 ///
218 /// let mut fields = DateFields::default();
219 /// fields.extended_year = Some(2000);
220 /// fields.ordinal_month = Some(1);
221 /// fields.day = Some(1);
222 ///
223 /// let d1 = Date::try_from_fields(fields, Default::default(), Gregorian)
224 /// .expect("Jan 1 in year 2000");
225 ///
226 /// let d2 = Date::try_new_gregorian(2000, 1, 1).unwrap();
227 /// assert_eq!(d1, d2);
228 /// ```
229 ///
230 /// See [`DateFromFieldsError`] for examples of error conditions.
231 #[inline]
232 pub fn try_from_fields(
233 fields: types::DateFields,
234 options: DateFromFieldsOptions,
235 calendar: A,
236 ) -> Result<Self, DateFromFieldsError> {
237 let inner = calendar.as_calendar().from_fields(fields, options)?;
238 Ok(Date::from_raw(inner, calendar))
239 }
240
241 /// Construct a date from a [`RataDie`] and a calendar.
242 ///
243 /// This method is guaranteed to round trip with [`Date::to_rata_die`].
244 ///
245 /// For other values, This API will not construct dates outside of the fundamental range
246 /// described on the [`Date`] type instead clamping the result:
247 ///
248 /// ```rust
249 /// use icu::calendar::{Date, Gregorian, types::RataDie};
250 ///
251 /// let rd = RataDie::new(1_000_000_000);
252 /// assert_ne!(Date::from_rata_die(rd, Gregorian).to_rata_die(), rd);
253 /// ```
254 #[inline]
255 pub fn from_rata_die(rd: RataDie, calendar: A) -> Self {
256 let rd = rd.clamp(*VALID_RD_RANGE.start(), *VALID_RD_RANGE.end());
257 Date::from_raw(calendar.as_calendar().from_rata_die(rd), calendar)
258 }
259
260 /// Convert the date to a [`RataDie`]
261 ///
262 /// This method is guaranteed to round trip with [`Date::from_rata_die`].
263 #[inline]
264 pub fn to_rata_die(&self) -> RataDie {
265 self.calendar.as_calendar().to_rata_die(self.inner())
266 }
267
268 /// Construct a [`Date`] from an ISO date and a calendar.
269 #[inline]
270 #[deprecated(since = "2.2.0", note = "use `iso.to_calendar(calendar)`")]
271 pub fn new_from_iso(iso: Date<Iso>, calendar: A) -> Self {
272 iso.to_calendar(calendar)
273 }
274
275 /// Convert the [`Date`] to an ISO Date
276 #[inline]
277 #[deprecated(since = "2.2.0", note = "use `date.to_calendar(Iso)`")]
278 pub fn to_iso(&self) -> Date<Iso> {
279 self.to_calendar(Iso)
280 }
281
282 /// Convert the [`Date`] to a different calendar
283 #[inline]
284 pub fn to_calendar<A2: AsCalendar>(&self, calendar: A2) -> Date<A2> {
285 let c1 = self.calendar.as_calendar();
286 let c2 = calendar.as_calendar();
287 let inner = if c1.has_cheap_iso_conversion() && c2.has_cheap_iso_conversion() {
288 // no-op
289 c2.from_iso(c1.to_iso(self.inner()))
290 } else {
291 // `from_rata_die` precondition is satified by `to_rata_die`
292 c2.from_rata_die(c1.to_rata_die(self.inner()))
293 };
294 Date::from_raw(inner, calendar)
295 }
296
297 /// The day-of-month of this date.
298 #[inline]
299 pub fn day_of_month(&self) -> types::DayOfMonth {
300 self.calendar.as_calendar().day_of_month(&self.inner)
301 }
302
303 /// The day-of-year of this date.
304 #[inline]
305 pub fn day_of_year(&self) -> types::DayOfYear {
306 self.calendar.as_calendar().day_of_year(&self.inner)
307 }
308
309 /// The weekday of this date.
310 #[inline]
311 pub fn weekday(&self) -> types::Weekday {
312 self.to_rata_die().into()
313 }
314
315 /// The weekday of this date.
316 ///
317 /// This is *not* the day of the week, an ordinal number that is locale
318 /// dependent.
319 #[deprecated(since = "2.2.0", note = "use `Date::weekday`")]
320 pub fn day_of_week(&self) -> types::Weekday {
321 self.to_rata_die().into()
322 }
323
324 /// The month of this date.
325 #[inline]
326 pub fn month(&self) -> types::MonthInfo {
327 self.calendar.as_calendar().month(&self.inner)
328 }
329
330 /// The year of this date.
331 ///
332 /// This returns an enum, see [`Date::era_year()`] and [`Date::cyclic_year()`] which are available
333 /// for concrete calendar types and return concrete types.
334 #[inline]
335 pub fn year(&self) -> types::YearInfo {
336 self.calendar.as_calendar().year_info(&self.inner).into()
337 }
338
339 /// Use [`YearInfo::extended_year`](types::YearInfo::extended_year)
340 #[inline]
341 #[deprecated(since = "2.2.0", note = "use `date.year().extended_year()`")]
342 pub fn extended_year(&self) -> i32 {
343 self.year().extended_year()
344 }
345
346 /// Whether this date is in a leap year.
347 #[inline]
348 pub fn is_in_leap_year(&self) -> bool {
349 self.calendar.as_calendar().is_in_leap_year(&self.inner)
350 }
351
352 /// The number of days in the month of this date.
353 #[inline]
354 pub fn days_in_month(&self) -> u8 {
355 self.calendar.as_calendar().days_in_month(self.inner())
356 }
357
358 /// The number of days in the year of this date.
359 #[inline]
360 pub fn days_in_year(&self) -> u16 {
361 self.calendar.as_calendar().days_in_year(self.inner())
362 }
363
364 /// The number of months in the year of this date.
365 #[inline]
366 pub fn months_in_year(&self) -> u8 {
367 self.calendar.as_calendar().months_in_year(self.inner())
368 }
369
370 /// Add a `duration` to this [`Date`], mutating it.
371 ///
372 /// This API will not construct dates outside of the fundamental range described on the [`Date`] type,
373 /// instead returning [`DateAddError::Overflow`].
374 #[inline]
375 pub fn try_add_with_options(
376 &mut self,
377 duration: types::DateDuration,
378 options: DateAddOptions,
379 ) -> Result<(), DateAddError> {
380 let inner = self
381 .calendar
382 .as_calendar()
383 .add(&self.inner, duration, options)?;
384 self.inner = inner;
385 Ok(())
386 }
387
388 /// Add a `duration` to this [`Date`].
389 ///
390 /// This API will not construct dates outside of the fundamental range described on the [`Date`] type,
391 /// instead returning [`DateAddError::Overflow`].
392 #[inline]
393 pub fn try_added_with_options(
394 mut self,
395 duration: types::DateDuration,
396 options: DateAddOptions,
397 ) -> Result<Self, DateAddError> {
398 self.try_add_with_options(duration, options)?;
399 Ok(self)
400 }
401
402 /// Calculating the duration between `other - self`, counting from `self`
403 ///
404 /// Although this returns a [`Result`], with most fixed calendars, this operation can't fail.
405 /// In such cases, the error type is [`Infallible`], and the inner value can be safely
406 /// unwrapped using [`Result::into_ok()`], which is available in nightly Rust as of this
407 /// writing. In stable Rust, the value can be unwrapped using [pattern matching].
408 ///
409 /// Note that `a.try_until_with_options(b, ..)` is not necessarily the same as
410 /// `-b.try_until_with_options(a, ..)`. `a.try_until_with_options(b, ..)`
411 /// computes a duration starting at `a` by adding years, months, sometimes weeks, and days in order
412 /// (based on the options) until it reaches `b`. So, `(Sep 30).until(Oct 31)` with `largest_unit = DateDurationUnit::Months`
413 /// will be a duration of 1 month and 1 day, but `(Oct 31).until(Sep 30)` will be a duration of -1 months.
414 ///
415 /// # Examples
416 ///
417 /// ```
418 /// use icu::calendar::Date;
419 /// use icu::calendar::types::DateDuration;
420 ///
421 /// let d1 = Date::try_new_iso(2020, 1, 1).unwrap();
422 /// let d2 = Date::try_new_iso(2025, 10, 2).unwrap();
423 /// let options = Default::default();
424 ///
425 /// // The value can be unwrapped with destructuring syntax:
426 /// let Ok(duration) = d1.try_until_with_options(&d2, options);
427 ///
428 /// assert_eq!(duration, DateDuration::for_days(2101));
429 /// ```
430 ///
431 /// Reversing the order of parameters does not necessarily produce the inverse result:
432 ///
433 /// ```
434 /// use icu::calendar::Date;
435 /// use icu::calendar::options::{DateDifferenceOptions, DateDurationUnit};
436 /// use icu::calendar::types::DateDuration;
437 ///
438 /// let d1 = Date::try_new_iso(2025, 9, 30).unwrap();
439 /// let d2 = Date::try_new_iso(2025, 10, 31).unwrap();
440 /// let mut options = DateDifferenceOptions::default();
441 /// options.largest_unit = Some(DateDurationUnit::Months);
442 ///
443 /// let Ok(duration_forward) = d1.try_until_with_options(&d2, options);
444 /// let Ok(duration_backward) = d2.try_until_with_options(&d1, options);
445 ///
446 /// assert_eq!(
447 /// duration_forward,
448 /// DateDuration {
449 /// months: 1,
450 /// days: 1,
451 /// ..Default::default()
452 /// }
453 /// );
454 /// assert_eq!(duration_backward, DateDuration::for_months(-1));
455 /// ```
456 ///
457 /// [`Infallible`]: core::convert::Infallible
458 /// [pattern matching]: https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html
459 #[inline]
460 pub fn try_until_with_options<B: AsCalendar<Calendar = A::Calendar>>(
461 &self,
462 other: &Date<B>,
463 options: DateDifferenceOptions,
464 ) -> Result<types::DateDuration, <A::Calendar as Calendar>::DateCompatibilityError> {
465 self.calendar().check_date_compatibility(other.calendar())?;
466 Ok(self
467 .calendar
468 .as_calendar()
469 .until(self.inner(), other.inner(), options))
470 }
471
472 /// Construct a date from raw values for a given calendar. This does not check any
473 /// invariants for the date and calendar, and should only be called by calendar implementations.
474 ///
475 /// Calling this outside of calendar implementations is sound, but calendar implementations are not
476 /// expected to do anything sensible with such invalid dates.
477 ///
478 /// [`AnyCalendar`](crate::AnyCalendar) *will* panic if `Date<AnyCalendar>` objects with mismatching
479 /// date and calendar types are encountered.
480 #[inline]
481 pub fn from_raw(inner: <A::Calendar as Calendar>::DateInner, calendar: A) -> Self {
482 Self { inner, calendar }
483 }
484
485 /// Get the inner date implementation. Should not be called outside of calendar implementations
486 #[inline]
487 pub fn inner(&self) -> &<A::Calendar as Calendar>::DateInner {
488 &self.inner
489 }
490
491 /// Get a reference to the contained calendar
492 #[inline]
493 pub fn calendar(&self) -> &A::Calendar {
494 self.calendar.as_calendar()
495 }
496
497 #[inline]
498 pub(crate) fn into_calendar(self) -> A {
499 self.calendar
500 }
501
502 /// Get a reference to the contained calendar wrapper
503 ///
504 /// (Useful in case the user wishes to e.g. clone an Rc)
505 #[inline]
506 pub fn calendar_wrapper(&self) -> &A {
507 &self.calendar
508 }
509 }
510
511 impl<A: AsCalendar<Calendar = C>, C: Calendar<Year = EraYear>> Date<A> {
512 /// The year and era of this date.
513 pub fn era_year(&self) -> EraYear {
514 self.calendar.as_calendar().year_info(self.inner())
515 }
516 }
517
518 impl<A: AsCalendar<Calendar = C>, C: Calendar<Year = CyclicYear>> Date<A> {
519 /// The cyclic year of this date.
520 pub fn cyclic_year(&self) -> CyclicYear {
521 self.calendar.as_calendar().year_info(self.inner())
522 }
523 }
524
525 impl Date<Iso> {
526 /// The ISO week of the year containing this date.
527 ///
528 /// # Examples
529 ///
530 /// ```
531 /// use icu::calendar::Date;
532 /// use icu::calendar::types::IsoWeekOfYear;
533 ///
534 /// let date = Date::try_new_iso(2022, 8, 26).unwrap();
535 ///
536 /// assert_eq!(
537 /// date.week_of_year(),
538 /// IsoWeekOfYear {
539 /// week_number: 34,
540 /// iso_year: 2022,
541 /// }
542 /// );
543 /// ```
544 pub fn week_of_year(&self) -> IsoWeekOfYear {
545 let iso_year = self.inner.0.year().to_iso_year();
546
547 let week_of = WeekCalculator::ISO
548 .week_of(
549 365 + calendrical_calculations::gregorian::is_leap_year(iso_year - 1) as u16,
550 self.days_in_year(),
551 self.day_of_year().0,
552 self.weekday(),
553 )
554 .unwrap_or_else(|_| {
555 // ISO calendar has more than 14 days per year
556 debug_assert!(false);
557 WeekOf {
558 week: 1,
559 unit: RelativeUnit::Current,
560 }
561 });
562
563 IsoWeekOfYear {
564 week_number: week_of.week,
565 iso_year: match week_of.unit {
566 RelativeUnit::Current => iso_year,
567 RelativeUnit::Next => iso_year + 1,
568 RelativeUnit::Previous => iso_year - 1,
569 },
570 }
571 }
572 }
573
574 impl<A: AsCalendar> Date<A> {
575 /// Wrap the contained calendar type in `Rc<T>`, making it cheaper to clone.
576 ///
577 /// Useful when paired with [`Self::to_any()`] to obtain a `Date<Rc<AnyCalendar>>`
578 ///
579 /// ✨ *Enabled with the `alloc` Cargo feature.*
580 #[cfg(feature = "alloc")]
581 pub fn into_ref_counted(self) -> Date<Rc<A>> {
582 Date::from_raw(self.inner, Rc::new(self.calendar))
583 }
584
585 /// Wrap the contained calendar type in `Arc<T>`, making it cheaper to clone in a thread-safe manner.
586 ///
587 /// Useful when paired with [`Self::to_any()`] to obtain a `Date<Arc<AnyCalendar>>`
588 ///
589 /// ✨ *Enabled with the `alloc` Cargo feature.*
590 #[cfg(feature = "alloc")]
591 pub fn into_atomic_ref_counted(self) -> Date<Arc<A>> {
592 Date::from_raw(self.inner, Arc::new(self.calendar))
593 }
594
595 /// Wrap the calendar type in `Ref<T>`, making it cheaper to clone (by introducing a borrow)
596 ///
597 /// Useful for converting a `&Date<C>` into an equivalent `Date<D>` without cloning
598 /// the calendar.
599 pub fn as_borrowed(&self) -> Date<Ref<'_, A>> {
600 Date::from_raw(self.inner, Ref(&self.calendar))
601 }
602 }
603
604 impl<C, A, B> PartialEq<Date<B>> for Date<A>
605 where
606 C: Calendar,
607 A: AsCalendar<Calendar = C>,
608 B: AsCalendar<Calendar = C>,
609 {
610 fn eq(&self, other: &Date<B>) -> bool {
611 match self.calendar().check_date_compatibility(other.calendar()) {
612 Ok(_) => self.inner.eq(&other.inner),
613 Err(_) => false,
614 }
615 }
616 }
617
618 impl<A: AsCalendar> Eq for Date<A> {}
619
620 impl<C, A, B> PartialOrd<Date<B>> for Date<A>
621 where
622 C: Calendar,
623 A: AsCalendar<Calendar = C>,
624 B: AsCalendar<Calendar = C>,
625 {
626 fn partial_cmp(&self, other: &Date<B>) -> Option<core::cmp::Ordering> {
627 match self.calendar().check_date_compatibility(other.calendar()) {
628 Ok(_) => self.inner.partial_cmp(&other.inner),
629 Err(_) => None,
630 }
631 }
632 }
633
634 impl<C, A> Ord for Date<A>
635 where
636 C: Calendar,
637 C::DateInner: Ord,
638 A: AsCalendar<Calendar = C>,
639 {
640 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
641 match self.calendar().check_date_compatibility(other.calendar()) {
642 Ok(_) => self.inner().cmp(other.inner()),
643 Err(_) => {
644 // TODO: this is incorrect
645 self.inner().cmp(other.inner())
646 }
647 }
648 }
649 }
650
651 impl<A: AsCalendar> fmt::Debug for Date<A> {
652 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
653 let month = self.month().ordinal;
654 let day = self.day_of_month().0;
655 let calendar = self.calendar.as_calendar().debug_name();
656 match self.year() {
657 types::YearInfo::Era(EraYear { year, era, .. }) => {
658 write!(
659 f,
660 "Date({year}-{month}-{day}, {era} era, for calendar {calendar})"
661 )
662 }
663 types::YearInfo::Cyclic(CyclicYear { year, related_iso }) => {
664 write!(
665 f,
666 "Date({year}-{month}-{day}, ISO year {related_iso}, for calendar {calendar})"
667 )
668 }
669 }
670 }
671 }
672
673 impl<A: AsCalendar + Clone> Clone for Date<A> {
674 fn clone(&self) -> Self {
675 Self {
676 inner: self.inner,
677 calendar: self.calendar.clone(),
678 }
679 }
680 }
681
682 impl<A> Copy for Date<A> where A: AsCalendar + Copy {}
683
684 #[cfg(test)]
685 mod tests {
686 use super::*;
687 use crate::{
688 Gregorian,
689 cal::{Buddhist, Hebrew},
690 types::{Month, Weekday},
691 };
692
693 #[test]
694 fn test_ord() {
695 let dates_in_order = [
696 Date::try_new_iso(-10, 1, 1).unwrap(),
697 Date::try_new_iso(-10, 1, 2).unwrap(),
698 Date::try_new_iso(-10, 2, 1).unwrap(),
699 Date::try_new_iso(-1, 1, 1).unwrap(),
700 Date::try_new_iso(-1, 1, 2).unwrap(),
701 Date::try_new_iso(-1, 2, 1).unwrap(),
702 Date::try_new_iso(0, 1, 1).unwrap(),
703 Date::try_new_iso(0, 1, 2).unwrap(),
704 Date::try_new_iso(0, 2, 1).unwrap(),
705 Date::try_new_iso(1, 1, 1).unwrap(),
706 Date::try_new_iso(1, 1, 2).unwrap(),
707 Date::try_new_iso(1, 2, 1).unwrap(),
708 Date::try_new_iso(10, 1, 1).unwrap(),
709 Date::try_new_iso(10, 1, 2).unwrap(),
710 Date::try_new_iso(10, 2, 1).unwrap(),
711 ];
712 for (i, i_date) in dates_in_order.iter().enumerate() {
713 for (j, j_date) in dates_in_order.iter().enumerate() {
714 let result1 = i_date.cmp(j_date);
715 let result2 = j_date.cmp(i_date);
716 assert_eq!(result1.reverse(), result2);
717 assert_eq!(i.cmp(&j), i_date.cmp(j_date));
718 }
719 }
720 }
721
722 #[test]
723 fn test_weekday() {
724 // June 23, 2021 is a Wednesday
725 assert_eq!(
726 Date::try_new_iso(2021, 6, 23).unwrap().weekday(),
727 Weekday::Wednesday,
728 );
729 // Feb 2, 1983 was a Wednesday
730 assert_eq!(
731 Date::try_new_iso(1983, 2, 2).unwrap().weekday(),
732 Weekday::Wednesday,
733 );
734 // Jan 21, 2021 was a Tuesday
735 assert_eq!(
736 Date::try_new_iso(2020, 1, 21).unwrap().weekday(),
737 Weekday::Tuesday,
738 );
739 }
740
741 #[test]
742 fn test_to_calendar() {
743 let date = Date::try_new_gregorian(2025, 12, 9).unwrap();
744 // These conversions use the AbstractGregorian fast path
745 let date2 = date.to_calendar(Buddhist).to_calendar(Gregorian);
746 // These conversions go through RataDie
747 let date3 = date.to_calendar(Hebrew).to_calendar(Gregorian);
748 assert_eq!(date, date2);
749 assert_eq!(date2, date3);
750 }
751
752 #[test]
753 fn test_try_new() {
754 use crate::cal::Japanese;
755 use crate::types::YearInput;
756 let date = Date::try_new(2025.into(), Month::new(1), 1, Gregorian).unwrap();
757 assert_eq!(date, Date::try_new_gregorian(2025, 1, 1).unwrap());
758
759 let date2 = Date::try_new(
760 YearInput::EraYear("reiwa", 7),
761 Month::new(1),
762 1,
763 Japanese::new(),
764 )
765 .unwrap();
766 let date2_expected =
767 Date::try_new_japanese_with_calendar("reiwa", 7, 1, 1, Japanese::new()).unwrap();
768 assert_eq!(date2, date2_expected);
769 }
770 #[test]
771 fn date_add_options_default_is_constrain() {
772 use crate::cal::ChineseTraditional;
773 use crate::duration::DateDuration;
774 use crate::types::Month;
775
776 // 10 Adar I 5787
777 // 5787 is a leap year; 5788 is not
778 let mut date = Date::try_new(5787.into(), Month::leap(5), 10, Hebrew).unwrap();
779 date.try_add_with_options(DateDuration::for_years(1), DateAddOptions::default())
780 .unwrap();
781 assert_eq!(date.month().to_input(), Month::new(6));
782
783 // Leap Month 6, day 1, 2025.
784 // 2025 is a leap year; 2026 is not
785 let mut date = Date::try_new(
786 2025.into(),
787 Month::leap(6),
788 1,
789 ChineseTraditional::default(),
790 )
791 .unwrap();
792
793 date.try_add_with_options(DateDuration::for_years(1), DateAddOptions::default())
794 .unwrap();
795 assert_eq!(date.month().to_input(), Month::new(6));
796 }
797 }