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::iter::DateIter;
23use crate::num_fmt::{four_to_six_digits, str_from_raw_parts, two_digits_zero_padded};
24#[cfg(feature = "parsing")]
25use crate::parsing::{Parsable, Parsed};
26use crate::unit::*;
27use crate::util::{days_in_month_leap, range_validated, weeks_in_year};
28use crate::{Month, PlainDateTime, SignedDuration, Time, Weekday, error, hint};
29
30type Year = ri32<MIN_YEAR, MAX_YEAR>;
31
32pub(crate) const MIN_YEAR: i32 = if falsecfg!(feature = "large-dates") {
34 -999_999
35} else {
36 -9999
37};
38pub(crate) const MAX_YEAR: i32 = if falsecfg!(feature = "large-dates") {
40 999_999
41} else {
42 9999
43};
44
45#[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)]
51pub struct Date {
52 value: NonZero<i32>,
58}
59
60impl Date {
61 #[inline]
68 pub(crate) const fn as_i32(self) -> i32 {
69 self.value.get()
70 }
71
72 pub(crate) const UNIX_EPOCH: Self = unsafe { Self::__from_ordinal_date_unchecked(1970, 1) };
75
76 pub const MIN: Self = unsafe { Self::__from_ordinal_date_unchecked(MIN_YEAR, 1) };
81
82 pub const MAX: Self = unsafe {
87 Self::__from_ordinal_date_unchecked(MAX_YEAR, range_validated::days_in_year(MAX_YEAR))
88 };
89
90 #[inline]
98 #[track_caller]
99 pub(crate) const unsafe fn from_parts(year: i32, is_leap_year: bool, ordinal: u16) -> Self {
100 if true {
if !(year >= MIN_YEAR) {
::core::panicking::panic("assertion failed: year >= MIN_YEAR")
};
};debug_assert!(year >= MIN_YEAR);
101 if true {
if !(year <= MAX_YEAR) {
::core::panicking::panic("assertion failed: year <= MAX_YEAR")
};
};debug_assert!(year <= MAX_YEAR);
102 if true {
if !(ordinal != 0) {
::core::panicking::panic("assertion failed: ordinal != 0")
};
};debug_assert!(ordinal != 0);
103 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));
104 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);
105
106 Self {
107 value: unsafe {
109 NonZero::new_unchecked((year << 10) | ((is_leap_year as i32) << 9) | ordinal as i32)
110 },
111 }
112 }
113
114 #[doc(hidden)]
122 #[inline]
123 #[track_caller]
124 pub const unsafe fn __from_ordinal_date_unchecked(year: i32, ordinal: u16) -> Self {
125 unsafe { Self::from_parts(year, range_validated::is_leap_year(year), ordinal) }
128 }
129
130 #[inline]
143 pub const fn from_calendar_date(
144 year: i32,
145 month: Month,
146 day: u8,
147 ) -> Result<Self, error::ComponentRange> {
148 const DAYS_CUMULATIVE_COMMON_LEAP: [[u16; 12]; 2] = [
150 [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
151 [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335],
152 ];
153
154 match <Year>::new(year) {
Some(val) => val,
None => {
crate::hint::cold_path();
return Err(crate::error::ComponentRange::unconditional("year"));
}
};ensure_ranged!(Year: year);
155
156 let is_leap_year = range_validated::is_leap_year(year);
157 match day {
158 1..=28 => {}
159 29..=31 if day <= days_in_month_leap(month as u8, is_leap_year) => hint::cold_path(),
160 _ => {
161 hint::cold_path();
162 return Err(error::ComponentRange::conditional("day"));
163 }
164 }
165
166 Ok(unsafe {
168 Self::from_parts(
169 year,
170 is_leap_year,
171 DAYS_CUMULATIVE_COMMON_LEAP[is_leap_year as usize][month as usize - 1] + day as u16,
172 )
173 })
174 }
175
176 #[inline]
189 pub const fn from_ordinal_date(year: i32, ordinal: u16) -> Result<Self, error::ComponentRange> {
190 match <Year>::new(year) {
Some(val) => val,
None => {
crate::hint::cold_path();
return Err(crate::error::ComponentRange::unconditional("year"));
}
};ensure_ranged!(Year: year);
191
192 let is_leap_year = range_validated::is_leap_year(year);
193 match ordinal {
194 1..=365 => {}
195 366 if is_leap_year => hint::cold_path(),
196 _ => {
197 hint::cold_path();
198 return Err(error::ComponentRange::conditional("ordinal"));
199 }
200 }
201
202 Ok(unsafe { Self::from_parts(year, is_leap_year, ordinal) })
204 }
205
206 pub const fn from_iso_week_date(
220 year: i32,
221 week: u8,
222 weekday: Weekday,
223 ) -> Result<Self, error::ComponentRange> {
224 match <Year>::new(year) {
Some(val) => val,
None => {
crate::hint::cold_path();
return Err(crate::error::ComponentRange::unconditional("year"));
}
};ensure_ranged!(Year: year);
225 match week {
226 1..=52 => {}
227 53 if week <= weeks_in_year(year) => hint::cold_path(),
228 _ => {
229 hint::cold_path();
230 return Err(error::ComponentRange::conditional("week"));
231 }
232 }
233
234 let adj_year = year - 1;
235 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)
236 + 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);
237 let jan_4 = match (raw % 7) as i8 {
238 -6 | 1 => 8,
239 -5 | 2 => 9,
240 -4 | 3 => 10,
241 -3 | 4 => 4,
242 -2 | 5 => 5,
243 -1 | 6 => 6,
244 _ => 7,
245 };
246 let ordinal = week as i16 * 7 + weekday.number_from_monday() as i16 - jan_4;
247
248 if ordinal <= 0 {
249 return Ok(unsafe {
251 Self::__from_ordinal_date_unchecked(
252 year - 1,
253 ordinal
254 .cast_unsigned()
255 .wrapping_add(range_validated::days_in_year(year - 1)),
256 )
257 });
258 }
259
260 let is_leap_year = range_validated::is_leap_year(year);
261 let days_in_year = if is_leap_year { 366 } else { 365 };
262 let ordinal = ordinal.cast_unsigned();
263 Ok(if ordinal > days_in_year {
264 if hint::unlikely(year == MAX_YEAR) {
266 return Err(error::ComponentRange::conditional("weekday"));
267 }
268 unsafe { Self::__from_ordinal_date_unchecked(year + 1, ordinal - days_in_year) }
270 } else {
271 unsafe { Self::from_parts(year, is_leap_year, ordinal) }
273 })
274 }
275
276 #[doc(alias = "from_julian_date")]
287 #[inline]
288 pub const fn from_julian_day(julian_day: i32) -> Result<Self, error::ComponentRange> {
289 type JulianDay = ri32<{ Date::MIN.to_julian_day() }, { Date::MAX.to_julian_day() }>;
290 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);
291 Ok(unsafe { Self::from_julian_day_unchecked(julian_day) })
293 }
294
295 #[inline]
302 pub(crate) const unsafe fn from_julian_day_unchecked(julian_day: i32) -> Self {
303 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());
304 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());
305
306 const ERAS: u32 = 5_949;
307 const D_SHIFT: u32 = 146097 * ERAS - 1_721_060;
309 const Y_SHIFT: u32 = 400 * ERAS;
311
312 const CEN_MUL: u32 = ((4u64 << 47) / 146_097) as u32;
313 const JUL_MUL: u32 = ((4u64 << 40) / 1_461 + 1) as u32;
314 const CEN_CUT: u32 = ((365u64 << 32) / 36_525) as u32;
315
316 let day = julian_day.cast_unsigned().wrapping_add(D_SHIFT);
317 let c_n = (day as u64 * CEN_MUL as u64) >> 15;
318 let cen = (c_n >> 32) as u32;
319 let cpt = c_n as u32;
320 let ijy = cpt > CEN_CUT || cen.is_multiple_of(4);
321 let jul = day - cen / 4 + cen;
322 let y_n = (jul as u64 * JUL_MUL as u64) >> 8;
323 let yrs = (y_n >> 32) as u32;
324 let ypt = y_n as u32;
325
326 let year = yrs.wrapping_sub(Y_SHIFT).cast_signed();
327 let ordinal = ((ypt as u64 * 1_461) >> 34) as u32 + ijy as u32;
328 let leap = yrs.is_multiple_of(4) & ijy;
329
330 unsafe { Self::from_parts(year, leap, ordinal as u16) }
333 }
334
335 #[inline]
340 pub(crate) const fn is_in_leap_year(self) -> bool {
341 (self.value.get() >> 9) & 1 == 1
342 }
343
344 #[inline]
353 pub const fn year(self) -> i32 {
354 self.value.get() >> 10
355 }
356
357 #[inline]
366 pub const fn month(self) -> Month {
367 let ordinal = self.ordinal() as u32;
368 let jan_feb_len = 59 + self.is_in_leap_year() as u32;
369
370 let (month_adj, ordinal_adj) = if ordinal <= jan_feb_len {
371 (0, 0)
372 } else {
373 (2, jan_feb_len)
374 };
375
376 let ordinal = ordinal - ordinal_adj;
377 let month = ((ordinal * 268 + 8031) >> 13) + month_adj;
378
379 unsafe {
381 match Month::from_number(NonZero::new_unchecked(month as u8)) {
382 Ok(month) => month,
383 Err(_) => core::hint::unreachable_unchecked(),
384 }
385 }
386 }
387
388 #[inline]
398 pub const fn day(self) -> u8 {
399 let ordinal = self.ordinal() as u32;
400 let jan_feb_len = 59 + self.is_in_leap_year() as u32;
401
402 let ordinal_adj = if ordinal <= jan_feb_len {
403 0
404 } else {
405 jan_feb_len
406 };
407
408 let ordinal = ordinal - ordinal_adj;
409 let month = (ordinal * 268 + 8031) >> 13;
410 let days_in_preceding_months = (month * 3917 - 3866) >> 7;
411 (ordinal - days_in_preceding_months) as u8
412 }
413
414 #[inline]
424 pub const fn ordinal(self) -> u16 {
425 (self.value.get() & 0x1FF) as u16
426 }
427
428 #[inline]
430 pub(crate) const fn iso_year_week(self) -> (i32, u8) {
431 let (year, ordinal) = self.to_ordinal_date();
432
433 match ((ordinal + 10 - self.weekday().number_from_monday() as u16) / 7) as u8 {
434 0 => (year - 1, weeks_in_year(year - 1)),
435 53 if weeks_in_year(year) == 52 => (year + 1, 1),
436 week => (year, week),
437 }
438 }
439
440 #[inline]
453 pub const fn iso_week(self) -> u8 {
454 self.iso_year_week().1
455 }
456
457 #[inline]
469 pub const fn sunday_based_week(self) -> u8 {
470 ((self.ordinal().cast_signed() - self.weekday().number_days_from_sunday() as i16 + 6) / 7)
471 as u8
472 }
473
474 #[inline]
486 pub const fn monday_based_week(self) -> u8 {
487 ((self.ordinal().cast_signed() - self.weekday().number_days_from_monday() as i16 + 6) / 7)
488 as u8
489 }
490
491 #[inline]
502 pub const fn to_calendar_date(self) -> (i32, Month, u8) {
503 let (year, ordinal) = self.to_ordinal_date();
504 let ordinal = ordinal as u32;
505 let jan_feb_len = 59 + self.is_in_leap_year() as u32;
506
507 let (month_adj, ordinal_adj) = if ordinal <= jan_feb_len {
508 (0, 0)
509 } else {
510 (2, jan_feb_len)
511 };
512
513 let ordinal = ordinal - ordinal_adj;
514 let month = (ordinal * 268 + 8031) >> 13;
515 let days_in_preceding_months = (month * 3917 - 3866) >> 7;
516 let day = ordinal - days_in_preceding_months;
517 let month = month + month_adj;
518
519 (
520 year,
521 unsafe {
523 match Month::from_number(NonZero::new_unchecked(month as u8)) {
524 Ok(month) => month,
525 Err(_) => core::hint::unreachable_unchecked(),
526 }
527 },
528 day as u8,
529 )
530 }
531
532 #[inline]
539 pub const fn to_ordinal_date(self) -> (i32, u16) {
540 (self.year(), self.ordinal())
541 }
542
543 #[inline]
555 pub const fn to_iso_week_date(self) -> (i32, u8, Weekday) {
556 let (year, ordinal) = self.to_ordinal_date();
557 let weekday = self.weekday();
558
559 match ((ordinal + 10 - weekday.number_from_monday() as u16) / 7) as u8 {
560 0 => (year - 1, weeks_in_year(year - 1), weekday),
561 53 if weeks_in_year(year) == 52 => (year + 1, 1, weekday),
562 week => (year, week, weekday),
563 }
564 }
565
566 #[inline]
585 pub const fn weekday(self) -> Weekday {
586 match self.to_julian_day() % 7 {
587 -6 | 1 => Weekday::Tuesday,
588 -5 | 2 => Weekday::Wednesday,
589 -4 | 3 => Weekday::Thursday,
590 -3 | 4 => Weekday::Friday,
591 -2 | 5 => Weekday::Saturday,
592 -1 | 6 => Weekday::Sunday,
593 val => {
594 if true {
if !(val == 0) { ::core::panicking::panic("assertion failed: val == 0") };
};debug_assert!(val == 0);
595 Weekday::Monday
596 }
597 }
598 }
599
600 #[inline]
611 pub const fn next_day(self) -> Option<Self> {
612 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);
613 if hint::unlikely(is_last_day_of_year) {
614 if self.value.get() == Self::MAX.value.get() {
615 None
616 } else {
617 unsafe { Some(Self::__from_ordinal_date_unchecked(self.year() + 1, 1)) }
619 }
620 } else {
621 Some(unsafe { self.add_days_unchecked(1) })
623 }
624 }
625
626 #[inline]
637 pub const fn previous_day(self) -> Option<Self> {
638 if hint::likely(self.ordinal() != 1) {
639 Some(unsafe { self.add_days_unchecked(-1) })
641 } else if self.value.get() == Self::MIN.value.get() {
642 None
643 } else {
644 let year = self.year() - 1;
645 let is_leap_year = range_validated::is_leap_year(year);
646 let ordinal = if is_leap_year { 366 } else { 365 };
647 Some(unsafe { Self::from_parts(year, is_leap_year, ordinal) })
649 }
650 }
651
652 #[inline]
671 #[track_caller]
672 pub const fn next_occurrence(self, weekday: Weekday) -> Self {
673 self.checked_next_occurrence(weekday)
674 .expect("overflow calculating the next occurrence of a weekday")
675 }
676
677 #[inline]
696 #[track_caller]
697 pub const fn prev_occurrence(self, weekday: Weekday) -> Self {
698 self.checked_prev_occurrence(weekday)
699 .expect("overflow calculating the previous occurrence of a weekday")
700 }
701
702 #[inline]
721 #[track_caller]
722 pub const fn nth_next_occurrence(self, weekday: Weekday, n: u8) -> Self {
723 self.checked_nth_next_occurrence(weekday, n)
724 .expect("overflow calculating the next occurrence of a weekday")
725 }
726
727 #[inline]
746 #[track_caller]
747 pub const fn nth_prev_occurrence(self, weekday: Weekday, n: u8) -> Self {
748 self.checked_nth_prev_occurrence(weekday, n)
749 .expect("overflow calculating the previous occurrence of a weekday")
750 }
751
752 #[inline]
763 pub const fn iter_to(self, end: Self) -> DateIter {
764 DateIter::new(self, end)
765 }
766
767 #[inline]
777 pub const fn to_julian_day(self) -> i32 {
778 let (year, ordinal) = self.to_ordinal_date();
779
780 let adj_year = year + 999_999;
783 let century = adj_year / 100;
784
785 let days_before_year = (1461 * adj_year as i64 / 4) as i32 - century + century / 4;
786 days_before_year + ordinal as i32 - 363_521_075
787 }
788
789 #[inline]
796 pub(crate) const unsafe fn add_days_unchecked(mut self, days: i32) -> Self {
797 self.value = unsafe { NonZero::new_unchecked(self.value.get() + days) };
799 self
800 }
801
802 #[inline]
834 pub const fn checked_add(self, duration: SignedDuration) -> Option<Self> {
835 let whole_days = duration.whole_days();
836 if whole_days < i32::MIN as i64 || whole_days > i32::MAX as i64 {
837 return None;
838 }
839
840 let year = self.year();
841 let is_leap_year = self.is_in_leap_year();
842 let ordinal = self.ordinal() as i32;
843
844 let days_in_year = if is_leap_year { 366 } else { 365 };
845 let whole_days = whole_days as i32;
846
847 if let Some(new_ordinal) = ordinal.checked_add(whole_days)
849 && new_ordinal >= 1
850 && new_ordinal <= days_in_year
851 {
852 return Some(unsafe { Self::from_parts(year, is_leap_year, new_ordinal as u16) });
854 }
855
856 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));
857 if let Ok(date) = Self::from_julian_day(julian_day) {
858 Some(date)
859 } else {
860 None
861 }
862 }
863
864 #[inline]
894 pub const fn checked_add_std(self, duration: StdDuration) -> Option<Self> {
895 let whole_days = duration.as_secs() / Second::per_t::<u64>(Day);
896 if whole_days > i32::MAX as u64 {
897 return None;
898 }
899
900 let year = self.year();
901 let is_leap_year = self.is_in_leap_year();
902 let ordinal = self.ordinal() as i32;
903
904 let days_in_year = if is_leap_year { 366 } else { 365 };
905 let whole_days = whole_days as i32;
906
907 if let Some(new_ordinal) = ordinal.checked_add(whole_days)
909 && new_ordinal >= 1
910 && new_ordinal <= days_in_year
911 {
912 return Some(unsafe { Self::from_parts(year, is_leap_year, new_ordinal as u16) });
914 }
915
916 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));
917 if let Ok(date) = Self::from_julian_day(julian_day) {
918 Some(date)
919 } else {
920 None
921 }
922 }
923
924 #[inline]
956 pub const fn checked_sub(self, duration: SignedDuration) -> Option<Self> {
957 let whole_days = duration.whole_days();
958 if whole_days < i32::MIN as i64 || whole_days > i32::MAX as i64 {
959 return None;
960 }
961
962 let year = self.year();
963 let is_leap_year = self.is_in_leap_year();
964 let ordinal = self.ordinal() as i32;
965
966 let days_in_year = if is_leap_year { 366 } else { 365 };
967 let whole_days = whole_days as i32;
968
969 if let Some(new_ordinal) = ordinal.checked_sub(whole_days)
971 && new_ordinal >= 1
972 && new_ordinal <= days_in_year
973 {
974 return Some(unsafe { Self::from_parts(year, is_leap_year, new_ordinal as u16) });
976 }
977
978 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));
979 if let Ok(date) = Self::from_julian_day(julian_day) {
980 Some(date)
981 } else {
982 None
983 }
984 }
985
986 #[inline]
1016 pub const fn checked_sub_std(self, duration: StdDuration) -> Option<Self> {
1017 let whole_days = duration.as_secs() / Second::per_t::<u64>(Day);
1018 if whole_days > i32::MAX as u64 {
1019 return None;
1020 }
1021
1022 let year = self.year();
1023 let is_leap_year = self.is_in_leap_year();
1024 let ordinal = self.ordinal() as i32;
1025
1026 let days_in_year = if is_leap_year { 366 } else { 365 };
1027 let whole_days = whole_days as i32;
1028
1029 if let Some(new_ordinal) = ordinal.checked_sub(whole_days)
1031 && new_ordinal >= 1
1032 && new_ordinal <= days_in_year
1033 {
1034 return Some(unsafe { Self::from_parts(year, is_leap_year, new_ordinal as u16) });
1036 }
1037
1038 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));
1039 if let Ok(date) = Self::from_julian_day(julian_day) {
1040 Some(date)
1041 } else {
1042 None
1043 }
1044 }
1045
1046 #[inline]
1049 pub(crate) const fn checked_next_occurrence(self, weekday: Weekday) -> Option<Self> {
1050 let day_diff = match weekday as i8 - self.weekday() as i8 {
1051 1 | -6 => 1,
1052 2 | -5 => 2,
1053 3 | -4 => 3,
1054 4 | -3 => 4,
1055 5 | -2 => 5,
1056 6 | -1 => 6,
1057 val => {
1058 if true {
if !(val == 0) { ::core::panicking::panic("assertion failed: val == 0") };
};debug_assert!(val == 0);
1059 7
1060 }
1061 };
1062
1063 self.checked_add(SignedDuration::days(day_diff))
1064 }
1065
1066 #[inline]
1069 pub(crate) const fn checked_prev_occurrence(self, weekday: Weekday) -> Option<Self> {
1070 let day_diff = match weekday as i8 - self.weekday() as i8 {
1071 1 | -6 => 6,
1072 2 | -5 => 5,
1073 3 | -4 => 4,
1074 4 | -3 => 3,
1075 5 | -2 => 2,
1076 6 | -1 => 1,
1077 val => {
1078 if true {
if !(val == 0) { ::core::panicking::panic("assertion failed: val == 0") };
};debug_assert!(val == 0);
1079 7
1080 }
1081 };
1082
1083 self.checked_sub(SignedDuration::days(day_diff))
1084 }
1085
1086 #[inline]
1089 pub(crate) const fn checked_nth_next_occurrence(self, weekday: Weekday, n: u8) -> Option<Self> {
1090 if n == 0 {
1091 return None;
1092 }
1093
1094 match self.checked_next_occurrence(weekday) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(self.checked_next_occurrence(weekday))
1095 .checked_add(SignedDuration::weeks(n as i64 - 1))
1096 }
1097
1098 #[inline]
1101 pub(crate) const fn checked_nth_prev_occurrence(self, weekday: Weekday, n: u8) -> Option<Self> {
1102 if n == 0 {
1103 return None;
1104 }
1105
1106 match self.checked_prev_occurrence(weekday) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(self.checked_prev_occurrence(weekday))
1107 .checked_sub(SignedDuration::weeks(n as i64 - 1))
1108 }
1109
1110 #[inline]
1140 pub const fn saturating_add(self, duration: SignedDuration) -> Self {
1141 if let Some(datetime) = self.checked_add(duration) {
1142 datetime
1143 } else if duration.is_negative() {
1144 Self::MIN
1145 } else {
1146 if true {
if !duration.is_positive() {
::core::panicking::panic("assertion failed: duration.is_positive()")
};
};debug_assert!(duration.is_positive());
1147 Self::MAX
1148 }
1149 }
1150
1151 #[inline]
1181 pub const fn saturating_sub(self, duration: SignedDuration) -> Self {
1182 if let Some(datetime) = self.checked_sub(duration) {
1183 datetime
1184 } else if duration.is_negative() {
1185 Self::MAX
1186 } else {
1187 if true {
if !duration.is_positive() {
::core::panicking::panic("assertion failed: duration.is_positive()")
};
};debug_assert!(duration.is_positive());
1188 Self::MIN
1189 }
1190 }
1191
1192 #[inline]
1204 #[must_use = "This method does not mutate the original `Date`."]
1205 pub const fn replace_year(self, year: i32) -> Result<Self, error::ComponentRange> {
1206 match <Year>::new(year) {
Some(val) => val,
None => {
crate::hint::cold_path();
return Err(crate::error::ComponentRange::unconditional("year"));
}
};ensure_ranged!(Year: year);
1207
1208 let new_is_leap_year = range_validated::is_leap_year(year);
1209 let ordinal = self.ordinal();
1210
1211 if ordinal <= 59 {
1213 return Ok(unsafe { Self::from_parts(year, new_is_leap_year, ordinal) });
1215 }
1216
1217 match (self.is_in_leap_year(), new_is_leap_year) {
1218 (false, false) | (true, true) => {
1219 Ok(Self {
1220 value: unsafe {
1223 NonZero::new_unchecked((year << 10) | (self.value.get() & 0x3FF))
1224 },
1225 })
1226 }
1227 (true, false) if ordinal == 60 => Err(error::ComponentRange::conditional("day")),
1229 (false, true) => Ok(unsafe { Self::from_parts(year, true, ordinal + 1) }),
1233 (true, false) => Ok(unsafe { Self::from_parts(year, false, ordinal - 1) }),
1237 }
1238 }
1239
1240 #[inline]
1254 #[must_use = "This method does not mutate the original `Date`."]
1255 pub const fn replace_month(self, month: Month) -> Result<Self, error::ComponentRange> {
1256 const DAYS_CUMULATIVE_COMMON_LEAP: [[u16; 12]; 2] = [
1258 [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
1259 [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335],
1260 ];
1261
1262 let (year, ordinal) = self.to_ordinal_date();
1263 let mut ordinal = ordinal as u32;
1264 let is_leap_year = self.is_in_leap_year();
1265 let jan_feb_len = 59 + is_leap_year as u32;
1266
1267 if ordinal > jan_feb_len {
1268 ordinal -= jan_feb_len;
1269 }
1270 let current_month = (ordinal * 268 + 8031) >> 13;
1271 let days_in_preceding_months = (current_month * 3917 - 3866) >> 7;
1272 let day = (ordinal - days_in_preceding_months) as u8;
1273
1274 match day {
1275 1..=28 => {}
1276 29..=31 if day <= days_in_month_leap(month as u8, is_leap_year) => hint::cold_path(),
1277 _ => {
1278 hint::cold_path();
1279 return Err(error::ComponentRange::conditional("day"));
1280 }
1281 }
1282
1283 Ok(unsafe {
1285 Self::from_parts(
1286 year,
1287 is_leap_year,
1288 DAYS_CUMULATIVE_COMMON_LEAP[is_leap_year as usize][month as usize - 1] + day as u16,
1289 )
1290 })
1291 }
1292
1293 #[inline]
1302 #[must_use = "This method does not mutate the original `Date`."]
1303 pub const fn replace_day(self, day: u8) -> Result<Self, error::ComponentRange> {
1304 let is_leap_year = self.is_in_leap_year();
1305 match day {
1306 1..=28 => {}
1307 29..=31 if day <= days_in_month_leap(self.month() as u8, is_leap_year) => {
1308 hint::cold_path()
1309 }
1310 _ => {
1311 hint::cold_path();
1312 return Err(error::ComponentRange::conditional("day"));
1313 }
1314 }
1315
1316 Ok(unsafe {
1318 Self::from_parts(
1319 self.year(),
1320 is_leap_year,
1321 (self.ordinal().cast_signed() - self.day() as i16 + day as i16).cast_unsigned(),
1322 )
1323 })
1324 }
1325
1326 #[inline]
1335 #[must_use = "This method does not mutate the original `Date`."]
1336 pub const fn replace_ordinal(self, ordinal: u16) -> Result<Self, error::ComponentRange> {
1337 let is_leap_year = self.is_in_leap_year();
1338 match ordinal {
1339 1..=365 => {}
1340 366 if is_leap_year => hint::cold_path(),
1341 _ => {
1342 hint::cold_path();
1343 return Err(error::ComponentRange::conditional("ordinal"));
1344 }
1345 }
1346
1347 Ok(unsafe { Self::from_parts(self.year(), is_leap_year, ordinal) })
1349 }
1350}
1351
1352impl Date {
1354 #[inline]
1362 pub const fn midnight(self) -> PlainDateTime {
1363 PlainDateTime::new(self, Time::MIDNIGHT)
1364 }
1365
1366 #[inline]
1376 pub const fn with_time(self, time: Time) -> PlainDateTime {
1377 PlainDateTime::new(self, time)
1378 }
1379
1380 #[inline]
1388 pub const fn with_hms(
1389 self,
1390 hour: u8,
1391 minute: u8,
1392 second: u8,
1393 ) -> Result<PlainDateTime, error::ComponentRange> {
1394 Ok(PlainDateTime::new(
1395 self,
1396 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)),
1397 ))
1398 }
1399
1400 #[inline]
1408 pub const fn with_hms_milli(
1409 self,
1410 hour: u8,
1411 minute: u8,
1412 second: u8,
1413 millisecond: u16,
1414 ) -> Result<PlainDateTime, error::ComponentRange> {
1415 Ok(PlainDateTime::new(
1416 self,
1417 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)),
1418 ))
1419 }
1420
1421 #[inline]
1429 pub const fn with_hms_micro(
1430 self,
1431 hour: u8,
1432 minute: u8,
1433 second: u8,
1434 microsecond: u32,
1435 ) -> Result<PlainDateTime, error::ComponentRange> {
1436 Ok(PlainDateTime::new(
1437 self,
1438 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)),
1439 ))
1440 }
1441
1442 #[inline]
1450 pub const fn with_hms_nano(
1451 self,
1452 hour: u8,
1453 minute: u8,
1454 second: u8,
1455 nanosecond: u32,
1456 ) -> Result<PlainDateTime, error::ComponentRange> {
1457 Ok(PlainDateTime::new(
1458 self,
1459 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)),
1460 ))
1461 }
1462}
1463
1464#[cfg(feature = "formatting")]
1465impl Date {
1466 #[inline]
1468 pub fn format_into(
1469 self,
1470 output: &mut (impl io::Write + ?Sized),
1471 format: &(impl Formattable + ?Sized),
1472 ) -> Result<usize, error::Format> {
1473 format.format_into(output, &self, &mut Default::default(), PrivateMethod)
1474 }
1475
1476 #[inline]
1486 pub fn format(self, format: &(impl Formattable + ?Sized)) -> Result<String, error::Format> {
1487 format.format(&self, &mut Default::default(), PrivateMethod)
1488 }
1489}
1490
1491#[cfg(feature = "parsing")]
1492impl Date {
1493 #[inline]
1504 pub fn parse(
1505 input: &str,
1506 description: &(impl Parsable + ?Sized),
1507 ) -> Result<Self, error::Parse> {
1508 description.parse_date(input.as_bytes(), None, PrivateMethod)
1509 }
1510
1511 #[inline]
1527 pub fn parse_with_defaults(
1528 input: &[u8],
1529 description: &(impl Parsable + ?Sized),
1530 defaults: Parsed,
1531 ) -> Result<Self, error::Parse> {
1532 description.parse_date(input, Some(defaults), PrivateMethod)
1533 }
1534}
1535
1536impl SmartDisplay for Date {
1540 type Metadata = ();
1541
1542 #[inline]
1543 fn metadata(&self, _: FormatterOptions) -> Metadata<'_, Self> {
1544 use crate::ext::DigitCount as _;
1545
1546 let year_sign_width =
1547 if self.year() < 0 || (falsecfg!(feature = "large-dates") && self.year() >= 10_000) {
1548 1
1549 } else {
1550 0
1551 };
1552 let year_width = self.year().unsigned_abs().num_digits().clamp(4, 6);
1553 let formatted_width = year_sign_width + year_width + 6; Metadata::new(formatted_width as usize, self, ())
1556 }
1557
1558 #[inline]
1559 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1560 fmt::Display::fmt(self, f)
1561 }
1562}
1563
1564impl Date {
1565 pub(crate) const DISPLAY_BUFFER_SIZE: usize = 13;
1568
1569 #[inline]
1571 pub(crate) fn fmt_into_buffer(
1572 self,
1573 buf: &mut [MaybeUninit<u8>; Self::DISPLAY_BUFFER_SIZE],
1574 ) -> usize {
1575 let mut idx = 0;
1576 let (year, month, day) = self.to_calendar_date();
1577
1578 let neg = year.is_negative() as u8;
1581 let pos = (falsecfg!(feature = "large-dates") && year - 10_000 >= 0) as u8;
1582 let sign = b'+' + 2 * neg; buf[idx] = MaybeUninit::new(sign);
1586 idx += (neg | pos) as usize;
1587
1588 let [first_two, second_two, third_two] =
1590 four_to_six_digits(unsafe { ru32::new_unchecked(year.unsigned_abs()) });
1591 unsafe {
1597 first_two
1598 .as_ptr()
1599 .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), first_two.len());
1600 }
1601 idx += first_two.len();
1602 unsafe {
1604 second_two
1605 .as_ptr()
1606 .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), 2);
1607 }
1608 idx += 2;
1609 unsafe {
1611 third_two
1612 .as_ptr()
1613 .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), 2);
1614 }
1615 idx += 2;
1616
1617 buf[idx] = MaybeUninit::new(b'-');
1618 idx += 1;
1619
1620 unsafe {
1622 two_digits_zero_padded(ru8::new_unchecked(u8::from(month)))
1623 .as_ptr()
1624 .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), 2);
1625 }
1626 idx += 2;
1627
1628 buf[idx] = MaybeUninit::new(b'-');
1629 idx += 1;
1630
1631 unsafe {
1633 two_digits_zero_padded(ru8::new_unchecked(day))
1634 .as_ptr()
1635 .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), 2);
1636 }
1637 idx += 2;
1638
1639 idx
1640 }
1641}
1642
1643impl fmt::Display for Date {
1644 #[inline]
1645 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1646 let mut buf = [MaybeUninit::uninit(); 13];
1647 let len = self.fmt_into_buffer(&mut buf);
1648 let s = unsafe { str_from_raw_parts((&raw const buf).cast(), len) };
1650 f.pad(s)
1651 }
1652}
1653
1654impl fmt::Debug for Date {
1655 #[inline]
1656 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1657 fmt::Display::fmt(self, f)
1658 }
1659}
1660
1661impl Add<SignedDuration> for Date {
1662 type Output = Self;
1663
1664 #[inline]
1668 #[track_caller]
1669 fn add(self, duration: SignedDuration) -> Self::Output {
1670 self.checked_add(duration)
1671 .expect("overflow adding duration to date")
1672 }
1673}
1674
1675impl Add<StdDuration> for Date {
1676 type Output = Self;
1677
1678 #[inline]
1682 #[track_caller]
1683 fn add(self, duration: StdDuration) -> Self::Output {
1684 self.checked_add_std(duration)
1685 .expect("overflow adding duration to date")
1686 }
1687}
1688
1689impl AddAssign<SignedDuration> for Date {
1690 #[inline]
1694 #[track_caller]
1695 fn add_assign(&mut self, rhs: SignedDuration) {
1696 *self = *self + rhs;
1697 }
1698}
1699
1700impl AddAssign<StdDuration> for Date {
1701 #[inline]
1705 #[track_caller]
1706 fn add_assign(&mut self, rhs: StdDuration) {
1707 *self = *self + rhs;
1708 }
1709}
1710
1711impl Sub<SignedDuration> for Date {
1712 type Output = Self;
1713
1714 #[inline]
1718 #[track_caller]
1719 fn sub(self, duration: SignedDuration) -> Self::Output {
1720 self.checked_sub(duration)
1721 .expect("overflow subtracting duration from date")
1722 }
1723}
1724
1725impl Sub<StdDuration> for Date {
1726 type Output = Self;
1727
1728 #[inline]
1732 #[track_caller]
1733 fn sub(self, duration: StdDuration) -> Self::Output {
1734 self.checked_sub_std(duration)
1735 .expect("overflow subtracting duration from date")
1736 }
1737}
1738
1739impl SubAssign<SignedDuration> for Date {
1740 #[inline]
1744 #[track_caller]
1745 fn sub_assign(&mut self, rhs: SignedDuration) {
1746 *self = *self - rhs;
1747 }
1748}
1749
1750impl SubAssign<StdDuration> for Date {
1751 #[inline]
1755 #[track_caller]
1756 fn sub_assign(&mut self, rhs: StdDuration) {
1757 *self = *self - rhs;
1758 }
1759}
1760
1761impl Sub for Date {
1762 type Output = SignedDuration;
1763
1764 #[inline]
1765 fn sub(self, other: Self) -> Self::Output {
1766 SignedDuration::days((self.to_julian_day() - other.to_julian_day()).widen())
1767 }
1768}