Skip to main content

spoolframe_types/
date.rs

1//! A day on the calendar, with no time and no zone: when an episode first
2//! aired. On the wire it is `"YYYY-MM-DD"`, so it reads the same in every
3//! time zone; a Unix time for a date shows the day before west of UTC.
4
5use std::fmt;
6use std::str::FromStr;
7
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9
10/// Why a string is not a `YYYY-MM-DD` date.
11#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
12#[error("{0:?} is not a YYYY-MM-DD date")]
13pub struct DateError(String);
14
15/// A day of the proleptic Gregorian calendar, years 1 to 9999.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct CalendarDate {
18    year: u16,
19    month: u8,
20    day: u8,
21}
22
23impl CalendarDate {
24    /// The date, if there is such a day.
25    pub fn new(year: u16, month: u8, day: u8) -> Option<Self> {
26        let valid = (1..=9999).contains(&year)
27            && (1..=12).contains(&month)
28            && (1..=days_in(year, month)).contains(&day);
29        valid.then_some(Self { year, month, day })
30    }
31
32    pub fn year(self) -> u16 {
33        self.year
34    }
35
36    pub fn month(self) -> u8 {
37        self.month
38    }
39
40    pub fn day(self) -> u8 {
41        self.day
42    }
43}
44
45fn days_in(year: u16, month: u8) -> u8 {
46    let leap = year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400));
47    match month {
48        2 if leap => 29,
49        2 => 28,
50        4 | 6 | 9 | 11 => 30,
51        _ => 31,
52    }
53}
54
55impl fmt::Display for CalendarDate {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
58    }
59}
60
61impl FromStr for CalendarDate {
62    type Err = DateError;
63
64    fn from_str(s: &str) -> Result<Self, DateError> {
65        let error = || DateError(s.to_owned());
66        // Exactly four, two and two digits: `2019-5-7` is not one, so
67        // there is one spelling of each day.
68        let mut parts = s.split('-');
69        let mut part = |width: usize| {
70            parts
71                .next()
72                .filter(|p| p.len() == width && p.bytes().all(|b| b.is_ascii_digit()))
73                .ok_or_else(error)
74        };
75        let (year, month, day) = (part(4)?, part(2)?, part(2)?);
76        if parts.next().is_some() {
77            return Err(error());
78        }
79        // At most four digits each, so every parse fits; `new` checks the
80        // ranges.
81        match (year.parse(), month.parse(), day.parse()) {
82            (Ok(year), Ok(month), Ok(day)) => Self::new(year, month, day).ok_or_else(error),
83            _ => Err(error()),
84        }
85    }
86}
87
88impl Serialize for CalendarDate {
89    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
90        serializer.collect_str(self)
91    }
92}
93
94impl<'de> Deserialize<'de> for CalendarDate {
95    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
96        let s = String::deserialize(deserializer)?;
97        s.parse().map_err(serde::de::Error::custom)
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    #[test]
106    fn a_date_is_a_yyyy_mm_dd_string_on_the_wire() {
107        let date = CalendarDate::new(2019, 5, 7).unwrap();
108        let json = serde_json::to_value(date).unwrap();
109        assert_eq!(json, "2019-05-07");
110        assert_eq!(serde_json::from_value::<CalendarDate>(json).unwrap(), date);
111    }
112
113    #[test]
114    fn only_days_that_exist_parse() {
115        assert!("2024-02-29".parse::<CalendarDate>().is_ok());
116        for bad in [
117            "2023-02-29",
118            "1900-02-29",
119            "2019-13-01",
120            "2019-04-31",
121            "2019-00-10",
122            "0000-01-01",
123            "2019-5-7",
124            "2019-05-07T00:00:00Z",
125            "2019/05/07",
126            "+201-05-07",
127            "",
128        ] {
129            assert!(bad.parse::<CalendarDate>().is_err(), "{bad}");
130        }
131    }
132}