1use std::fmt::{self, Debug, Display};
4
5#[derive(Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
7#[repr(transparent)]
8pub struct Date(i32);
9
10impl Date {
11 pub const EPOCH: Self = Self(0);
13 pub const MIN: Self = Self(-719_528);
15 pub const MAX: Self = Self(2_932_896);
17
18 const DAYS_PER_CYCLE: i32 = 146_097;
22 const MARCH_EPOCH_OFFSET: i32 = 719_468;
23
24 #[must_use]
28 pub fn try_new(y: i32, m: u8, d: u8) -> Option<Self> {
29 if !(0..=9_999).contains(&y) {
30 return None;
31 }
32 let month_days = match m {
33 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
34 4 | 6 | 9 | 11 => 30,
35 2 if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) => 29,
36 2 => 28,
37 _ => return None,
38 };
39 if d == 0 || d > month_days {
40 return None;
41 }
42
43 let year = y - i32::from(m <= 2);
44 let cycle = year.div_euclid(400);
45 let cycle_year = year.rem_euclid(400);
46 let march_month = i32::from(m) + if m > 2 { -3 } else { 9 };
47 let cycle_day = 365 * cycle_year + cycle_year / 4 - cycle_year / 100
48 + (153 * march_month + 2) / 5
49 + i32::from(d)
50 - 1;
51 Self::try_from_days_since_epoch(
52 cycle * Self::DAYS_PER_CYCLE + cycle_day - Self::MARCH_EPOCH_OFFSET,
53 )
54 }
55
56 #[must_use]
58 pub const fn try_from_days_since_epoch(days: i32) -> Option<Self> {
59 if days < Self::MIN.0 || days > Self::MAX.0 {
60 None
61 } else {
62 Some(Self(days))
63 }
64 }
65
66 #[must_use]
68 pub const fn as_days_since_epoch(self) -> i32 {
69 self.0
70 }
71
72 #[must_use]
74 pub fn try_from_i64(days: i64) -> Option<Self> {
75 i32::try_from(days)
76 .ok()
77 .and_then(Self::try_from_days_since_epoch)
78 }
79
80 #[must_use]
82 pub fn try_from_u64(days: u64) -> Option<Self> {
83 i32::try_from(days)
84 .ok()
85 .and_then(Self::try_from_days_since_epoch)
86 }
87
88 #[must_use]
90 pub fn checked_add_days(self, days: i64) -> Option<Self> {
91 i64::from(self.0)
92 .checked_add(days)
93 .and_then(Self::try_from_i64)
94 }
95
96 #[must_use]
98 pub fn checked_sub_days(self, days: i64) -> Option<Self> {
99 i64::from(self.0)
100 .checked_sub(days)
101 .and_then(Self::try_from_i64)
102 }
103
104 #[must_use]
106 pub fn days_since(self, earlier: Self) -> i64 {
107 i64::from(self.0) - i64::from(earlier.0)
108 }
109
110 #[must_use]
112 pub fn year(self) -> i32 {
113 self.calendar_parts().0
114 }
115
116 #[must_use]
118 pub fn month(self) -> u8 {
119 self.calendar_parts().1
120 }
121
122 #[must_use]
124 pub fn day(self) -> u8 {
125 self.calendar_parts().2
126 }
127
128 #[must_use]
130 pub fn parse(s: &str) -> Option<Self> {
131 let bytes = s.as_bytes();
132 if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
133 return None;
134 }
135
136 let year = parse_ascii_i32(&bytes[0..4])?;
138 let month = parse_ascii_u8(&bytes[5..7])?;
139 let day = parse_ascii_u8(&bytes[8..10])?;
140
141 Self::try_new(year, month, day)
142 }
143
144 fn calendar_parts(self) -> (i32, u8, u8) {
147 let march_day = self.0 + Self::MARCH_EPOCH_OFFSET;
148 let cycle = march_day.div_euclid(Self::DAYS_PER_CYCLE);
149 let cycle_day = march_day.rem_euclid(Self::DAYS_PER_CYCLE);
150 let cycle_year =
151 (cycle_day - cycle_day / 1_460 + cycle_day / 36_524 - cycle_day / 146_096) / 365;
152 let year = cycle * 400 + cycle_year;
153 let march_ordinal = cycle_day - (365 * cycle_year + cycle_year / 4 - cycle_year / 100);
154 let march_month = (5 * march_ordinal + 2) / 153;
155 let day = march_ordinal - (153 * march_month + 2) / 5 + 1;
156 let month = march_month + if march_month < 10 { 3 } else { -9 };
157
158 (year + i32::from(month <= 2), month as u8, day as u8)
159 }
160}
161
162impl Debug for Date {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 write!(f, "Date({self})")
165 }
166}
167
168impl Display for Date {
169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170 let (year, month, day) = self.calendar_parts();
171 write!(f, "{year:04}-{month:02}-{day:02}")
172 }
173}
174
175fn parse_ascii_i32(bytes: &[u8]) -> Option<i32> {
176 bytes.iter().try_fold(0_i32, |value, byte| {
177 byte.checked_sub(b'0')
178 .filter(|digit| *digit <= 9)
179 .and_then(|digit| value.checked_mul(10)?.checked_add(i32::from(digit)))
180 })
181}
182
183fn parse_ascii_u8(bytes: &[u8]) -> Option<u8> {
184 bytes.iter().try_fold(0_u8, |value, byte| {
185 byte.checked_sub(b'0')
186 .filter(|digit| *digit <= 9)
187 .and_then(|digit| value.checked_mul(10)?.checked_add(digit))
188 })
189}