Skip to main content

fiscalclock/
date.rs

1use core::fmt;
2use core::str::FromStr;
3
4/// A proleptic Gregorian civil date in the years 0001 to 9999.
5///
6/// Stored as a day number, so comparison, ordering and differences are cheap.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
8pub struct Date(i32);
9
10/// A day of the week.
11#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub enum Weekday {
13    /// Monday.
14    Monday,
15    /// Tuesday.
16    Tuesday,
17    /// Wednesday.
18    Wednesday,
19    /// Thursday.
20    Thursday,
21    /// Friday.
22    Friday,
23    /// Saturday.
24    Saturday,
25    /// Sunday.
26    Sunday,
27}
28
29/// The error returned when a string is not a strict `YYYY-MM-DD` date in 0001–9999.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub struct ParseDateError;
32
33impl fmt::Display for ParseDateError {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        f.write_str("not a YYYY-MM-DD civil date in the years 0001-9999")
36    }
37}
38
39impl core::error::Error for ParseDateError {}
40
41const WEEKDAYS: [Weekday; 7] = [
42    Weekday::Monday,
43    Weekday::Tuesday,
44    Weekday::Wednesday,
45    Weekday::Thursday,
46    Weekday::Friday,
47    Weekday::Saturday,
48    Weekday::Sunday,
49];
50
51const MONTH_NAMES: [&str; 12] = [
52    "January",
53    "February",
54    "March",
55    "April",
56    "May",
57    "June",
58    "July",
59    "August",
60    "September",
61    "October",
62    "November",
63    "December",
64];
65
66impl Weekday {
67    /// Days since Monday: 0 for Monday up to 6 for Sunday.
68    pub const fn index(self) -> u32 {
69        self as u32
70    }
71
72    pub(crate) fn from_index(i: u32) -> Weekday {
73        WEEKDAYS[(i % 7) as usize]
74    }
75
76    /// The lower-case English name used in definitions, such as `"monday"`.
77    pub const fn name(self) -> &'static str {
78        match self {
79            Weekday::Monday => "monday",
80            Weekday::Tuesday => "tuesday",
81            Weekday::Wednesday => "wednesday",
82            Weekday::Thursday => "thursday",
83            Weekday::Friday => "friday",
84            Weekday::Saturday => "saturday",
85            Weekday::Sunday => "sunday",
86        }
87    }
88
89    pub(crate) fn title(self) -> &'static str {
90        match self {
91            Weekday::Monday => "Monday",
92            Weekday::Tuesday => "Tuesday",
93            Weekday::Wednesday => "Wednesday",
94            Weekday::Thursday => "Thursday",
95            Weekday::Friday => "Friday",
96            Weekday::Saturday => "Saturday",
97            Weekday::Sunday => "Sunday",
98        }
99    }
100
101    pub(crate) fn from_name(s: &str) -> Option<Weekday> {
102        WEEKDAYS.iter().copied().find(|w| w.name() == s)
103    }
104
105    /// The weekday `n` days later.
106    pub(crate) fn plus(self, n: i32) -> Weekday {
107        Weekday::from_index((self.index() as i32 + n).rem_euclid(7) as u32)
108    }
109}
110
111pub(crate) fn month_name(month: u32) -> &'static str {
112    MONTH_NAMES[(month - 1) as usize]
113}
114
115pub(crate) const fn is_leap(year: i32) -> bool {
116    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
117}
118
119pub(crate) const fn days_in_month(year: i32, month: u32) -> u32 {
120    match month {
121        2 if is_leap(year) => 29,
122        2 => 28,
123        4 | 6 | 9 | 11 => 30,
124        _ => 31,
125    }
126}
127
128// Howard Hinnant's days_from_civil; day 0 is 1970-01-01. Valid for any year
129// whose day number fits i32, which internal boundary arithmetic relies on for
130// years 0 and 10000.
131const fn days_from_civil(year: i32, month: u32, day: u32) -> i32 {
132    let y = if month <= 2 { year - 1 } else { year };
133    let era = if y >= 0 { y } else { y - 399 } / 400;
134    let yoe = (y - era * 400) as u32;
135    let mp = (month + 9) % 12;
136    let doy = (153 * mp + 2) / 5 + day - 1;
137    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
138    era * 146_097 + doe as i32 - 719_468
139}
140
141const fn civil_from_days(days: i32) -> (i32, u32, u32) {
142    let z = days + 719_468;
143    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
144    let doe = (z - era * 146_097) as u32;
145    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
146    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
147    let mp = (5 * doy + 2) / 153;
148    let day = doy - (153 * mp + 2) / 5 + 1;
149    let month = if mp < 10 { mp + 3 } else { mp - 9 };
150    let year = yoe as i32 + era * 400 + if month <= 2 { 1 } else { 0 };
151    (year, month, day)
152}
153
154impl Date {
155    /// The earliest representable date, 0001-01-01.
156    pub const MIN: Date = Date(days_from_civil(1, 1, 1));
157    /// The latest representable date, 9999-12-31.
158    pub const MAX: Date = Date(days_from_civil(9999, 12, 31));
159
160    /// Builds a date from a year, month and day, or `None` if it does not exist
161    /// or lies outside 0001-01-01 to 9999-12-31.
162    pub fn from_ymd(year: i32, month: u32, day: u32) -> Option<Date> {
163        if !(1..=9999).contains(&year)
164            || !(1..=12).contains(&month)
165            || day == 0
166            || day > days_in_month(year, month)
167        {
168            return None;
169        }
170        Some(Date(days_from_civil(year, month, day)))
171    }
172
173    /// Parses exactly `YYYY-MM-DD` with a year from 0001 to 9999. Anything else,
174    /// including a time or zone suffix, is rejected.
175    pub fn parse_iso(s: &str) -> Option<Date> {
176        let b = s.as_bytes();
177        if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
178            return None;
179        }
180        let num = |range: core::ops::Range<usize>| -> Option<u32> {
181            b[range].iter().try_fold(0u32, |acc, &c| {
182                c.is_ascii_digit().then(|| acc * 10 + u32::from(c - b'0'))
183            })
184        };
185        Date::from_ymd(num(0..4)? as i32, num(5..7)?, num(8..10)?)
186    }
187
188    /// Internal constructor for any year, used where boundary arithmetic needs
189    /// years just outside the public range. `month` and `day` must be valid.
190    pub(crate) const fn civil(year: i32, month: u32, day: u32) -> Date {
191        Date(days_from_civil(year, month, day))
192    }
193
194    /// The year, month and day.
195    pub const fn ymd(self) -> (i32, u32, u32) {
196        civil_from_days(self.0)
197    }
198
199    /// The calendar year.
200    pub const fn year(self) -> i32 {
201        self.ymd().0
202    }
203
204    /// The month, 1 to 12.
205    pub const fn month(self) -> u32 {
206        self.ymd().1
207    }
208
209    /// The day of the month, 1 to 31.
210    pub const fn day(self) -> u32 {
211        self.ymd().2
212    }
213
214    /// The day of the week.
215    pub fn weekday(self) -> Weekday {
216        // 1970-01-01 was a Thursday.
217        Weekday::from_index((self.0 + 3).rem_euclid(7) as u32)
218    }
219
220    /// The date `days` days later (earlier when negative), or `None` outside
221    /// the representable range.
222    pub fn checked_add_days(self, days: i64) -> Option<Date> {
223        let d = i64::from(self.0).checked_add(days)?;
224        let date = Date(i32::try_from(d).ok()?);
225        (Date::MIN..=Date::MAX).contains(&date).then_some(date)
226    }
227
228    /// The number of days from `self` to `later`; negative when `later` is earlier.
229    pub const fn days_until(self, later: Date) -> i32 {
230        later.0 - self.0
231    }
232
233    pub(crate) const fn add(self, days: i32) -> Date {
234        Date(self.0 + days)
235    }
236}
237
238impl fmt::Display for Date {
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        let (y, m, d) = self.ymd();
241        write!(f, "{y:04}-{m:02}-{d:02}")
242    }
243}
244
245impl FromStr for Date {
246    type Err = ParseDateError;
247
248    fn from_str(s: &str) -> Result<Date, ParseDateError> {
249        Date::parse_iso(s).ok_or(ParseDateError)
250    }
251}