jmap_types/id.rs
1//! RFC 8620 §1.2/§1.4 opaque string newtypes: [`Id`], [`UTCDate`], [`Date`], [`State`].
2
3use serde::{Deserialize, Serialize};
4use std::fmt;
5
6/// Error returned by the fallible constructors [`Id::new_validated`],
7/// [`UTCDate::new_validated`], and [`State::new_validated`].
8///
9/// The message is reachable only through [`fmt::Display`]; the inner
10/// field is private, like the other newtypes in this module:
11///
12/// ```compile_fail
13/// let err = jmap_types::Id::new_validated("").unwrap_err();
14/// let _ = err.0;
15/// ```
16#[non_exhaustive]
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct ValidationError(String);
19
20impl fmt::Display for ValidationError {
21 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22 f.write_str(&self.0)
23 }
24}
25
26impl std::error::Error for ValidationError {}
27
28/// Opaque non-empty server-assigned identifier (RFC 8620 §1.2).
29///
30/// Character set: URL-safe base64 alphabet (A-Za-z0-9, `-`, `_`), max 255 octets.
31/// Clients MUST treat Id values as opaque strings — no parsing of structure.
32///
33/// # Deserialization is validated
34///
35/// Deserializing an `Id` applies the same check as [`Id::new_validated`],
36/// so a wire value outside the RFC 8620 §1.2 syntax is a deserialization
37/// error rather than an unchecked `Id`:
38///
39/// ```
40/// use jmap_types::Id;
41/// assert!(serde_json::from_str::<Id>("\"abc-_123\"").is_ok());
42/// assert!(serde_json::from_str::<Id>("\"has space\"").is_err());
43/// ```
44///
45/// [`Id::from`] remains an unchecked constructor for values the caller
46/// already trusts.
47// #[non_exhaustive] prevents callers from pattern-matching the inner field
48// (e.g. `let Id(s) = id;`), preserving semver freedom to add fields later.
49#[non_exhaustive]
50#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
51#[serde(transparent)]
52pub struct Id(String);
53
54// A manual impl rather than `#[serde(try_from = "String")]`: the existing
55// `From<String>` makes the blanket `TryFrom<String>` infallible, so a
56// fallible `TryFrom<String>` cannot be added (see the note above
57// `validate_id`).
58impl<'de> Deserialize<'de> for Id {
59 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
60 let s = String::deserialize(deserializer)?;
61 Self::new_validated(s).map_err(serde::de::Error::custom)
62 }
63}
64
65/// RFC 3339 UTC timestamp string (RFC 8620 §1.4).
66///
67/// Format: `YYYY-MM-DDTHH:MM:SS[.fff…]Z` — time-offset MUST be `Z`, letters
68/// uppercase, fractional seconds omitted if zero. Examples:
69/// `"2014-10-30T06:12:00Z"`, `"2014-10-30T06:12:00.123Z"`.
70///
71/// # Deserialization is NOT validated
72///
73/// `UTCDate` is `#[serde(transparent)]` over `String`. Any string that
74/// deserializes into a `String` deserializes into a `UTCDate` — including
75/// `"not-a-date"`, `"2024-01-19T18:00:00"` (no `Z` suffix), or any other
76/// shape that violates RFC 8620 §1.4. The newtype carries the
77/// **type-level intent** of "RFC 8620 UTC timestamp" but does NOT enforce
78/// it at the wire boundary.
79///
80/// Use [`UTCDate::new_validated`] when constructing from untrusted input,
81/// or call [`UTCDate::to_epoch_seconds`] when consuming a deserialized
82/// value: the latter re-validates structural format AND semantic ranges
83/// (month, day, hour, minute, second) and returns [`ValidationError`] on
84/// any deviation. Treat any field of type `Option<UTCDate>` arriving
85/// from a peer as "RFC 8620 timestamp by convention, not by contract".
86// #[non_exhaustive] prevents callers from pattern-matching the inner field,
87// preserving semver freedom to add fields later.
88#[non_exhaustive]
89#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
90#[serde(transparent)]
91pub struct UTCDate(String);
92
93/// RFC 3339 date-time string with any timezone offset (RFC 8620 §1.4).
94///
95/// Format: `YYYY-MM-DDTHH:MM:SS±HH:MM` or `Z` suffix — any valid RFC 3339 offset,
96/// letters uppercase, fractional seconds omitted if zero.
97/// Example: `"2014-10-30T14:12:00+08:00"`.
98///
99/// Distinct from [`UTCDate`], which requires the time-offset to be `Z`.
100/// Use `Date` for fields derived from RFC 5322 email headers (e.g. `sentAt`),
101/// which commonly carry non-UTC offsets.
102///
103/// # Deserialization is NOT validated
104///
105/// `Date` is `#[serde(transparent)]` over `String`. Any string that
106/// deserializes into a `String` deserializes into a `Date`, including
107/// values that violate RFC 8620 §1.4 / RFC 3339. The newtype carries
108/// the **type-level intent** but does NOT enforce it at the wire
109/// boundary. Treat any field of type `Option<Date>` arriving from a
110/// peer as "RFC 8620 timestamp by convention, not by contract".
111// #[non_exhaustive] prevents callers from pattern-matching the inner field,
112// preserving semver freedom to add fields later.
113#[non_exhaustive]
114#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
115#[serde(transparent)]
116pub struct Date(String);
117
118/// Opaque server state token (RFC 8620 §1.2).
119///
120/// Returned by `/get` and `/changes` methods. Clients echo it back in
121/// `sinceState` / `ifInState` parameters. Treat as opaque — no structure assumed.
122///
123/// # Migrating from `String`-typed code
124///
125/// Earlier revisions of this crate exposed state fields as
126/// `pub session_state: String` on [`crate::JmapResponse`] and similar
127/// shapes. The current revision uses the `State` newtype for type
128/// safety. The wire format is unchanged (`State` is
129/// `#[serde(transparent)]` over `String`). The Rust API conversions
130/// available to callers migrating from `String`:
131///
132/// - Read as `&str`: `state.as_ref()` (via `AsRef<str>`) or
133/// `format!("{state}")` (via `Display`).
134/// - Compare to a literal: `state == "abc"` (via `PartialEq<str>`).
135/// - Move into an owned `String`: `state.into_inner()`.
136/// - Borrow as `&String`: not directly available; use `as_ref()` to
137/// get `&str` instead.
138/// - Build from `&str` or `String`: `State::from("abc")` or
139/// `State::from(my_string)` (via `From<&str>` / `From<String>`).
140///
141/// Callers passing a `State` to a function that takes `String` should
142/// either change the signature to `impl AsRef<str>` or call
143/// `state.into_inner()` at the boundary. Callers keying a
144/// `HashMap<String, _>` by state token can either rekey by
145/// `HashMap<State, _>` (`State` implements `Hash + Eq`) or call
146/// `state.into_inner()` at insertion / lookup time.
147// #[non_exhaustive] prevents callers from pattern-matching the inner field,
148// preserving semver freedom to add fields later.
149#[non_exhaustive]
150#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
151#[serde(transparent)]
152pub struct State(String);
153
154/// Generates `Display`, `From<String>`, `From<&str>`, `AsRef<str>`,
155/// `PartialEq<str>`, `PartialEq<&str>`, and `into_inner` for a transparent
156/// `String` newtype.
157macro_rules! impl_string_newtype {
158 ($T:ident) => {
159 impl fmt::Display for $T {
160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161 f.write_str(&self.0)
162 }
163 }
164 impl From<String> for $T {
165 fn from(s: String) -> Self {
166 Self(s)
167 }
168 }
169 impl From<&str> for $T {
170 fn from(s: &str) -> Self {
171 Self(s.to_owned())
172 }
173 }
174 impl AsRef<str> for $T {
175 fn as_ref(&self) -> &str {
176 &self.0
177 }
178 }
179 impl PartialEq<str> for $T {
180 fn eq(&self, other: &str) -> bool {
181 self.0 == other
182 }
183 }
184 impl PartialEq<&str> for $T {
185 fn eq(&self, other: &&str) -> bool {
186 self.0 == *other
187 }
188 }
189 impl std::borrow::Borrow<str> for $T {
190 fn borrow(&self) -> &str {
191 &self.0
192 }
193 }
194 impl $T {
195 /// Consumes the value and returns the inner `String`.
196 pub fn into_inner(self) -> String {
197 self.0
198 }
199 }
200 };
201}
202
203impl_string_newtype!(Id);
204impl_string_newtype!(UTCDate);
205impl_string_newtype!(Date);
206impl_string_newtype!(State);
207
208// ---------------------------------------------------------------------------
209// Fallible constructors — validate RFC 8620 constraints at the boundary.
210//
211// These are named constructors (not TryFrom impls) because Id/UTCDate/State
212// already implement From<String> and From<&str>. Rust's blanket impl
213// `impl<T,U> TryFrom<U> where U: Into<T>` would make TryFrom<String>
214// infallible (Error = Infallible) via the existing From impl, making it
215// impossible to add a second, fallible TryFrom<String>. Named constructors
216// achieve the same goal without the conflict.
217// ---------------------------------------------------------------------------
218
219/// Validate an [`Id`] string per RFC 8620 §1.2.
220///
221/// RFC 8620 §1.2 requires Ids to use the "URL and Filename Safe" base64
222/// alphabet defined in RFC 4648 §5, excluding the pad character `=`.
223/// That is: ASCII alphanumeric characters (`A-Z`, `a-z`, `0-9`), hyphen
224/// (`-`), and underscore (`_`). The string must also be non-empty and
225/// at most 255 bytes.
226fn validate_id(s: &str) -> Result<(), ValidationError> {
227 if s.is_empty() {
228 return Err(ValidationError("Id must not be empty".into()));
229 }
230 if s.len() > 255 {
231 return Err(ValidationError(format!(
232 "Id exceeds 255 bytes (got {})",
233 s.len()
234 )));
235 }
236 for ch in s.chars() {
237 // RFC 4648 §5 URL-safe base64 alphabet, minus the pad `=`:
238 // A-Z, a-z, 0-9, '-', '_'.
239 if !ch.is_ascii_alphanumeric() && ch != '-' && ch != '_' {
240 return Err(ValidationError(format!(
241 "Id contains invalid character {:?} (U+{:04X})",
242 ch, ch as u32
243 )));
244 }
245 }
246 Ok(())
247}
248
249/// Validate a [`UTCDate`] string per RFC 8620 §1.4.
250///
251/// Validation has two layers:
252///
253/// 1. **Shape**: the `YYYY-MM-DDTHH:MM:SS` layout with ASCII digits in
254/// every numeric position, an optional RFC 3339 `time-secfrac`
255/// (`.` followed by one or more digits, not all zero, because RFC 8620
256/// §1.4 says it "MUST always be omitted if zero"), then `Z`.
257/// 2. **Values**: month in `1..=12`, day in `1..=days_in_month(year,
258/// month)` (proleptic Gregorian, exact leap-year rules), hour in
259/// `0..=23`, minute in `0..=59`, second in `0..=59` (RFC 8620 §1.4
260/// does not permit leap seconds even though RFC 3339 §5.6 does).
261///
262/// No external crate needed.
263fn validate_utcdate(s: &str) -> Result<(), ValidationError> {
264 if s.len() < 20 {
265 return Err(ValidationError(format!(
266 "UTCDate must be at least 20 characters (YYYY-MM-DDTHH:MM:SSZ), got {:?}",
267 s
268 )));
269 }
270 let b = s.as_bytes();
271 // Tail after the seconds: `Z`, or `.` + non-zero digit run + `Z`.
272 let tail_ok = match &b[19..] {
273 [b'Z'] => true,
274 [b'.', frac @ .., b'Z'] => {
275 !frac.is_empty()
276 && frac.iter().all(u8::is_ascii_digit)
277 && frac.iter().any(|&d| d != b'0')
278 }
279 _ => false,
280 };
281 // Fixed separators: dashes, T, colons.
282 if !tail_ok || b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' {
283 return Err(ValidationError(format!(
284 "UTCDate has wrong structure, expected YYYY-MM-DDTHH:MM:SS[.fff]Z, got {:?}",
285 s
286 )));
287 }
288 // Digit positions: 0-3 (year), 5-6 (month), 8-9 (day),
289 // 11-12 (hour), 14-15 (min), 17-18 (sec).
290 for &pos in &[0, 1, 2, 3, 5, 6, 8, 9, 11, 12, 14, 15, 17, 18] {
291 if !b[pos].is_ascii_digit() {
292 return Err(ValidationError(format!(
293 "UTCDate position {} is not a digit in {:?}",
294 pos, s
295 )));
296 }
297 }
298
299 // Value-range checks. Shape is now confirmed, so digit positions
300 // are guaranteed ASCII digits and the parses are infallible.
301 let parse = |start: usize, end: usize| -> i64 {
302 let mut n: i64 = 0;
303 for &byte in &b[start..end] {
304 n = n * 10 + (byte - b'0') as i64;
305 }
306 n
307 };
308 let year = parse(0, 4);
309 let month = parse(5, 7) as u32;
310 let day = parse(8, 10) as u32;
311 let hour = parse(11, 13) as u32;
312 let minute = parse(14, 16) as u32;
313 let second = parse(17, 19) as u32;
314
315 if !(1..=12).contains(&month) {
316 return Err(ValidationError(format!(
317 "UTCDate month must be 1..=12, got {month} in {s:?}"
318 )));
319 }
320 let max_day = days_in_month(year, month);
321 if !(1..=max_day).contains(&day) {
322 return Err(ValidationError(format!(
323 "UTCDate day must be 1..={max_day} for {year:04}-{month:02}, got {day} in {s:?}"
324 )));
325 }
326 if hour > 23 {
327 return Err(ValidationError(format!(
328 "UTCDate hour must be 0..=23, got {hour} in {s:?}"
329 )));
330 }
331 if minute > 59 {
332 return Err(ValidationError(format!(
333 "UTCDate minute must be 0..=59, got {minute} in {s:?}"
334 )));
335 }
336 // No leap seconds in RFC 8620 §1.4 (it specifies seconds 0..=59).
337 if second > 59 {
338 return Err(ValidationError(format!(
339 "UTCDate second must be 0..=59, got {second} in {s:?}"
340 )));
341 }
342 Ok(())
343}
344
345/// Validate a [`State`] string: must be non-empty.
346///
347/// RFC 8620 §1.2 does not restrict the character set for State beyond
348/// requiring it to be non-empty.
349fn validate_state(s: &str) -> Result<(), ValidationError> {
350 if s.is_empty() {
351 return Err(ValidationError("State must not be empty".into()));
352 }
353 Ok(())
354}
355
356impl Id {
357 /// Construct an [`Id`] with RFC 8620 §1.2 syntax validation.
358 ///
359 /// RFC 8620 §1.2 restricts Ids to the URL-safe base64 alphabet defined
360 /// in RFC 4648 §5, excluding the pad character `=`. The permitted
361 /// characters are therefore the ASCII alphanumerics (`A-Z`, `a-z`,
362 /// `0-9`), hyphen (`-`), and underscore (`_`). The string must also
363 /// be non-empty and at most 255 bytes.
364 ///
365 /// # Errors
366 ///
367 /// Returns [`ValidationError`] when the input does not satisfy
368 /// RFC 8620 §1.2. The error description contains a category keyword
369 /// that callers can match on if they need finer-grained handling:
370 ///
371 /// - `"empty"` — the input was an empty string;
372 /// - `"exceeds 255 bytes"` — the input was longer than the spec
373 /// maximum;
374 /// - `"invalid character"` — the input contained at least one
375 /// character outside `A-Z`, `a-z`, `0-9`, `-`, `_`.
376 ///
377 /// Use [`Id::from`] when the value is known to be valid (e.g. a string
378 /// received from a JMAP server response).
379 pub fn new_validated(s: impl Into<String>) -> Result<Self, ValidationError> {
380 let s = s.into();
381 validate_id(&s)?;
382 Ok(Self(s))
383 }
384}
385
386impl UTCDate {
387 /// Construct a [`UTCDate`] with RFC 8620 §1.4 validation.
388 ///
389 /// Validation has two layers:
390 ///
391 /// 1. **Shape**: the `YYYY-MM-DDTHH:MM:SS` layout with ASCII
392 /// digits in every numeric position, an optional fractional
393 /// second (`.` and one or more digits, rejected when all zero
394 /// because RFC 8620 §1.4 requires a zero `time-secfrac` to be
395 /// omitted), then `Z`.
396 /// 2. **Values**: month `1..=12`; day `1..=days_in_month(year,
397 /// month)` with proleptic Gregorian leap-year rules so e.g.
398 /// `2024-02-29` is accepted but `2023-02-29` and `2024-02-30`
399 /// are rejected; hour `0..=23`; minute `0..=59`; second
400 /// `0..=59` (RFC 8620 §1.4 does not permit leap seconds even
401 /// though RFC 3339 §5.6 does).
402 ///
403 /// # Errors
404 ///
405 /// Returns [`ValidationError`] when the input does not satisfy
406 /// RFC 8620 §1.4. The error description contains a substring that
407 /// callers can match on if they need finer-grained handling:
408 ///
409 /// - `"at least 20 characters"` — too short;
410 /// - `"wrong structure"` — separators or `Z` suffix missing /
411 /// misplaced, or a fractional second that is empty, non-numeric
412 /// or zero;
413 /// - `"is not a digit"` — non-digit at a numeric position;
414 /// - `"month must be"` — month outside `1..=12`;
415 /// - `"day must be"` — day outside `1..=days_in_month(year,
416 /// month)` (catches both out-of-range day numbers like `32` and
417 /// non-existent dates like Feb 30 or Feb 29 in a non-leap year);
418 /// - `"hour must be"`, `"minute must be"`, `"second must be"` —
419 /// the corresponding time component is out of range.
420 ///
421 /// Use [`UTCDate::from`] when the value is known to be valid.
422 pub fn new_validated(s: impl Into<String>) -> Result<Self, ValidationError> {
423 let s = s.into();
424 validate_utcdate(&s)?;
425 Ok(Self(s))
426 }
427
428 /// Convert this [`UTCDate`] to seconds since the Unix epoch
429 /// (`1970-01-01T00:00:00Z`).
430 ///
431 /// Re-validates the structural RFC 8620 §1.4 format (the value may have
432 /// been constructed via [`UTCDate::from`] without validation) and also
433 /// validates semantic ranges: month `1..=12`, day `1..=days_in_month`,
434 /// hour `0..=23`, minute `0..=59`, second `0..=59` (no leap seconds).
435 ///
436 /// Negative values are returned for dates before `1970-01-01T00:00:00Z`.
437 /// A fractional second is truncated toward the earlier whole second.
438 ///
439 /// Uses the proleptic Gregorian calendar via Hinnant's `days_from_civil`
440 /// algorithm, which is exact-integer and handles leap years and century
441 /// rules correctly. No external dependencies.
442 ///
443 /// # Errors
444 ///
445 /// Returns [`ValidationError`] if the value is not structurally an
446 /// RFC 8620 §1.4 `UTCDate`, or a field is out of range: month outside
447 /// `1..=12`, day past the end of its month, hour above 23, or minute or
448 /// second above 59.
449 ///
450 /// # Examples
451 ///
452 /// ```
453 /// use jmap_types::UTCDate;
454 /// let d = UTCDate::new_validated("1970-01-01T00:00:00Z").unwrap();
455 /// assert_eq!(d.to_epoch_seconds().unwrap(), 0);
456 /// let rfc = UTCDate::new_validated("2014-10-30T06:12:00Z").unwrap();
457 /// assert_eq!(rfc.to_epoch_seconds().unwrap(), 1_414_649_520);
458 /// ```
459 pub fn to_epoch_seconds(&self) -> Result<i64, ValidationError> {
460 utcdate_to_epoch_seconds(&self.0)
461 }
462
463 /// Compare the instants `self` and `other` denote.
464 ///
465 /// Whole seconds first, then the fractional seconds compared as
466 /// decimals, so `…:00.5Z` is later than `…:00Z` and `…:00.50Z` equals
467 /// `…:00.5Z`. Use this rather than string order (`"…00.5Z" <
468 /// "…00Z"`), [`to_epoch_seconds`](Self::to_epoch_seconds) (which
469 /// truncates fractions), or a conversion to a fixed precision (RFC 8620
470 /// §1.4 sets no limit on fractional digits).
471 ///
472 /// # Errors
473 ///
474 /// [`ValidationError`] when either value is not a valid RFC 8620 §1.4
475 /// `UTCDate` (one built with [`UTCDate::from`] is re-validated).
476 ///
477 /// # Examples
478 ///
479 /// ```
480 /// use std::cmp::Ordering;
481 /// use jmap_types::UTCDate;
482 /// let whole = UTCDate::new_validated("2025-01-01T00:00:00Z").unwrap();
483 /// let half = UTCDate::new_validated("2025-01-01T00:00:00.5Z").unwrap();
484 /// assert_eq!(half.cmp_instant(&whole).unwrap(), Ordering::Greater);
485 /// ```
486 pub fn cmp_instant(&self, other: &UTCDate) -> Result<std::cmp::Ordering, ValidationError> {
487 let seconds = self.to_epoch_seconds()?.cmp(&other.to_epoch_seconds()?);
488 Ok(seconds.then_with(|| cmp_fraction(fraction(&self.0), fraction(&other.0))))
489 }
490}
491
492/// The fractional-second digits of a validated `UTCDate` (after `.`), or
493/// `""`.
494fn fraction(s: &str) -> &str {
495 s.get(19..s.len().saturating_sub(1))
496 .and_then(|f| f.strip_prefix('.'))
497 .unwrap_or("")
498}
499
500/// Compare two strings of decimal digits as fractions (`"5"` = 0.5), the
501/// shorter padded with zeros.
502fn cmp_fraction(a: &str, b: &str) -> std::cmp::Ordering {
503 let (a, b) = (a.as_bytes(), b.as_bytes());
504 (0..a.len().max(b.len()))
505 .map(|i| {
506 let x = a.get(i).copied().unwrap_or(b'0');
507 let y = b.get(i).copied().unwrap_or(b'0');
508 x.cmp(&y)
509 })
510 .find(|o| o.is_ne())
511 .unwrap_or(std::cmp::Ordering::Equal)
512}
513
514/// Number of days in `month` of `year`, accounting for proleptic Gregorian
515/// leap-year rules (year divisible by 4, except centuries not divisible by 400).
516fn days_in_month(year: i64, month: u32) -> u32 {
517 match month {
518 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
519 4 | 6 | 9 | 11 => 30,
520 2 => {
521 if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 {
522 29
523 } else {
524 28
525 }
526 }
527 _ => 0, // unreachable when month range is validated by caller
528 }
529}
530
531/// Hinnant's `days_from_civil` algorithm: number of days from
532/// `1970-01-01` (positive) or to `1970-01-01` (negative) for the proleptic
533/// Gregorian date `(y, m, d)`. Source: Howard Hinnant, "chrono-Compatible
534/// Low-Level Date Algorithms", §6.
535///
536/// Preconditions (caller-validated): `m` in `1..=12`, `d` in
537/// `1..=days_in_month(y, m)`. Years are unbounded `i64`.
538fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
539 let y = if m <= 2 { y - 1 } else { y };
540 let era = if y >= 0 { y } else { y - 399 } / 400;
541 let yoe = y - era * 400; // [0, 399]
542 let m = m as i64;
543 let d = d as i64;
544 let mp = if m > 2 { m - 3 } else { m + 9 }; // [0, 11]
545 let doy = (153 * mp + 2) / 5 + d - 1; // [0, 365]
546 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
547 era * 146097 + doe - 719_468
548}
549
550/// Internal helper: convert a `YYYY-MM-DDTHH:MM:SS[.fff]Z` string to epoch
551/// seconds, truncating any fractional second.
552///
553/// `validate_utcdate` performs both shape and value-range validation;
554/// after it returns Ok, the per-position digit parses are infallible
555/// and the parsed values are within their RFC 8620 §1.4 ranges.
556fn utcdate_to_epoch_seconds(s: &str) -> Result<i64, ValidationError> {
557 validate_utcdate(s)?;
558 let parse = |start: usize, end: usize| -> i64 {
559 let mut n: i64 = 0;
560 for &b in &s.as_bytes()[start..end] {
561 n = n * 10 + (b - b'0') as i64;
562 }
563 n
564 };
565 let year = parse(0, 4);
566 let month = parse(5, 7) as u32;
567 let day = parse(8, 10) as u32;
568 let hour = parse(11, 13) as u32;
569 let minute = parse(14, 16) as u32;
570 let second = parse(17, 19) as u32;
571
572 let days = days_from_civil(year, month, day);
573 Ok(days * 86_400 + hour as i64 * 3_600 + minute as i64 * 60 + second as i64)
574}
575
576impl State {
577 /// Construct a [`State`] with RFC 8620 §1.2 validation.
578 ///
579 /// Rejects empty strings. RFC 8620 §1.2 requires State to be non-empty;
580 /// no character-set restriction is imposed.
581 ///
582 /// Use [`State::from`] when the value is known to be valid.
583 ///
584 /// # Errors
585 ///
586 /// Returns [`ValidationError`] if `s` is empty.
587 pub fn new_validated(s: impl Into<String>) -> Result<Self, ValidationError> {
588 let s = s.into();
589 validate_state(&s)?;
590 Ok(Self(s))
591 }
592}
593
594#[cfg(test)]
595mod tests {
596
597 /// RFC 8620 §1.4: `time-secfrac` is a decimal fraction of a second, so
598 /// instants compare by seconds and then by that fraction's value, not
599 /// by string order or a truncated precision (bd JMAP-tna1.3.1).
600 #[test]
601 fn cmp_instant_compares_fractions_as_decimals() {
602 use std::cmp::Ordering::{Equal, Greater, Less};
603 let d = |s: &str| UTCDate::new_validated(s).unwrap();
604 let whole = d("2025-01-01T00:00:00Z");
605 assert_eq!(
606 d("2025-01-01T00:00:00.5Z").cmp_instant(&whole).unwrap(),
607 Greater
608 );
609 assert_eq!(
610 d("2025-01-01T00:00:00.0000000001Z")
611 .cmp_instant(&whole)
612 .unwrap(),
613 Greater
614 );
615 assert_eq!(
616 d("2025-01-01T00:00:00.5Z")
617 .cmp_instant(&d("2025-01-01T00:00:00.50Z"))
618 .unwrap(),
619 Equal
620 );
621 assert_eq!(
622 d("2025-01-01T00:00:00.09Z")
623 .cmp_instant(&d("2025-01-01T00:00:00.1Z"))
624 .unwrap(),
625 Less
626 );
627 assert_eq!(
628 d("2024-12-31T23:59:59.999Z").cmp_instant(&whole).unwrap(),
629 Less
630 );
631 assert!(UTCDate::from("nope").cmp_instant(&whole).is_err());
632 }
633 use super::*;
634
635 // Oracle: RFC 8620 §1.2 — Id is a plain JSON string, not a wrapped object.
636 #[test]
637 fn id_serializes_as_plain_string() {
638 let id = Id("abc123".to_owned());
639 let json = serde_json::to_string(&id).expect("serialize Id");
640 assert_eq!(json, "\"abc123\"");
641 }
642
643 // Oracle: RFC 8620 §1.2 — Id round-trips through JSON.
644 #[test]
645 fn id_deserializes_from_plain_string() {
646 let id: Id = serde_json::from_str("\"abc123\"").expect("deserialize Id");
647 assert_eq!(id.as_ref(), "abc123");
648 }
649
650 // Oracle: RFC 8620 §1.2 — "MUST be at least 1 character in length and
651 // maximum 255 octets in size" and "MUST only contain characters from the
652 // 'URL and Filename Safe' base64 alphabet ... excluding the pad
653 // character (=)". Hand-written JSON strings outside that rule must fail
654 // to deserialize.
655 #[test]
656 fn id_deserialize_rejects_non_conforming_strings() {
657 let too_long = format!("\"{}\"", "a".repeat(256));
658 for json in [
659 "\"\"",
660 "\"has space\"",
661 "\"#creation\"",
662 "\"a=\"",
663 "\"a/b\"",
664 "\"a.b\"",
665 too_long.as_str(),
666 ] {
667 assert!(
668 serde_json::from_str::<Id>(json).is_err(),
669 "{json} must be rejected"
670 );
671 }
672 }
673
674 // Oracle: RFC 8620 §1.2 — the full alphabet and the 255-octet maximum
675 // are accepted.
676 #[test]
677 fn id_deserialize_accepts_conforming_strings() {
678 let max = format!("\"{}\"", "Z".repeat(255));
679 for json in ["\"AZaz09-_\"", max.as_str()] {
680 assert!(
681 serde_json::from_str::<Id>(json).is_ok(),
682 "{json} must be accepted"
683 );
684 }
685 }
686
687 // Oracle: RFC 8620 §1.2 — Ids used as JSON object keys (e.g. /set
688 // "update") are validated the same way.
689 #[test]
690 fn id_deserialize_validates_map_keys() {
691 use std::collections::HashMap;
692 let ok: HashMap<Id, u8> = serde_json::from_str(r#"{"m1":1}"#).expect("valid key");
693 assert_eq!(ok.get("m1"), Some(&1));
694 assert!(serde_json::from_str::<HashMap<Id, u8>>(r#"{"bad key":1}"#).is_err());
695 }
696
697 // Oracle: RFC 8620 §1.4 example — "2014-10-30T06:12:00Z".
698 #[test]
699 fn utcdate_serializes_as_plain_string() {
700 let d = UTCDate("2014-10-30T06:12:00Z".to_owned());
701 let json = serde_json::to_string(&d).expect("serialize UTCDate");
702 assert_eq!(json, "\"2014-10-30T06:12:00Z\"");
703 }
704
705 // Oracle: RFC 8620 §3.4.1 fixture — sessionState value is "75128aab4b1b".
706 #[test]
707 fn state_serializes_as_plain_string() {
708 let s = State("75128aab4b1b".to_owned());
709 let json = serde_json::to_string(&s).expect("serialize State");
710 assert_eq!(json, "\"75128aab4b1b\"");
711 }
712
713 // Oracle: From<&str> trait contract.
714 #[test]
715 fn id_from_str() {
716 let id = Id::from("hello");
717 assert_eq!(id.as_ref(), "hello");
718 }
719
720 // Oracle: Display delegates to inner String.
721 #[test]
722 fn id_display() {
723 let id = Id("display-test".to_owned());
724 assert_eq!(id.to_string(), "display-test");
725 }
726
727 // Oracle: AsRef<str> returns the inner string.
728 #[test]
729 fn id_as_ref_str() {
730 let id = Id("ref-test".to_owned());
731 assert_eq!(id.as_ref(), "ref-test");
732 }
733
734 // Oracle: RFC 8620 §3.4.1 — State in sessionState field round-trips correctly.
735 #[test]
736 fn state_round_trip() {
737 let s = State("75128aab4b1b".to_owned());
738 let json = serde_json::to_string(&s).expect("serialize");
739 let s2: State = serde_json::from_str(&json).expect("deserialize");
740 assert_eq!(s, s2);
741 }
742
743 // Oracle: RFC 8620 §1.4 example — Date allows non-UTC offsets, unlike UTCDate.
744 #[test]
745 fn date_accepts_non_utc_offset() {
746 let d = Date("2014-10-30T14:12:00+08:00".to_owned());
747 let json = serde_json::to_string(&d).expect("serialize Date");
748 assert_eq!(json, "\"2014-10-30T14:12:00+08:00\"");
749 let d2: Date = serde_json::from_str(&json).expect("deserialize Date");
750 assert_eq!(d, d2);
751 }
752
753 // -----------------------------------------------------------------------
754 // new_validated / ValidationError tests
755 // Oracle for all: RFC 8620 §1.2 (Id, State) and §1.4 (UTCDate).
756 // -----------------------------------------------------------------------
757
758 /// Oracle: RFC 8620 §1.2 — Id must not be empty.
759 #[test]
760 fn id_new_validated_empty_fails() {
761 let err = Id::new_validated("").unwrap_err();
762 assert!(err.0.contains("empty"), "error must mention 'empty': {err}");
763 }
764
765 /// Oracle: RFC 8620 §1.2 URL-safe base64 alphabet — space (0x20) is
766 /// not in `A-Za-z0-9-_`.
767 #[test]
768 fn id_new_validated_space_fails() {
769 let err = Id::new_validated("has space").unwrap_err();
770 assert!(err.0.contains("invalid character"), "{err}");
771 }
772
773 /// Oracle: RFC 8620 §1.2 URL-safe base64 alphabet — double-quote
774 /// (0x22) is not in `A-Za-z0-9-_`.
775 #[test]
776 fn id_new_validated_dquote_fails() {
777 let err = Id::new_validated("has\"quote").unwrap_err();
778 assert!(err.0.contains("invalid character"), "{err}");
779 }
780
781 /// Oracle: RFC 8620 §1.2 URL-safe base64 alphabet — a control
782 /// character (0x01) is not in `A-Za-z0-9-_`.
783 #[test]
784 fn id_new_validated_control_char_fails() {
785 let err = Id::new_validated("has\x01ctrl").unwrap_err();
786 assert!(err.0.contains("invalid character"), "{err}");
787 }
788
789 /// Oracle: RFC 8620 §1.2 URL-safe base64 alphabet (RFC 4648 §5) —
790 /// every visible-ASCII character outside `A-Za-z0-9-_` MUST be
791 /// rejected. These characters were accepted by the previous
792 /// (incorrect) `SAFE-CHAR` validator; this test pins the spec-
793 /// conforming rejection (bd:JMAP-6xs8.19).
794 #[test]
795 fn id_new_validated_rejects_non_url_safe_base64_chars() {
796 // Representative sample of characters that are visible ASCII
797 // (the old SAFE-CHAR set) but NOT in the RFC 4648 §5 URL-safe
798 // base64 alphabet. Each MUST be rejected with category
799 // "invalid character".
800 let rejected = [
801 '!', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '.', '/', ':', ';', '<', '=',
802 '>', '?', '@', '[', '\\', ']', '^', '`', '{', '|', '}', '~',
803 ];
804 for ch in rejected {
805 let input = format!("a{ch}z");
806 let err = Id::new_validated(&input).unwrap_err();
807 assert!(
808 err.0.contains("invalid character"),
809 "char {ch:?} (input {input:?}) must be rejected with \
810 'invalid character', got: {err}"
811 );
812 }
813 }
814
815 /// Oracle: RFC 8620 §1.2 — max length 255 bytes.
816 #[test]
817 fn id_new_validated_too_long_fails() {
818 let long = "a".repeat(256);
819 assert!(Id::new_validated(long).is_err());
820 }
821
822 /// Oracle: valid printable ASCII Id succeeds and is preserved verbatim.
823 #[test]
824 fn id_new_validated_valid_succeeds() {
825 let id = Id::new_validated("abc123-_ABC").expect("valid Id must succeed");
826 assert_eq!(id.as_ref(), "abc123-_ABC");
827 }
828
829 /// Oracle: exactly 255-byte Id succeeds.
830 #[test]
831 fn id_new_validated_max_length_succeeds() {
832 let id255 = "a".repeat(255);
833 Id::new_validated(id255).expect("255-byte Id must succeed");
834 }
835
836 /// Oracle: RFC 8620 §1.4 example "2014-10-30T06:12:00Z" must succeed.
837 #[test]
838 fn utcdate_new_validated_valid_succeeds() {
839 let d = UTCDate::new_validated("2014-10-30T06:12:00Z").expect("valid UTCDate must succeed");
840 assert_eq!(d.as_ref(), "2014-10-30T06:12:00Z");
841 }
842
843 /// Oracle: UTC date without Z suffix is not RFC 8620 §1.4 format.
844 #[test]
845 fn utcdate_new_validated_no_z_fails() {
846 assert!(UTCDate::new_validated("2014-10-30T06:12:00+00:00").is_err());
847 }
848
849 /// Oracle: empty UTCDate fails.
850 #[test]
851 fn utcdate_new_validated_empty_fails() {
852 assert!(UTCDate::new_validated("").is_err());
853 }
854
855 /// Oracle: UTCDate with wrong length fails.
856 #[test]
857 fn utcdate_new_validated_wrong_length_fails() {
858 assert!(UTCDate::new_validated("2014-10-30").is_err());
859 // fractional seconds are not permitted in RFC 8620 §1.4 format.
860 assert!(UTCDate::new_validated("2014-10-30T06:12:00.000Z").is_err());
861 }
862
863 /// Oracle: RFC 8620 §1.4 makes UTCDate an RFC 3339 "date-time"
864 /// (`time-secfrac = "." 1*DIGIT`) where "the "time-secfrac" MUST
865 /// always be omitted if zero" (rfc8620.txt:346-347). A non-zero
866 /// fraction is therefore valid.
867 #[test]
868 fn utcdate_new_validated_nonzero_secfrac_succeeds() {
869 for s in [
870 "2014-10-30T06:12:00.123Z",
871 "2014-10-30T06:12:00.1Z",
872 "2014-10-30T06:12:00.001Z",
873 "2014-10-30T06:12:00.000001Z",
874 ] {
875 assert!(UTCDate::new_validated(s).is_ok(), "{s} must be accepted");
876 }
877 }
878
879 /// Oracle: RFC 3339 `time-secfrac = "." 1*DIGIT` plus the RFC 8620
880 /// §1.4 omit-if-zero rule: an empty, zero, or non-digit fraction fails.
881 #[test]
882 fn utcdate_new_validated_bad_secfrac_fails() {
883 for s in [
884 "2014-10-30T06:12:00.Z",
885 "2014-10-30T06:12:00.0Z",
886 "2014-10-30T06:12:00.00000Z",
887 "2014-10-30T06:12:00.12aZ",
888 "2014-10-30T06:12:00.123",
889 "2014-10-30T06:12:00.123z",
890 "2014-10-30T06:12:00Z0",
891 ] {
892 let err = UTCDate::new_validated(s).unwrap_err();
893 assert!(err.to_string().contains("wrong structure"), "{s}: {err}");
894 }
895 }
896
897 /// Oracle: 2014-10-30T06:12:00Z is 1_414_649_520 (RFC 8620 §1.4
898 /// example, GNU `date -u -d 2014-10-30T06:12:00Z +%s`); a sub-second
899 /// fraction does not move it to the next second.
900 #[test]
901 fn utcdate_to_epoch_seconds_truncates_secfrac() {
902 let d = UTCDate::new_validated("2014-10-30T06:12:00.999Z").unwrap();
903 assert_eq!(d.to_epoch_seconds().unwrap(), 1_414_649_520);
904 }
905
906 /// Oracle: non-digit in year position fails.
907 #[test]
908 fn utcdate_new_validated_non_digit_fails() {
909 assert!(UTCDate::new_validated("XXXX-10-30T06:12:00Z").is_err());
910 }
911
912 /// Oracle: RFC 8620 §1.4 — month out of range MUST be rejected.
913 /// Pre-tightening, `validate_utcdate` was shape-only and would
914 /// accept this. bd:JMAP-6xs8.20 added semantic validation.
915 #[test]
916 fn utcdate_new_validated_rejects_month_out_of_range() {
917 let err = UTCDate::new_validated("2024-13-15T09:00:00Z").unwrap_err();
918 assert!(err.0.contains("month must be"), "{err}");
919 let err = UTCDate::new_validated("9999-99-99T09:00:00Z").unwrap_err();
920 assert!(err.0.contains("month must be"), "{err}");
921 }
922
923 /// Oracle: RFC 8620 §1.4 — day out of range MUST be rejected
924 /// including non-existent dates (Feb 30) and Feb 29 in non-leap
925 /// years. bd:JMAP-6xs8.20.
926 #[test]
927 fn utcdate_new_validated_rejects_day_out_of_range() {
928 // Day 32 in January
929 let err = UTCDate::new_validated("2024-01-32T09:00:00Z").unwrap_err();
930 assert!(err.0.contains("day must be"), "{err}");
931 // Feb 30 never exists
932 let err = UTCDate::new_validated("2024-02-30T09:00:00Z").unwrap_err();
933 assert!(err.0.contains("day must be"), "{err}");
934 // Feb 29 in non-leap year 2023 (not divisible by 4)
935 let err = UTCDate::new_validated("2023-02-29T09:00:00Z").unwrap_err();
936 assert!(err.0.contains("day must be"), "{err}");
937 // April 31 (April has 30 days)
938 let err = UTCDate::new_validated("2024-04-31T09:00:00Z").unwrap_err();
939 assert!(err.0.contains("day must be"), "{err}");
940 }
941
942 /// Oracle: RFC 8620 §1.4 — Feb 29 in a leap year MUST be accepted.
943 /// Pins the leap-year branch of the day-range check (2024 is
944 /// divisible by 4, not by 100, so leap). bd:JMAP-6xs8.20.
945 #[test]
946 fn utcdate_new_validated_accepts_feb_29_leap_year() {
947 UTCDate::new_validated("2024-02-29T00:00:00Z").expect("leap day must succeed");
948 }
949
950 /// Oracle: RFC 8620 §1.4 — time-component out of range MUST be
951 /// rejected. Includes hour 24, minute 60, second 60 (no leap
952 /// seconds per §1.4 even though RFC 3339 §5.6 permits them).
953 /// bd:JMAP-6xs8.20.
954 #[test]
955 fn utcdate_new_validated_rejects_time_out_of_range() {
956 let err = UTCDate::new_validated("2024-06-15T24:00:00Z").unwrap_err();
957 assert!(err.0.contains("hour must be"), "{err}");
958 let err = UTCDate::new_validated("2024-06-15T09:60:00Z").unwrap_err();
959 assert!(err.0.contains("minute must be"), "{err}");
960 let err = UTCDate::new_validated("2024-06-15T09:00:60Z").unwrap_err();
961 assert!(err.0.contains("second must be"), "{err}");
962 }
963
964 /// Oracle: the absurd case from the bd:JMAP-6xs8.20 bead body
965 /// (`9999-99-99T99:99:99Z`) MUST be rejected. Pinned here so a
966 /// future contributor can't accidentally regress to the old
967 /// shape-only validator.
968 #[test]
969 fn utcdate_new_validated_rejects_absurd_values() {
970 let err = UTCDate::new_validated("9999-99-99T99:99:99Z").unwrap_err();
971 assert!(
972 err.0.contains("month must be"),
973 "first rejected component (in left-to-right order) is the \
974 month; got: {err}"
975 );
976 }
977
978 /// Oracle: RFC 8620 §1.2 — State must be non-empty.
979 #[test]
980 fn state_new_validated_empty_fails() {
981 let err = State::new_validated("").unwrap_err();
982 assert!(err.0.contains("empty"), "{err}");
983 }
984
985 /// Oracle: non-empty State string succeeds.
986 #[test]
987 fn state_new_validated_valid_succeeds() {
988 let s = State::new_validated("75128aab4b1b").expect("valid State must succeed");
989 assert_eq!(s.as_ref(), "75128aab4b1b");
990 }
991
992 /// Oracle: ValidationError implements std::error::Error and Display.
993 #[test]
994 fn validation_error_implements_error() {
995 let e = Id::new_validated("").unwrap_err();
996 let _: &dyn std::error::Error = &e;
997 assert!(!e.to_string().is_empty(), "error message must not be empty");
998 assert_eq!(format!("{e}"), e.0, "Display must show the inner message");
999 }
1000
1001 // -----------------------------------------------------------------------
1002 // UTCDate::to_epoch_seconds tests
1003 //
1004 // Oracle for all numeric vectors: Python 3 `datetime.datetime(...).
1005 // replace(tzinfo=timezone.utc).timestamp()`, computed independently and
1006 // hardcoded as integer literals per workspace AGENTS.md "Test vector
1007 // discipline". The oracle is independent of the code under test — these
1008 // are NOT round-trip self-tests.
1009 // -----------------------------------------------------------------------
1010
1011 /// Oracle (Python): `1970-01-01T00:00:00Z` → 0.
1012 #[test]
1013 fn utcdate_to_epoch_seconds_unix_epoch() {
1014 let d = UTCDate::new_validated("1970-01-01T00:00:00Z").unwrap();
1015 assert_eq!(d.to_epoch_seconds().unwrap(), 0);
1016 }
1017
1018 /// Oracle (Python): RFC 8620 §1.4 example `2014-10-30T06:12:00Z` →
1019 /// 1_414_649_520.
1020 #[test]
1021 fn utcdate_to_epoch_seconds_rfc8620_example() {
1022 let d = UTCDate::new_validated("2014-10-30T06:12:00Z").unwrap();
1023 assert_eq!(d.to_epoch_seconds().unwrap(), 1_414_649_520);
1024 }
1025
1026 /// Oracle (Python): `2000-01-01T00:00:00Z` (Y2K, century-leap year) →
1027 /// 946_684_800.
1028 #[test]
1029 fn utcdate_to_epoch_seconds_y2k() {
1030 let d = UTCDate::new_validated("2000-01-01T00:00:00Z").unwrap();
1031 assert_eq!(d.to_epoch_seconds().unwrap(), 946_684_800);
1032 }
1033
1034 /// Oracle (Python): `1999-12-31T23:59:59Z` (one second before Y2K) →
1035 /// 946_684_799.
1036 #[test]
1037 fn utcdate_to_epoch_seconds_pre_y2k() {
1038 let d = UTCDate::new_validated("1999-12-31T23:59:59Z").unwrap();
1039 assert_eq!(d.to_epoch_seconds().unwrap(), 946_684_799);
1040 }
1041
1042 /// Oracle (Python): `2024-02-29T00:00:00Z` (leap year, leap day start) →
1043 /// 1_709_164_800.
1044 #[test]
1045 fn utcdate_to_epoch_seconds_leap_day_2024() {
1046 let d = UTCDate::new_validated("2024-02-29T00:00:00Z").unwrap();
1047 assert_eq!(d.to_epoch_seconds().unwrap(), 1_709_164_800);
1048 }
1049
1050 /// Oracle (Python): `2024-02-29T23:59:59Z` (leap day end) →
1051 /// 1_709_251_199.
1052 #[test]
1053 fn utcdate_to_epoch_seconds_leap_day_2024_end() {
1054 let d = UTCDate::new_validated("2024-02-29T23:59:59Z").unwrap();
1055 assert_eq!(d.to_epoch_seconds().unwrap(), 1_709_251_199);
1056 }
1057
1058 /// Oracle (Python): `2100-03-01T00:00:00Z` exercises the
1059 /// century-non-leap-year rule (2100 is not a leap year, divisible by 100
1060 /// but not 400).
1061 #[test]
1062 fn utcdate_to_epoch_seconds_2100_non_leap_century() {
1063 let d = UTCDate::new_validated("2100-03-01T00:00:00Z").unwrap();
1064 assert_eq!(d.to_epoch_seconds().unwrap(), 4_107_542_400);
1065 }
1066
1067 /// Oracle (Python): `1969-12-31T23:59:59Z` (one second before epoch) → -1.
1068 /// Verifies negative-epoch handling.
1069 #[test]
1070 fn utcdate_to_epoch_seconds_one_before_epoch() {
1071 let d = UTCDate::new_validated("1969-12-31T23:59:59Z").unwrap();
1072 assert_eq!(d.to_epoch_seconds().unwrap(), -1);
1073 }
1074
1075 /// Oracle (Python): `1900-01-01T00:00:00Z` → -2_208_988_800.
1076 /// 1900 is divisible by 100 but not 400, so NOT a leap year — exercises
1077 /// the same century rule as 2100 but well before the epoch.
1078 #[test]
1079 fn utcdate_to_epoch_seconds_1900() {
1080 let d = UTCDate::new_validated("1900-01-01T00:00:00Z").unwrap();
1081 assert_eq!(d.to_epoch_seconds().unwrap(), -2_208_988_800);
1082 }
1083
1084 /// Oracle (Python): `0001-01-01T00:00:00Z` → -62_135_596_800.
1085 /// Far-past boundary; verifies the proleptic Gregorian algorithm
1086 /// extrapolates correctly to year 1.
1087 #[test]
1088 fn utcdate_to_epoch_seconds_year_one() {
1089 let d = UTCDate::new_validated("0001-01-01T00:00:00Z").unwrap();
1090 assert_eq!(d.to_epoch_seconds().unwrap(), -62_135_596_800);
1091 }
1092
1093 /// Oracle (Python): `9999-12-31T23:59:59Z` (UTCDate max year) →
1094 /// 253_402_300_799.
1095 /// Far-future boundary within `i64` range.
1096 #[test]
1097 fn utcdate_to_epoch_seconds_year_9999() {
1098 let d = UTCDate::new_validated("9999-12-31T23:59:59Z").unwrap();
1099 assert_eq!(d.to_epoch_seconds().unwrap(), 253_402_300_799);
1100 }
1101
1102 /// Oracle (Python): `2038-01-19T03:14:07Z` = i32::MAX = 2_147_483_647
1103 /// (the "Year 2038 problem" boundary).
1104 #[test]
1105 fn utcdate_to_epoch_seconds_y2038_boundary() {
1106 let d = UTCDate::new_validated("2038-01-19T03:14:07Z").unwrap();
1107 assert_eq!(d.to_epoch_seconds().unwrap(), 2_147_483_647);
1108 }
1109
1110 /// Oracle (Python): `2038-01-19T03:14:08Z` = i32::MAX + 1.
1111 /// Verifies `i64` handles the i32 overflow point that 32-bit time_t
1112 /// implementations would wrap at.
1113 #[test]
1114 fn utcdate_to_epoch_seconds_post_y2038() {
1115 let d = UTCDate::new_validated("2038-01-19T03:14:08Z").unwrap();
1116 assert_eq!(d.to_epoch_seconds().unwrap(), 2_147_483_648);
1117 }
1118
1119 /// Oracle: `validate_utcdate` accepts month 13 structurally; semantic
1120 /// validation in `to_epoch_seconds` must reject it.
1121 #[test]
1122 fn utcdate_to_epoch_seconds_rejects_month_13() {
1123 let d = UTCDate::from("2024-13-01T00:00:00Z");
1124 let err = d.to_epoch_seconds().unwrap_err();
1125 assert!(err.0.contains("month"), "error must mention month: {err}");
1126 }
1127
1128 /// Oracle: `validate_utcdate` accepts day 32 structurally; semantic
1129 /// validation in `to_epoch_seconds` must reject it.
1130 #[test]
1131 fn utcdate_to_epoch_seconds_rejects_day_32() {
1132 let d = UTCDate::from("2024-01-32T00:00:00Z");
1133 let err = d.to_epoch_seconds().unwrap_err();
1134 assert!(err.0.contains("day"), "error must mention day: {err}");
1135 }
1136
1137 /// Oracle: 2023 is NOT a leap year; Feb 29 must be rejected as
1138 /// out-of-range for that month.
1139 #[test]
1140 fn utcdate_to_epoch_seconds_rejects_feb_29_non_leap() {
1141 let d = UTCDate::from("2023-02-29T00:00:00Z");
1142 let err = d.to_epoch_seconds().unwrap_err();
1143 assert!(err.0.contains("day"), "error must mention day: {err}");
1144 }
1145
1146 /// Oracle: hour 24 is out of range per RFC 8620 §1.4 (no end-of-day
1147 /// convention) — `to_epoch_seconds` must reject it.
1148 #[test]
1149 fn utcdate_to_epoch_seconds_rejects_hour_24() {
1150 let d = UTCDate::from("2024-01-01T24:00:00Z");
1151 let err = d.to_epoch_seconds().unwrap_err();
1152 assert!(err.0.contains("hour"), "error must mention hour: {err}");
1153 }
1154
1155 /// Oracle: minute 60 out of range.
1156 #[test]
1157 fn utcdate_to_epoch_seconds_rejects_minute_60() {
1158 let d = UTCDate::from("2024-01-01T00:60:00Z");
1159 let err = d.to_epoch_seconds().unwrap_err();
1160 assert!(err.0.contains("minute"), "error must mention minute: {err}");
1161 }
1162
1163 /// Oracle: second 60 (leap second) is not permitted by RFC 8620 §1.4 —
1164 /// `to_epoch_seconds` must reject it.
1165 #[test]
1166 fn utcdate_to_epoch_seconds_rejects_leap_second() {
1167 let d = UTCDate::from("2016-12-31T23:59:60Z");
1168 let err = d.to_epoch_seconds().unwrap_err();
1169 assert!(err.0.contains("second"), "error must mention second: {err}");
1170 }
1171
1172 /// Oracle: a value constructed via `UTCDate::from` with wrong structure
1173 /// must surface a structural ValidationError (re-validation in
1174 /// `to_epoch_seconds`).
1175 #[test]
1176 fn utcdate_to_epoch_seconds_rejects_invalid_structure() {
1177 let d = UTCDate::from("not-a-date");
1178 assert!(d.to_epoch_seconds().is_err());
1179 }
1180
1181 /// Oracle (Python): `2024-02-28T23:59:59Z` → `2024-02-29T00:00:00Z` is
1182 /// exactly one second forward. Verifies leap-day arithmetic is
1183 /// internally consistent.
1184 #[test]
1185 fn utcdate_to_epoch_seconds_leap_day_boundary_one_sec() {
1186 let a = UTCDate::new_validated("2024-02-28T23:59:59Z").unwrap();
1187 let b = UTCDate::new_validated("2024-02-29T00:00:00Z").unwrap();
1188 let diff = b.to_epoch_seconds().unwrap() - a.to_epoch_seconds().unwrap();
1189 assert_eq!(
1190 diff, 1,
1191 "Feb 28 23:59:59 → Feb 29 00:00:00 must be 1 second"
1192 );
1193 }
1194
1195 /// Oracle (Python): a 365-day duration `2023-01-01T00:00:00Z` to
1196 /// `2024-01-01T00:00:00Z` is exactly `365 * 86_400 = 31_536_000` seconds
1197 /// (2023 is not a leap year). Anchors the `CalendarsLimits::default()
1198 /// .max_expanded_query_duration_seconds` value (`31_536_000`).
1199 #[test]
1200 fn utcdate_to_epoch_seconds_365_day_year_duration() {
1201 let a = UTCDate::new_validated("2023-01-01T00:00:00Z").unwrap();
1202 let b = UTCDate::new_validated("2024-01-01T00:00:00Z").unwrap();
1203 let diff = b.to_epoch_seconds().unwrap() - a.to_epoch_seconds().unwrap();
1204 assert_eq!(diff, 31_536_000);
1205 }
1206
1207 /// Oracle (Python): a 366-day duration `2024-01-01T00:00:00Z` to
1208 /// `2025-01-01T00:00:00Z` is `366 * 86_400 = 31_622_400` seconds (2024 is
1209 /// a leap year).
1210 #[test]
1211 fn utcdate_to_epoch_seconds_366_day_leap_year_duration() {
1212 let a = UTCDate::new_validated("2024-01-01T00:00:00Z").unwrap();
1213 let b = UTCDate::new_validated("2025-01-01T00:00:00Z").unwrap();
1214 let diff = b.to_epoch_seconds().unwrap() - a.to_epoch_seconds().unwrap();
1215 assert_eq!(diff, 31_622_400);
1216 }
1217}