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