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