1use serde::{Deserialize, Serialize};
2
3use crate::error::{AsyncValidationError, FieldIssue};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
7pub struct CivilDate {
8 pub year: i32,
9 pub month: u32,
10 pub day: u32,
11}
12
13impl CivilDate {
14 pub fn new(year: i32, month: u32, day: u32) -> Result<Self, FieldIssue> {
15 let date = Self { year, month, day };
16 date.validate_field("date")?;
17 Ok(date)
18 }
19
20 pub fn validate_field(&self, field: &str) -> Result<(), FieldIssue> {
21 if !(1..=12).contains(&self.month) {
22 return Err(FieldIssue::new(
23 field,
24 "INVALID_DATE",
25 "month must be 1..=12",
26 ));
27 }
28 let max_day = days_in_month(self.year, self.month);
29 if self.day < 1 || self.day > max_day {
30 return Err(FieldIssue::new(
31 field,
32 "INVALID_DATE",
33 format!("day must be 1..={max_day}"),
34 ));
35 }
36 Ok(())
37 }
38}
39
40impl std::fmt::Display for CivilDate {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
43 }
44}
45
46impl crate::traits::Normalize for CivilDate {
47 fn normalize(&mut self) {}
48}
49
50impl crate::traits::Validate for CivilDate {
51 fn validate_with(&self, _ctx: &crate::context::ValidationContext) -> Result<(), Vec<FieldIssue>> {
52 self.validate_field("").map_err(|e| vec![e])
53 }
54}
55
56impl<S> crate::traits::ScopedValidate<S> for CivilDate {
57 fn validate_scoped_with(
58 &self,
59 ctx: &crate::context::ValidationContext,
60 ) -> Result<(), Vec<FieldIssue>> {
61 crate::traits::Validate::validate_with(self, ctx)
62 }
63}
64
65#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
66#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
67impl<R: ?Sized + Sync, S> crate::traits::AsyncValidate<R, S> for CivilDate {
68 async fn validate_async_with(
69 &self,
70 ctx: &crate::context::ValidationContext,
71 _resolver: &R,
72 ) -> Result<(), AsyncValidationError> {
73 crate::traits::Validate::validate_with(self, ctx).map_err(AsyncValidationError::Issues)
74 }
75}
76
77const fn is_leap(year: i32) -> bool {
78 (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
79}
80
81const fn days_in_month(year: i32, month: u32) -> u32 {
82 match month {
83 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
84 4 | 6 | 9 | 11 => 30,
85 2 => {
86 if is_leap(year) {
87 29
88 } else {
89 28
90 }
91 }
92 _ => 0,
93 }
94}
95
96pub fn check_ymd(field: &str, value: &str) -> Result<CivilDate, FieldIssue> {
98 let bytes = value.as_bytes();
99 if !value.is_ascii()
100 || bytes.len() != 10
101 || bytes[4] != b'-'
102 || bytes[7] != b'-'
103 || !bytes[0..4].iter().all(u8::is_ascii_digit)
104 || !bytes[5..7].iter().all(u8::is_ascii_digit)
105 || !bytes[8..10].iter().all(u8::is_ascii_digit)
106 {
107 return Err(FieldIssue::new(
108 field,
109 "INVALID_DATE",
110 "date must be YYYY-MM-DD",
111 ));
112 }
113 let year: i32 = value[0..4]
114 .parse()
115 .map_err(|_| FieldIssue::new(field, "INVALID_DATE", "date must be YYYY-MM-DD"))?;
116 let month: u32 = value[5..7]
117 .parse()
118 .map_err(|_| FieldIssue::new(field, "INVALID_DATE", "date must be YYYY-MM-DD"))?;
119 let day: u32 = value[8..10]
120 .parse()
121 .map_err(|_| FieldIssue::new(field, "INVALID_DATE", "date must be YYYY-MM-DD"))?;
122 let date = CivilDate { year, month, day };
123 date.validate_field(field)?;
124 Ok(date)
125}
126
127pub fn check_rfc3339(field: &str, value: &str) -> Result<(), FieldIssue> {
129 if !value.is_ascii() || value.len() < 20 {
130 return Err(FieldIssue::new(
131 field,
132 "INVALID_DATE",
133 "timestamp must be RFC 3339",
134 ));
135 }
136 let bytes = value.as_bytes();
137 let looks_like = bytes[4] == b'-'
138 && bytes[7] == b'-'
139 && (bytes[10] == b'T' || bytes[10] == b't')
140 && bytes[13] == b':'
141 && bytes[16] == b':'
142 && bytes[11..13].iter().all(u8::is_ascii_digit)
143 && bytes[14..16].iter().all(u8::is_ascii_digit)
144 && bytes[17..19].iter().all(u8::is_ascii_digit);
145 if !looks_like {
146 return Err(FieldIssue::new(
147 field,
148 "INVALID_DATE",
149 "timestamp must be RFC 3339",
150 ));
151 }
152 let _date = check_ymd(field, &value[..10])?;
153 let hour: u32 = value[11..13]
154 .parse()
155 .map_err(|_| FieldIssue::new(field, "INVALID_DATE", "timestamp must be RFC 3339"))?;
156 let minute: u32 = value[14..16]
157 .parse()
158 .map_err(|_| FieldIssue::new(field, "INVALID_DATE", "timestamp must be RFC 3339"))?;
159 let second: u32 = value[17..19]
160 .parse()
161 .map_err(|_| FieldIssue::new(field, "INVALID_DATE", "timestamp must be RFC 3339"))?;
162 if hour > 23 || minute > 59 || second > 60 {
163 return Err(FieldIssue::new(
164 field,
165 "INVALID_DATE",
166 "timestamp time is out of range",
167 ));
168 }
169
170 let mut rest = &value[19..];
171 if let Some(after_dot) = rest.strip_prefix('.') {
172 let digits = after_dot
173 .as_bytes()
174 .iter()
175 .take_while(|b| b.is_ascii_digit())
176 .count();
177 if digits == 0 {
178 return Err(FieldIssue::new(
179 field,
180 "INVALID_DATE",
181 "timestamp fractional seconds are invalid",
182 ));
183 }
184 rest = &after_dot[digits..];
185 }
186
187 if rest == "Z" || rest == "z" {
188 return Ok(());
189 }
190 let tz_bytes = rest.as_bytes();
191 if tz_bytes.len() == 6
192 && (tz_bytes[0] == b'+' || tz_bytes[0] == b'-')
193 && tz_bytes[3] == b':'
194 && tz_bytes[1..3].iter().all(u8::is_ascii_digit)
195 && tz_bytes[4..6].iter().all(u8::is_ascii_digit)
196 {
197 let tz_h: u32 = rest[1..3].parse().map_err(|_| {
198 FieldIssue::new(field, "INVALID_DATE", "timestamp offset is invalid")
199 })?;
200 let tz_m: u32 = rest[4..6].parse().map_err(|_| {
201 FieldIssue::new(field, "INVALID_DATE", "timestamp offset is invalid")
202 })?;
203 if tz_h <= 23 && tz_m <= 59 {
204 return Ok(());
205 }
206 }
207
208 Err(FieldIssue::new(
209 field,
210 "INVALID_DATE",
211 "timestamp must include Z or ±HH:MM offset",
212 ))
213}
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218
219 #[test]
220 fn leap_day_and_ordering() {
221 let d1 = CivilDate::new(2024, 2, 29).unwrap();
222 let d2 = CivilDate::new(2024, 3, 1).unwrap();
223 assert!(d1 < d2);
224 assert_eq!(d1.to_string(), "2024-02-29");
225 assert!(CivilDate::new(2023, 2, 29).is_err());
226 }
227
228 #[test]
229 fn rfc3339_strict_timezone() {
230 assert!(check_rfc3339("when", "2024-01-02T03:04:05Z").is_ok());
231 assert!(check_rfc3339("when", "2024-01-02T03:04:05.123456789012+02:00").is_ok());
232 assert!(check_rfc3339("when", "2024-01-02T03:04:05").is_err());
233 assert!(check_rfc3339("when", "2024-01-02T03:04:05Zgarbage").is_err());
234 assert!(check_rfc3339("when", "2024-01-02T03:04:05+25:00").is_err());
235 }
236
237 #[test]
238 fn rejects_non_ascii_signed_and_untrimmed_dates() {
239 assert!(check_rfc3339("when", "2024-01-02T03:04:🔥Z").is_err());
240 assert!(check_ymd("date", "+024-+1-+2").is_err());
241 assert!(check_rfc3339("when", "2024-01-02T+1:+2:+3Z").is_err());
242 assert!(check_rfc3339("when", "2024-01-02T03:04:05++1:00").is_err());
243 assert!(check_rfc3339("when", " 2024-01-02T03:04:05Z").is_err());
244 assert!(check_rfc3339("when", "2024-01-02T03:04:05Z ").is_err());
245 }
246}