1#[cfg(feature = "formatting")]
4use alloc::string::String;
5use core::fmt;
6use core::mem::MaybeUninit;
7use core::num::NonZero;
8use core::ops::{Add, AddAssign, Sub, SubAssign};
9use core::time::Duration as StdDuration;
10#[cfg(feature = "formatting")]
11use std::io;
12
13use deranged::{ri32, ru8, ru32};
14use num_conv::prelude::*;
15use powerfmt::smart_display::{FormatterOptions, Metadata, SmartDisplay};
16
17#[cfg(any(feature = "formatting", feature = "parsing"))]
18use crate::PrivateMethod;
19#[cfg(feature = "formatting")]
20use crate::formatting::Formattable;
21use crate::internal_macros::{const_try, const_try_opt, div_floor, ensure_ranged};
22use crate::num_fmt::{four_to_six_digits, str_from_raw_parts, two_digits_zero_padded};
23#[cfg(feature = "parsing")]
24use crate::parsing::{Parsable, Parsed};
25use crate::unit::*;
26use crate::util::{days_in_month_leap, range_validated, weeks_in_year};
27use crate::{Duration, Month, PrimitiveDateTime, Time, Weekday, error, hint};
28
29type Year = ri32<MIN_YEAR, MAX_YEAR>;
30
31pub(crate) const MIN_YEAR: i32 = if falsecfg!(feature = "large-dates") {
33 -999_999
34} else {
35 -9999
36};
37pub(crate) const MAX_YEAR: i32 = if falsecfg!(feature = "large-dates") {
39 999_999
40} else {
41 9999
42};
43
44#[derive(#[automatically_derived]
impl ::core::clone::Clone for Date {
#[inline]
fn clone(&self) -> Date {
let _: ::core::clone::AssertParamIsClone<NonZero<i32>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Date { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for Date {
#[inline]
fn eq(&self, other: &Date) -> bool { self.value == other.value }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Date {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<NonZero<i32>>;
}
}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.value, state)
}
}Hash, #[automatically_derived]
impl ::core::cmp::PartialOrd for Date {
#[inline]
fn partial_cmp(&self, other: &Date)
-> ::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: &Date) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.value, &other.value)
}
}Ord)]
50pub struct Date {
51 value: NonZero<i32>,
57}
58
59impl Date {
60 #[inline]
67 pub(crate) const fn as_i32(self) -> i32 {
68 self.value.get()
69 }
70
71 pub(crate) const UNIX_EPOCH: Self = unsafe { Self::__from_ordinal_date_unchecked(1970, 1) };
74
75 pub const MIN: Self = unsafe { Self::__from_ordinal_date_unchecked(MIN_YEAR, 1) };
80
81 pub const MAX: Self = unsafe {
86 Self::__from_ordinal_date_unchecked(MAX_YEAR, range_validated::days_in_year(MAX_YEAR))
87 };
88
89 #[inline]
97 #[track_caller]
98 const unsafe fn from_parts(year: i32, is_leap_year: bool, ordinal: u16) -> Self {
99 if true {
if !(year >= MIN_YEAR) {
::core::panicking::panic("assertion failed: year >= MIN_YEAR")
};
};debug_assert!(year >= MIN_YEAR);
100 if true {
if !(year <= MAX_YEAR) {
::core::panicking::panic("assertion failed: year <= MAX_YEAR")
};
};debug_assert!(year <= MAX_YEAR);
101 if true {
if !(ordinal != 0) {
::core::panicking::panic("assertion failed: ordinal != 0")
};
};debug_assert!(ordinal != 0);
102 if true {
if !(ordinal <= range_validated::days_in_year(year)) {
::core::panicking::panic("assertion failed: ordinal <= range_validated::days_in_year(year)")
};
};debug_assert!(ordinal <= range_validated::days_in_year(year));
103 if true {
if !(range_validated::is_leap_year(year) == is_leap_year) {
::core::panicking::panic("assertion failed: range_validated::is_leap_year(year) == is_leap_year")
};
};debug_assert!(range_validated::is_leap_year(year) == is_leap_year);
104
105 Self {
106 value: unsafe {
108 NonZero::new_unchecked((year << 10) | ((is_leap_year as i32) << 9) | ordinal as i32)
109 },
110 }
111 }
112
113 #[doc(hidden)]
121 #[inline]
122 #[track_caller]
123 pub const unsafe fn __from_ordinal_date_unchecked(year: i32, ordinal: u16) -> Self {
124 unsafe { Self::from_parts(year, range_validated::is_leap_year(year), ordinal) }
127 }
128
129 #[inline]
142 pub const fn from_calendar_date(
143 year: i32,
144 month: Month,
145 day: u8,
146 ) -> Result<Self, error::ComponentRange> {
147 const DAYS_CUMULATIVE_COMMON_LEAP: [[u16; 12]; 2] = [
149 [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
150 [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335],
151 ];
152
153 match <Year>::new(year) {
Some(val) => val,
None => {
crate::hint::cold_path();
return Err(crate::error::ComponentRange::unconditional("year"));
}
};ensure_ranged!(Year: year);
154
155 let is_leap_year = range_validated::is_leap_year(year);
156 match day {
157 1..=28 => {}
158 29..=31 if day <= days_in_month_leap(month as u8, is_leap_year) => hint::cold_path(),
159 _ => {
160 hint::cold_path();
161 return Err(error::ComponentRange::conditional("day"));
162 }
163 }
164
165 Ok(unsafe {
167 Self::from_parts(
168 year,
169 is_leap_year,
170 DAYS_CUMULATIVE_COMMON_LEAP[is_leap_year as usize][month as usize - 1] + day as u16,
171 )
172 })
173 }
174
175 #[inline]
188 pub const fn from_ordinal_date(year: i32, ordinal: u16) -> Result<Self, error::ComponentRange> {
189 match <Year>::new(year) {
Some(val) => val,
None => {
crate::hint::cold_path();
return Err(crate::error::ComponentRange::unconditional("year"));
}
};ensure_ranged!(Year: year);
190
191 let is_leap_year = range_validated::is_leap_year(year);
192 match ordinal {
193 1..=365 => {}
194 366 if is_leap_year => hint::cold_path(),
195 _ => {
196 hint::cold_path();
197 return Err(error::ComponentRange::conditional("ordinal"));
198 }
199 }
200
201 Ok(unsafe { Self::from_parts(year, is_leap_year, ordinal) })
203 }
204
205 pub const fn from_iso_week_date(
219 year: i32,
220 week: u8,
221 weekday: Weekday,
222 ) -> Result<Self, error::ComponentRange> {
223 match <Year>::new(year) {
Some(val) => val,
None => {
crate::hint::cold_path();
return Err(crate::error::ComponentRange::unconditional("year"));
}
};ensure_ranged!(Year: year);
224 match week {
225 1..=52 => {}
226 53 if week <= weeks_in_year(year) => hint::cold_path(),
227 _ => {
228 hint::cold_path();
229 return Err(error::ComponentRange::conditional("week"));
230 }
231 }
232
233 let adj_year = year - 1;
234 let raw = 365 * adj_year + match (adj_year, 4) {
(this, rhs) => {
let d = this / rhs;
let r = this % rhs;
let correction = (this ^ rhs) >> (size_of_val(&this) * 8 - 1);
if r != 0 { d + correction } else { d }
}
}div_floor!(adj_year, 4) - match (adj_year, 100) {
(this, rhs) => {
let d = this / rhs;
let r = this % rhs;
let correction = (this ^ rhs) >> (size_of_val(&this) * 8 - 1);
if r != 0 { d + correction } else { d }
}
}div_floor!(adj_year, 100)
235 + match (adj_year, 400) {
(this, rhs) => {
let d = this / rhs;
let r = this % rhs;
let correction = (this ^ rhs) >> (size_of_val(&this) * 8 - 1);
if r != 0 { d + correction } else { d }
}
}div_floor!(adj_year, 400);
236 let jan_4 = match (raw % 7) as i8 {
237 -6 | 1 => 8,
238 -5 | 2 => 9,
239 -4 | 3 => 10,
240 -3 | 4 => 4,
241 -2 | 5 => 5,
242 -1 | 6 => 6,
243 _ => 7,
244 };
245 let ordinal = week as i16 * 7 + weekday.number_from_monday() as i16 - jan_4;
246
247 if ordinal <= 0 {
248 return Ok(unsafe {
250 Self::__from_ordinal_date_unchecked(
251 year - 1,
252 ordinal
253 .cast_unsigned()
254 .wrapping_add(range_validated::days_in_year(year - 1)),
255 )
256 });
257 }
258
259 let is_leap_year = range_validated::is_leap_year(year);
260 let days_in_year = if is_leap_year { 366 } else { 365 };
261 let ordinal = ordinal.cast_unsigned();
262 Ok(if ordinal > days_in_year {
263 if hint::unlikely(year == MAX_YEAR) {
265 return Err(error::ComponentRange::conditional("weekday"));
266 }
267 unsafe { Self::__from_ordinal_date_unchecked(year + 1, ordinal - days_in_year) }
269 } else {
270 unsafe { Self::from_parts(year, is_leap_year, ordinal) }
272 })
273 }
274
275 #[doc(alias = "from_julian_date")]
286 #[inline]
287 pub const fn from_julian_day(julian_day: i32) -> Result<Self, error::ComponentRange> {
288 type JulianDay = ri32<{ Date::MIN.to_julian_day() }, { Date::MAX.to_julian_day() }>;
289 match <JulianDay>::new(julian_day) {
Some(val) => val,
None => {
crate::hint::cold_path();
return Err(crate::error::ComponentRange::unconditional("julian_day"));
}
};ensure_ranged!(JulianDay: julian_day);
290 Ok(unsafe { Self::from_julian_day_unchecked(julian_day) })
292 }
293
294 #[inline]
301 pub(crate) const unsafe fn from_julian_day_unchecked(julian_day: i32) -> Self {
302 if true {
if !(julian_day >= Self::MIN.to_julian_day()) {
::core::panicking::panic("assertion failed: julian_day >= Self::MIN.to_julian_day()")
};
};debug_assert!(julian_day >= Self::MIN.to_julian_day());
303 if true {
if !(julian_day <= Self::MAX.to_julian_day()) {
::core::panicking::panic("assertion failed: julian_day <= Self::MAX.to_julian_day()")
};
};debug_assert!(julian_day <= Self::MAX.to_julian_day());
304
305 const ERAS: u32 = 5_949;
306 const D_SHIFT: u32 = 146097 * ERAS - 1_721_060;
308 const Y_SHIFT: u32 = 400 * ERAS;
310
311 const CEN_MUL: u32 = ((4u64 << 47) / 146_097) as u32;
312 const JUL_MUL: u32 = ((4u64 << 40) / 1_461 + 1) as u32;
313 const CEN_CUT: u32 = ((365u64 << 32) / 36_525) as u32;
314
315 let day = julian_day.cast_unsigned().wrapping_add(D_SHIFT);
316 let c_n = (day as u64 * CEN_MUL as u64) >> 15;
317 let cen = (c_n >> 32) as u32;
318 let cpt = c_n as u32;
319 let ijy = cpt > CEN_CUT || cen.is_multiple_of(4);
320 let jul = day - cen / 4 + cen;
321 let y_n = (jul as u64 * JUL_MUL as u64) >> 8;
322 let yrs = (y_n >> 32) as u32;
323 let ypt = y_n as u32;
324
325 let year = yrs.wrapping_sub(Y_SHIFT).cast_signed();
326 let ordinal = ((ypt as u64 * 1_461) >> 34) as u32 + ijy as u32;
327 let leap = yrs.is_multiple_of(4) & ijy;
328
329 unsafe { Self::from_parts(year, leap, ordinal as u16) }
332 }
333
334 #[inline]
339 const fn is_in_leap_year(self) -> bool {
340 (self.value.get() >> 9) & 1 == 1
341 }
342
343 #[inline]
352 pub const fn year(self) -> i32 {
353 self.value.get() >> 10
354 }
355
356 #[inline]
365 pub const fn month(self) -> Month {
366 let ordinal = self.ordinal() as u32;
367 let jan_feb_len = 59 + self.is_in_leap_year() as u32;
368
369 let (month_adj, ordinal_adj) = if ordinal <= jan_feb_len {
370 (0, 0)
371 } else {
372 (2, jan_feb_len)
373 };
374
375 let ordinal = ordinal - ordinal_adj;
376 let month = ((ordinal * 268 + 8031) >> 13) + month_adj;
377
378 unsafe {
380 match Month::from_number(NonZero::new_unchecked(month as u8)) {
381 Ok(month) => month,
382 Err(_) => core::hint::unreachable_unchecked(),
383 }
384 }
385 }
386
387 #[inline]
397 pub const fn day(self) -> u8 {
398 let ordinal = self.ordinal() as u32;
399 let jan_feb_len = 59 + self.is_in_leap_year() as u32;
400
401 let ordinal_adj = if ordinal <= jan_feb_len {
402 0
403 } else {
404 jan_feb_len
405 };
406
407 let ordinal = ordinal - ordinal_adj;
408 let month = (ordinal * 268 + 8031) >> 13;
409 let days_in_preceding_months = (month * 3917 - 3866) >> 7;
410 (ordinal - days_in_preceding_months) as u8
411 }
412
413 #[inline]
423 pub const fn ordinal(self) -> u16 {
424 (self.value.get() & 0x1FF) as u16
425 }
426
427 #[inline]
429 pub(crate) const fn iso_year_week(self) -> (i32, u8) {
430 let (year, ordinal) = self.to_ordinal_date();
431
432 match ((ordinal + 10 - self.weekday().number_from_monday() as u16) / 7) as u8 {
433 0 => (year - 1, weeks_in_year(year - 1)),
434 53 if weeks_in_year(year) == 52 => (year + 1, 1),
435 week => (year, week),
436 }
437 }
438
439 #[inline]
452 pub const fn iso_week(self) -> u8 {
453 self.iso_year_week().1
454 }
455
456 #[inline]
468 pub const fn sunday_based_week(self) -> u8 {
469 ((self.ordinal().cast_signed() - self.weekday().number_days_from_sunday() as i16 + 6) / 7)
470 as u8
471 }
472
473 #[inline]
485 pub const fn monday_based_week(self) -> u8 {
486 ((self.ordinal().cast_signed() - self.weekday().number_days_from_monday() as i16 + 6) / 7)
487 as u8
488 }
489
490 #[inline]
501 pub const fn to_calendar_date(self) -> (i32, Month, u8) {
502 let (year, ordinal) = self.to_ordinal_date();
503 let ordinal = ordinal as u32;
504 let jan_feb_len = 59 + self.is_in_leap_year() as u32;
505
506 let (month_adj, ordinal_adj) = if ordinal <= jan_feb_len {
507 (0, 0)
508 } else {
509 (2, jan_feb_len)
510 };
511
512 let ordinal = ordinal - ordinal_adj;
513 let month = (ordinal * 268 + 8031) >> 13;
514 let days_in_preceding_months = (month * 3917 - 3866) >> 7;
515 let day = ordinal - days_in_preceding_months;
516 let month = month + month_adj;
517
518 (
519 year,
520 unsafe {
522 match Month::from_number(NonZero::new_unchecked(month as u8)) {
523 Ok(month) => month,
524 Err(_) => core::hint::unreachable_unchecked(),
525 }
526 },
527 day as u8,
528 )
529 }
530
531 #[inline]
538 pub const fn to_ordinal_date(self) -> (i32, u16) {
539 (self.year(), self.ordinal())
540 }
541
542 #[inline]
554 pub const fn to_iso_week_date(self) -> (i32, u8, Weekday) {
555 let (year, ordinal) = self.to_ordinal_date();
556 let weekday = self.weekday();
557
558 match ((ordinal + 10 - weekday.number_from_monday() as u16) / 7) as u8 {
559 0 => (year - 1, weeks_in_year(year - 1), weekday),
560 53 if weeks_in_year(year) == 52 => (year + 1, 1, weekday),
561 week => (year, week, weekday),
562 }
563 }
564
565 #[inline]
584 pub const fn weekday(self) -> Weekday {
585 match self.to_julian_day() % 7 {
586 -6 | 1 => Weekday::Tuesday,
587 -5 | 2 => Weekday::Wednesday,
588 -4 | 3 => Weekday::Thursday,
589 -3 | 4 => Weekday::Friday,
590 -2 | 5 => Weekday::Saturday,
591 -1 | 6 => Weekday::Sunday,
592 val => {
593 if true {
if !(val == 0) { ::core::panicking::panic("assertion failed: val == 0") };
};debug_assert!(val == 0);
594 Weekday::Monday
595 }
596 }
597 }
598
599 #[inline]
610 pub const fn next_day(self) -> Option<Self> {
611 let is_last_day_of_year = #[allow(non_exhaustive_omitted_patterns)] match self.value.get() & 0x3FF {
365 | 878 => true,
_ => false,
}matches!(self.value.get() & 0x3FF, 365 | 878);
612 if hint::unlikely(is_last_day_of_year) {
613 if self.value.get() == Self::MAX.value.get() {
614 None
615 } else {
616 unsafe { Some(Self::__from_ordinal_date_unchecked(self.year() + 1, 1)) }
618 }
619 } else {
620 Some(Self {
621 value: unsafe { NonZero::new_unchecked(self.value.get() + 1) },
623 })
624 }
625 }
626
627 #[inline]
638 pub const fn previous_day(self) -> Option<Self> {
639 if hint::likely(self.ordinal() != 1) {
640 Some(Self {
641 value: unsafe { NonZero::new_unchecked(self.value.get() - 1) },
643 })
644 } else if self.value.get() == Self::MIN.value.get() {
645 None
646 } else {
647 let year = self.year() - 1;
648 let is_leap_year = range_validated::is_leap_year(year);
649 let ordinal = if is_leap_year { 366 } else { 365 };
650 Some(unsafe { Self::from_parts(year, is_leap_year, ordinal) })
652 }
653 }
654
655 #[inline]
674 #[track_caller]
675 pub const fn next_occurrence(self, weekday: Weekday) -> Self {
676 self.checked_next_occurrence(weekday)
677 .expect("overflow calculating the next occurrence of a weekday")
678 }
679
680 #[inline]
699 #[track_caller]
700 pub const fn prev_occurrence(self, weekday: Weekday) -> Self {
701 self.checked_prev_occurrence(weekday)
702 .expect("overflow calculating the previous occurrence of a weekday")
703 }
704
705 #[inline]
724 #[track_caller]
725 pub const fn nth_next_occurrence(self, weekday: Weekday, n: u8) -> Self {
726 self.checked_nth_next_occurrence(weekday, n)
727 .expect("overflow calculating the next occurrence of a weekday")
728 }
729
730 #[inline]
749 #[track_caller]
750 pub const fn nth_prev_occurrence(self, weekday: Weekday, n: u8) -> Self {
751 self.checked_nth_prev_occurrence(weekday, n)
752 .expect("overflow calculating the previous occurrence of a weekday")
753 }
754
755 #[inline]
765 pub const fn to_julian_day(self) -> i32 {
766 let (year, ordinal) = self.to_ordinal_date();
767
768 let adj_year = year + 999_999;
771 let century = adj_year / 100;
772
773 let days_before_year = (1461 * adj_year as i64 / 4) as i32 - century + century / 4;
774 days_before_year + ordinal as i32 - 363_521_075
775 }
776
777 #[inline]
809 pub const fn checked_add(self, duration: Duration) -> Option<Self> {
810 let whole_days = duration.whole_days();
811 if whole_days < i32::MIN as i64 || whole_days > i32::MAX as i64 {
812 return None;
813 }
814
815 let year = self.year();
816 let is_leap_year = self.is_in_leap_year();
817 let ordinal = self.ordinal() as i32;
818
819 let days_in_year = if is_leap_year { 366 } else { 365 };
820 let whole_days = whole_days as i32;
821
822 if let Some(new_ordinal) = ordinal.checked_add(whole_days)
824 && new_ordinal >= 1
825 && new_ordinal <= days_in_year
826 {
827 return Some(unsafe { Self::from_parts(year, is_leap_year, new_ordinal as u16) });
829 }
830
831 let julian_day = match self.to_julian_day().checked_add(whole_days) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(self.to_julian_day().checked_add(whole_days));
832 if let Ok(date) = Self::from_julian_day(julian_day) {
833 Some(date)
834 } else {
835 None
836 }
837 }
838
839 #[inline]
869 pub const fn checked_add_std(self, duration: StdDuration) -> Option<Self> {
870 let whole_days = duration.as_secs() / Second::per_t::<u64>(Day);
871 if whole_days > i32::MAX as u64 {
872 return None;
873 }
874
875 let year = self.year();
876 let is_leap_year = self.is_in_leap_year();
877 let ordinal = self.ordinal() as i32;
878
879 let days_in_year = if is_leap_year { 366 } else { 365 };
880 let whole_days = whole_days as i32;
881
882 if let Some(new_ordinal) = ordinal.checked_add(whole_days)
884 && new_ordinal >= 1
885 && new_ordinal <= days_in_year
886 {
887 return Some(unsafe { Self::from_parts(year, is_leap_year, new_ordinal as u16) });
889 }
890
891 let julian_day = match self.to_julian_day().checked_add(whole_days) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(self.to_julian_day().checked_add(whole_days));
892 if let Ok(date) = Self::from_julian_day(julian_day) {
893 Some(date)
894 } else {
895 None
896 }
897 }
898
899 #[inline]
931 pub const fn checked_sub(self, duration: Duration) -> Option<Self> {
932 let whole_days = duration.whole_days();
933 if whole_days < i32::MIN as i64 || whole_days > i32::MAX as i64 {
934 return None;
935 }
936
937 let year = self.year();
938 let is_leap_year = self.is_in_leap_year();
939 let ordinal = self.ordinal() as i32;
940
941 let days_in_year = if is_leap_year { 366 } else { 365 };
942 let whole_days = whole_days as i32;
943
944 if let Some(new_ordinal) = ordinal.checked_sub(whole_days)
946 && new_ordinal >= 1
947 && new_ordinal <= days_in_year
948 {
949 return Some(unsafe { Self::from_parts(year, is_leap_year, new_ordinal as u16) });
951 }
952
953 let julian_day = match self.to_julian_day().checked_sub(whole_days) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(self.to_julian_day().checked_sub(whole_days));
954 if let Ok(date) = Self::from_julian_day(julian_day) {
955 Some(date)
956 } else {
957 None
958 }
959 }
960
961 #[inline]
991 pub const fn checked_sub_std(self, duration: StdDuration) -> Option<Self> {
992 let whole_days = duration.as_secs() / Second::per_t::<u64>(Day);
993 if whole_days > i32::MAX as u64 {
994 return None;
995 }
996
997 let year = self.year();
998 let is_leap_year = self.is_in_leap_year();
999 let ordinal = self.ordinal() as i32;
1000
1001 let days_in_year = if is_leap_year { 366 } else { 365 };
1002 let whole_days = whole_days as i32;
1003
1004 if let Some(new_ordinal) = ordinal.checked_sub(whole_days)
1006 && new_ordinal >= 1
1007 && new_ordinal <= days_in_year
1008 {
1009 return Some(unsafe { Self::from_parts(year, is_leap_year, new_ordinal as u16) });
1011 }
1012
1013 let julian_day = match self.to_julian_day().checked_sub(whole_days) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(self.to_julian_day().checked_sub(whole_days));
1014 if let Ok(date) = Self::from_julian_day(julian_day) {
1015 Some(date)
1016 } else {
1017 None
1018 }
1019 }
1020
1021 #[inline]
1024 pub(crate) const fn checked_next_occurrence(self, weekday: Weekday) -> Option<Self> {
1025 let day_diff = match weekday as i8 - self.weekday() as i8 {
1026 1 | -6 => 1,
1027 2 | -5 => 2,
1028 3 | -4 => 3,
1029 4 | -3 => 4,
1030 5 | -2 => 5,
1031 6 | -1 => 6,
1032 val => {
1033 if true {
if !(val == 0) { ::core::panicking::panic("assertion failed: val == 0") };
};debug_assert!(val == 0);
1034 7
1035 }
1036 };
1037
1038 self.checked_add(Duration::days(day_diff))
1039 }
1040
1041 #[inline]
1044 pub(crate) const fn checked_prev_occurrence(self, weekday: Weekday) -> Option<Self> {
1045 let day_diff = match weekday as i8 - self.weekday() as i8 {
1046 1 | -6 => 6,
1047 2 | -5 => 5,
1048 3 | -4 => 4,
1049 4 | -3 => 3,
1050 5 | -2 => 2,
1051 6 | -1 => 1,
1052 val => {
1053 if true {
if !(val == 0) { ::core::panicking::panic("assertion failed: val == 0") };
};debug_assert!(val == 0);
1054 7
1055 }
1056 };
1057
1058 self.checked_sub(Duration::days(day_diff))
1059 }
1060
1061 #[inline]
1064 pub(crate) const fn checked_nth_next_occurrence(self, weekday: Weekday, n: u8) -> Option<Self> {
1065 if n == 0 {
1066 return None;
1067 }
1068
1069 match self.checked_next_occurrence(weekday) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(self.checked_next_occurrence(weekday))
1070 .checked_add(Duration::weeks(n as i64 - 1))
1071 }
1072
1073 #[inline]
1076 pub(crate) const fn checked_nth_prev_occurrence(self, weekday: Weekday, n: u8) -> Option<Self> {
1077 if n == 0 {
1078 return None;
1079 }
1080
1081 match self.checked_prev_occurrence(weekday) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(self.checked_prev_occurrence(weekday))
1082 .checked_sub(Duration::weeks(n as i64 - 1))
1083 }
1084
1085 #[inline]
1115 pub const fn saturating_add(self, duration: Duration) -> Self {
1116 if let Some(datetime) = self.checked_add(duration) {
1117 datetime
1118 } else if duration.is_negative() {
1119 Self::MIN
1120 } else {
1121 if true {
if !duration.is_positive() {
::core::panicking::panic("assertion failed: duration.is_positive()")
};
};debug_assert!(duration.is_positive());
1122 Self::MAX
1123 }
1124 }
1125
1126 #[inline]
1156 pub const fn saturating_sub(self, duration: Duration) -> Self {
1157 if let Some(datetime) = self.checked_sub(duration) {
1158 datetime
1159 } else if duration.is_negative() {
1160 Self::MAX
1161 } else {
1162 if true {
if !duration.is_positive() {
::core::panicking::panic("assertion failed: duration.is_positive()")
};
};debug_assert!(duration.is_positive());
1163 Self::MIN
1164 }
1165 }
1166
1167 #[inline]
1179 #[must_use = "This method does not mutate the original `Date`."]
1180 pub const fn replace_year(self, year: i32) -> Result<Self, error::ComponentRange> {
1181 match <Year>::new(year) {
Some(val) => val,
None => {
crate::hint::cold_path();
return Err(crate::error::ComponentRange::unconditional("year"));
}
};ensure_ranged!(Year: year);
1182
1183 let new_is_leap_year = range_validated::is_leap_year(year);
1184 let ordinal = self.ordinal();
1185
1186 if ordinal <= 59 {
1188 return Ok(unsafe { Self::from_parts(year, new_is_leap_year, ordinal) });
1190 }
1191
1192 match (self.is_in_leap_year(), new_is_leap_year) {
1193 (false, false) | (true, true) => {
1194 Ok(Self {
1195 value: unsafe {
1198 NonZero::new_unchecked((year << 10) | (self.value.get() & 0x3FF))
1199 },
1200 })
1201 }
1202 (true, false) if ordinal == 60 => Err(error::ComponentRange::conditional("day")),
1204 (false, true) => Ok(unsafe { Self::from_parts(year, true, ordinal + 1) }),
1208 (true, false) => Ok(unsafe { Self::from_parts(year, false, ordinal - 1) }),
1212 }
1213 }
1214
1215 #[inline]
1229 #[must_use = "This method does not mutate the original `Date`."]
1230 pub const fn replace_month(self, month: Month) -> Result<Self, error::ComponentRange> {
1231 const DAYS_CUMULATIVE_COMMON_LEAP: [[u16; 12]; 2] = [
1233 [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
1234 [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335],
1235 ];
1236
1237 let (year, ordinal) = self.to_ordinal_date();
1238 let mut ordinal = ordinal as u32;
1239 let is_leap_year = self.is_in_leap_year();
1240 let jan_feb_len = 59 + is_leap_year as u32;
1241
1242 if ordinal > jan_feb_len {
1243 ordinal -= jan_feb_len;
1244 }
1245 let current_month = (ordinal * 268 + 8031) >> 13;
1246 let days_in_preceding_months = (current_month * 3917 - 3866) >> 7;
1247 let day = (ordinal - days_in_preceding_months) as u8;
1248
1249 match day {
1250 1..=28 => {}
1251 29..=31 if day <= days_in_month_leap(month as u8, is_leap_year) => hint::cold_path(),
1252 _ => {
1253 hint::cold_path();
1254 return Err(error::ComponentRange::conditional("day"));
1255 }
1256 }
1257
1258 Ok(unsafe {
1260 Self::from_parts(
1261 year,
1262 is_leap_year,
1263 DAYS_CUMULATIVE_COMMON_LEAP[is_leap_year as usize][month as usize - 1] + day as u16,
1264 )
1265 })
1266 }
1267
1268 #[inline]
1277 #[must_use = "This method does not mutate the original `Date`."]
1278 pub const fn replace_day(self, day: u8) -> Result<Self, error::ComponentRange> {
1279 let is_leap_year = self.is_in_leap_year();
1280 match day {
1281 1..=28 => {}
1282 29..=31 if day <= days_in_month_leap(self.month() as u8, is_leap_year) => {
1283 hint::cold_path()
1284 }
1285 _ => {
1286 hint::cold_path();
1287 return Err(error::ComponentRange::conditional("day"));
1288 }
1289 }
1290
1291 Ok(unsafe {
1293 Self::from_parts(
1294 self.year(),
1295 is_leap_year,
1296 (self.ordinal().cast_signed() - self.day() as i16 + day as i16).cast_unsigned(),
1297 )
1298 })
1299 }
1300
1301 #[inline]
1310 #[must_use = "This method does not mutate the original `Date`."]
1311 pub const fn replace_ordinal(self, ordinal: u16) -> Result<Self, error::ComponentRange> {
1312 let is_leap_year = self.is_in_leap_year();
1313 match ordinal {
1314 1..=365 => {}
1315 366 if is_leap_year => hint::cold_path(),
1316 _ => {
1317 hint::cold_path();
1318 return Err(error::ComponentRange::conditional("ordinal"));
1319 }
1320 }
1321
1322 Ok(unsafe { Self::from_parts(self.year(), is_leap_year, ordinal) })
1324 }
1325}
1326
1327impl Date {
1329 #[inline]
1337 pub const fn midnight(self) -> PrimitiveDateTime {
1338 PrimitiveDateTime::new(self, Time::MIDNIGHT)
1339 }
1340
1341 #[inline]
1351 pub const fn with_time(self, time: Time) -> PrimitiveDateTime {
1352 PrimitiveDateTime::new(self, time)
1353 }
1354
1355 #[inline]
1363 pub const fn with_hms(
1364 self,
1365 hour: u8,
1366 minute: u8,
1367 second: u8,
1368 ) -> Result<PrimitiveDateTime, error::ComponentRange> {
1369 Ok(PrimitiveDateTime::new(
1370 self,
1371 match Time::from_hms(hour, minute, second) {
Ok(value) => value,
Err(error) => { crate::hint::cold_path(); return Err(error); }
}const_try!(Time::from_hms(hour, minute, second)),
1372 ))
1373 }
1374
1375 #[inline]
1383 pub const fn with_hms_milli(
1384 self,
1385 hour: u8,
1386 minute: u8,
1387 second: u8,
1388 millisecond: u16,
1389 ) -> Result<PrimitiveDateTime, error::ComponentRange> {
1390 Ok(PrimitiveDateTime::new(
1391 self,
1392 match Time::from_hms_milli(hour, minute, second, millisecond) {
Ok(value) => value,
Err(error) => { crate::hint::cold_path(); return Err(error); }
}const_try!(Time::from_hms_milli(hour, minute, second, millisecond)),
1393 ))
1394 }
1395
1396 #[inline]
1404 pub const fn with_hms_micro(
1405 self,
1406 hour: u8,
1407 minute: u8,
1408 second: u8,
1409 microsecond: u32,
1410 ) -> Result<PrimitiveDateTime, error::ComponentRange> {
1411 Ok(PrimitiveDateTime::new(
1412 self,
1413 match Time::from_hms_micro(hour, minute, second, microsecond) {
Ok(value) => value,
Err(error) => { crate::hint::cold_path(); return Err(error); }
}const_try!(Time::from_hms_micro(hour, minute, second, microsecond)),
1414 ))
1415 }
1416
1417 #[inline]
1425 pub const fn with_hms_nano(
1426 self,
1427 hour: u8,
1428 minute: u8,
1429 second: u8,
1430 nanosecond: u32,
1431 ) -> Result<PrimitiveDateTime, error::ComponentRange> {
1432 Ok(PrimitiveDateTime::new(
1433 self,
1434 match Time::from_hms_nano(hour, minute, second, nanosecond) {
Ok(value) => value,
Err(error) => { crate::hint::cold_path(); return Err(error); }
}const_try!(Time::from_hms_nano(hour, minute, second, nanosecond)),
1435 ))
1436 }
1437}
1438
1439#[cfg(feature = "formatting")]
1440impl Date {
1441 #[inline]
1443 pub fn format_into(
1444 self,
1445 output: &mut (impl io::Write + ?Sized),
1446 format: &(impl Formattable + ?Sized),
1447 ) -> Result<usize, error::Format> {
1448 format.format_into(output, &self, &mut Default::default(), PrivateMethod)
1449 }
1450
1451 #[inline]
1461 pub fn format(self, format: &(impl Formattable + ?Sized)) -> Result<String, error::Format> {
1462 format.format(&self, &mut Default::default(), PrivateMethod)
1463 }
1464}
1465
1466#[cfg(feature = "parsing")]
1467impl Date {
1468 #[inline]
1479 pub fn parse(
1480 input: &str,
1481 description: &(impl Parsable + ?Sized),
1482 ) -> Result<Self, error::Parse> {
1483 description.parse_date(input.as_bytes(), None, PrivateMethod)
1484 }
1485
1486 #[inline]
1502 pub fn parse_with_defaults(
1503 input: &[u8],
1504 description: &(impl Parsable + ?Sized),
1505 defaults: Parsed,
1506 ) -> Result<Self, error::Parse> {
1507 description.parse_date(input, Some(defaults), PrivateMethod)
1508 }
1509}
1510
1511mod private {
1512 #[non_exhaustive]
1514 #[derive(#[automatically_derived]
impl ::core::fmt::Debug for DateMetadata {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "DateMetadata")
}
}Debug)]
1515 pub struct DateMetadata;
1516}
1517use private::DateMetadata;
1518
1519impl SmartDisplay for Date {
1523 type Metadata = DateMetadata;
1524
1525 #[inline]
1526 fn metadata(&self, _: FormatterOptions) -> Metadata<'_, Self> {
1527 use crate::ext::DigitCount as _;
1528
1529 let year_sign_width =
1530 if self.year() < 0 || (falsecfg!(feature = "large-dates") && self.year() >= 10_000) {
1531 1
1532 } else {
1533 0
1534 };
1535 let year_width = self.year().unsigned_abs().num_digits().clamp(4, 6);
1536 let formatted_width = year_sign_width + year_width + 6; Metadata::new(formatted_width as usize, self, DateMetadata)
1539 }
1540
1541 #[inline]
1542 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1543 fmt::Display::fmt(self, f)
1544 }
1545}
1546
1547impl Date {
1548 pub(crate) const DISPLAY_BUFFER_SIZE: usize = 13;
1551
1552 #[inline]
1554 pub(crate) fn fmt_into_buffer(
1555 self,
1556 buf: &mut [MaybeUninit<u8>; Self::DISPLAY_BUFFER_SIZE],
1557 ) -> usize {
1558 let mut idx = 0;
1559 let (year, month, day) = self.to_calendar_date();
1560
1561 let neg = year.is_negative() as u8;
1564 let pos = (falsecfg!(feature = "large-dates") && year - 10_000 >= 0) as u8;
1565 let sign = b'+' + 2 * neg; buf[idx] = MaybeUninit::new(sign);
1569 idx += (neg | pos) as usize;
1570
1571 let [first_two, second_two, third_two] =
1573 four_to_six_digits(unsafe { ru32::new_unchecked(year.unsigned_abs()) });
1574 unsafe {
1580 first_two
1581 .as_ptr()
1582 .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), first_two.len());
1583 }
1584 idx += first_two.len();
1585 unsafe {
1587 second_two
1588 .as_ptr()
1589 .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), 2);
1590 }
1591 idx += 2;
1592 unsafe {
1594 third_two
1595 .as_ptr()
1596 .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), 2);
1597 }
1598 idx += 2;
1599
1600 buf[idx] = MaybeUninit::new(b'-');
1601 idx += 1;
1602
1603 unsafe {
1605 two_digits_zero_padded(ru8::new_unchecked(u8::from(month)))
1606 .as_ptr()
1607 .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), 2);
1608 }
1609 idx += 2;
1610
1611 buf[idx] = MaybeUninit::new(b'-');
1612 idx += 1;
1613
1614 unsafe {
1616 two_digits_zero_padded(ru8::new_unchecked(day))
1617 .as_ptr()
1618 .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), 2);
1619 }
1620 idx += 2;
1621
1622 idx
1623 }
1624}
1625
1626impl fmt::Display for Date {
1627 #[inline]
1628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1629 let mut buf = [MaybeUninit::uninit(); 13];
1630 let len = self.fmt_into_buffer(&mut buf);
1631 let s = unsafe { str_from_raw_parts((&raw const buf).cast(), len) };
1633 f.pad(s)
1634 }
1635}
1636
1637impl fmt::Debug for Date {
1638 #[inline]
1639 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1640 fmt::Display::fmt(self, f)
1641 }
1642}
1643
1644impl Add<Duration> for Date {
1645 type Output = Self;
1646
1647 #[inline]
1651 #[track_caller]
1652 fn add(self, duration: Duration) -> Self::Output {
1653 self.checked_add(duration)
1654 .expect("overflow adding duration to date")
1655 }
1656}
1657
1658impl Add<StdDuration> for Date {
1659 type Output = Self;
1660
1661 #[inline]
1665 #[track_caller]
1666 fn add(self, duration: StdDuration) -> Self::Output {
1667 self.checked_add_std(duration)
1668 .expect("overflow adding duration to date")
1669 }
1670}
1671
1672impl AddAssign<Duration> for Date {
1673 #[inline]
1677 #[track_caller]
1678 fn add_assign(&mut self, rhs: Duration) {
1679 *self = *self + rhs;
1680 }
1681}
1682
1683impl AddAssign<StdDuration> for Date {
1684 #[inline]
1688 #[track_caller]
1689 fn add_assign(&mut self, rhs: StdDuration) {
1690 *self = *self + rhs;
1691 }
1692}
1693
1694impl Sub<Duration> for Date {
1695 type Output = Self;
1696
1697 #[inline]
1701 #[track_caller]
1702 fn sub(self, duration: Duration) -> Self::Output {
1703 self.checked_sub(duration)
1704 .expect("overflow subtracting duration from date")
1705 }
1706}
1707
1708impl Sub<StdDuration> for Date {
1709 type Output = Self;
1710
1711 #[inline]
1715 #[track_caller]
1716 fn sub(self, duration: StdDuration) -> Self::Output {
1717 self.checked_sub_std(duration)
1718 .expect("overflow subtracting duration from date")
1719 }
1720}
1721
1722impl SubAssign<Duration> for Date {
1723 #[inline]
1727 #[track_caller]
1728 fn sub_assign(&mut self, rhs: Duration) {
1729 *self = *self - rhs;
1730 }
1731}
1732
1733impl SubAssign<StdDuration> for Date {
1734 #[inline]
1738 #[track_caller]
1739 fn sub_assign(&mut self, rhs: StdDuration) {
1740 *self = *self - rhs;
1741 }
1742}
1743
1744impl Sub for Date {
1745 type Output = Duration;
1746
1747 #[inline]
1748 fn sub(self, other: Self) -> Self::Output {
1749 Duration::days((self.to_julian_day() - other.to_julian_day()).widen())
1750 }
1751}