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    /// The day `days` after 1970-01-01 (before it, negative), in UTC;
45    /// `None` outside years 1 to 9999. Howard Hinnant's civil-from-days.
46    pub fn from_unix_days(days: i64) -> Option<Self> {
47        let z = days + 719_468;
48        let era = z.div_euclid(146_097);
49        let doe = z.rem_euclid(146_097);
50        let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
51        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
52        let mp = (5 * doy + 2) / 153;
53        let day = doy - (153 * mp + 2) / 5 + 1;
54        let month = if mp < 10 { mp + 3 } else { mp - 9 };
55        let year = yoe + era * 400 + i64::from(month <= 2);
56        Self::new(u16::try_from(year).ok()?, month as u8, day as u8)
57    }
58
59    /// The UTC day of Unix seconds `secs`.
60    pub fn of_unix(secs: i64) -> Option<Self> {
61        Self::from_unix_days(secs.div_euclid(86_400))
62    }
63}
64
65fn days_in(year: u16, month: u8) -> u8 {
66    let leap = year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400));
67    match month {
68        2 if leap => 29,
69        2 => 28,
70        4 | 6 | 9 | 11 => 30,
71        _ => 31,
72    }
73}
74
75impl fmt::Display for CalendarDate {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
78    }
79}
80
81impl FromStr for CalendarDate {
82    type Err = DateError;
83
84    fn from_str(s: &str) -> Result<Self, DateError> {
85        let error = || DateError(s.to_owned());
86        // Exactly four, two and two digits: `2019-5-7` is not one, so
87        // there is one spelling of each day.
88        let mut parts = s.split('-');
89        let mut part = |width: usize| {
90            parts
91                .next()
92                .filter(|p| p.len() == width && p.bytes().all(|b| b.is_ascii_digit()))
93                .ok_or_else(error)
94        };
95        let (year, month, day) = (part(4)?, part(2)?, part(2)?);
96        if parts.next().is_some() {
97            return Err(error());
98        }
99        // At most four digits each, so every parse fits; `new` checks the
100        // ranges.
101        match (year.parse(), month.parse(), day.parse()) {
102            (Ok(year), Ok(month), Ok(day)) => Self::new(year, month, day).ok_or_else(error),
103            _ => Err(error()),
104        }
105    }
106}
107
108impl Serialize for CalendarDate {
109    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
110        serializer.collect_str(self)
111    }
112}
113
114impl<'de> Deserialize<'de> for CalendarDate {
115    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
116        let s = String::deserialize(deserializer)?;
117        s.parse().map_err(serde::de::Error::custom)
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn unix_days_are_the_utc_calendar_day() {
127        let days = [0, 19_782, -1, 11_016].map(CalendarDate::from_unix_days);
128        let expected = [(1970, 1, 1), (2024, 2, 29), (1969, 12, 31), (2000, 2, 29)]
129            .map(|(y, m, d)| CalendarDate::new(y, m, d));
130        assert_eq!(days, expected);
131    }
132
133    #[test]
134    fn a_date_is_a_yyyy_mm_dd_string_on_the_wire() {
135        let date = CalendarDate::new(2019, 5, 7).unwrap();
136        let json = serde_json::to_value(date).unwrap();
137        assert_eq!(json, "2019-05-07");
138        assert_eq!(serde_json::from_value::<CalendarDate>(json).unwrap(), date);
139    }
140
141    #[test]
142    fn only_days_that_exist_parse() {
143        assert!("2024-02-29".parse::<CalendarDate>().is_ok());
144        for bad in [
145            "2023-02-29",
146            "1900-02-29",
147            "2019-13-01",
148            "2019-04-31",
149            "2019-00-10",
150            "0000-01-01",
151            "2019-5-7",
152            "2019-05-07T00:00:00Z",
153            "2019/05/07",
154            "+201-05-07",
155            "",
156        ] {
157            assert!(bad.parse::<CalendarDate>().is_err(), "{bad}");
158        }
159    }
160}