1use crate::{Decimal, NumericValue, TypeParseError};
7
8use serde::{Deserialize, Deserializer, Serialize};
9use std::fmt::{self, Debug, Display};
10
11#[derive(Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
25#[repr(transparent)]
26pub struct Date(i32);
27
28impl Date {
29 pub const EPOCH: Self = Self(0);
31 pub const MIN: Self = Self(-719_528);
33 pub const MAX: Self = Self(2_932_896);
35
36 const DAYS_PER_CYCLE: i32 = 146_097;
40 const MARCH_EPOCH_OFFSET: i32 = 719_468;
41
42 #[must_use]
46 pub fn try_new(y: i32, m: u8, d: u8) -> Option<Self> {
47 if !(0..=9_999).contains(&y) {
48 return None;
49 }
50 let month_days = match m {
51 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
52 4 | 6 | 9 | 11 => 30,
53 2 if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) => 29,
54 2 => 28,
55 _ => return None,
56 };
57 if d == 0 || d > month_days {
58 return None;
59 }
60
61 let year = y - i32::from(m <= 2);
62 let cycle = year.div_euclid(400);
63 let cycle_year = year.rem_euclid(400);
64 let march_month = i32::from(m) + if m > 2 { -3 } else { 9 };
65 let cycle_day = 365 * cycle_year + cycle_year / 4 - cycle_year / 100
66 + (153 * march_month + 2) / 5
67 + i32::from(d)
68 - 1;
69 Self::try_from_days_since_epoch(
70 cycle * Self::DAYS_PER_CYCLE + cycle_day - Self::MARCH_EPOCH_OFFSET,
71 )
72 }
73
74 #[must_use]
76 pub const fn try_from_days_since_epoch(days: i32) -> Option<Self> {
77 if days < Self::MIN.0 || days > Self::MAX.0 {
78 None
79 } else {
80 Some(Self(days))
81 }
82 }
83
84 #[must_use]
86 pub const fn as_days_since_epoch(self) -> i32 {
87 self.0
88 }
89
90 #[must_use]
92 pub fn try_from_i64(days: i64) -> Option<Self> {
93 i32::try_from(days)
94 .ok()
95 .and_then(Self::try_from_days_since_epoch)
96 }
97
98 #[must_use]
100 pub fn try_from_u64(days: u64) -> Option<Self> {
101 i32::try_from(days)
102 .ok()
103 .and_then(Self::try_from_days_since_epoch)
104 }
105
106 #[must_use]
108 pub fn checked_add_days(self, days: i64) -> Option<Self> {
109 i64::from(self.0)
110 .checked_add(days)
111 .and_then(Self::try_from_i64)
112 }
113
114 #[must_use]
116 pub fn checked_sub_days(self, days: i64) -> Option<Self> {
117 i64::from(self.0)
118 .checked_sub(days)
119 .and_then(Self::try_from_i64)
120 }
121
122 #[must_use]
124 pub fn days_since(self, earlier: Self) -> i64 {
125 i64::from(self.0) - i64::from(earlier.0)
126 }
127
128 #[must_use]
130 pub fn year(self) -> i32 {
131 self.calendar_parts().0
132 }
133
134 #[must_use]
136 pub fn month(self) -> u8 {
137 self.calendar_parts().1
138 }
139
140 #[must_use]
142 pub fn day(self) -> u8 {
143 self.calendar_parts().2
144 }
145
146 #[must_use]
148 pub fn parse(s: &str) -> Option<Self> {
149 let bytes = s.as_bytes();
150 if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
151 return None;
152 }
153
154 let year = parse_ascii_i32(&bytes[0..4])?;
156 let month = parse_ascii_u8(&bytes[5..7])?;
157 let day = parse_ascii_u8(&bytes[8..10])?;
158
159 Self::try_new(year, month, day)
160 }
161
162 #[expect(
165 clippy::cast_possible_truncation,
166 clippy::cast_sign_loss,
167 reason = "bounded Gregorian conversion yields positive u8 month/day components"
168 )]
169 fn calendar_parts(self) -> (i32, u8, u8) {
170 let march_day = self.0 + Self::MARCH_EPOCH_OFFSET;
171 let cycle = march_day.div_euclid(Self::DAYS_PER_CYCLE);
172 let cycle_day = march_day.rem_euclid(Self::DAYS_PER_CYCLE);
173 let cycle_year =
174 (cycle_day - cycle_day / 1_460 + cycle_day / 36_524 - cycle_day / 146_096) / 365;
175 let year = cycle * 400 + cycle_year;
176 let march_ordinal = cycle_day - (365 * cycle_year + cycle_year / 4 - cycle_year / 100);
177 let march_month = (5 * march_ordinal + 2) / 153;
178 let day = march_ordinal - (153 * march_month + 2) / 5 + 1;
179 let month = march_month + if march_month < 10 { 3 } else { -9 };
180
181 (year + i32::from(month <= 2), month as u8, day as u8)
182 }
183}
184
185impl Debug for Date {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 write!(f, "Date({self})")
188 }
189}
190
191impl Display for Date {
192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193 let (year, month, day) = self.calendar_parts();
194 write!(f, "{year:04}-{month:02}-{day:02}")
195 }
196}
197
198impl NumericValue for Date {
199 fn try_to_decimal(&self) -> Option<Decimal> {
200 Decimal::from_i64(i64::from(self.0))
201 }
202
203 fn try_from_decimal(value: Decimal) -> Option<Self> {
204 value.to_i32().and_then(Self::try_from_days_since_epoch)
205 }
206}
207
208impl<'de> Deserialize<'de> for Date {
209 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
210 where
211 D: Deserializer<'de>,
212 {
213 if deserializer.is_human_readable() {
214 return Self::parse(&String::deserialize(deserializer)?)
215 .ok_or_else(|| serde::de::Error::custom(TypeParseError::InvalidDate));
216 }
217 Self::try_from_days_since_epoch(i32::deserialize(deserializer)?)
219 .ok_or_else(|| serde::de::Error::custom(TypeParseError::InvalidDate))
220 }
221}
222
223impl Serialize for Date {
224 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
225 where
226 S: serde::Serializer,
227 {
228 if serializer.is_human_readable() {
229 serializer.collect_str(self)
230 } else {
231 serializer.serialize_i32(self.0)
232 }
233 }
234}
235
236fn parse_ascii_i32(bytes: &[u8]) -> Option<i32> {
237 bytes.iter().try_fold(0_i32, |value, byte| {
238 byte.checked_sub(b'0')
239 .filter(|digit| *digit <= 9)
240 .and_then(|digit| value.checked_mul(10)?.checked_add(i32::from(digit)))
241 })
242}
243
244fn parse_ascii_u8(bytes: &[u8]) -> Option<u8> {
245 bytes.iter().try_fold(0_u8, |value, byte| {
246 byte.checked_sub(b'0')
247 .filter(|digit| *digit <= 9)
248 .and_then(|digit| value.checked_mul(10)?.checked_add(digit))
249 })
250}
251
252#[cfg(test)]
257mod tests;