Skip to main content

ic_db/
date.rs

1//! Bounded Gregorian date, adapted from frozen IcyDB 6d421e3.
2//! Serde carries the bounded day count since the Unix epoch.
3
4use std::fmt::{self, Debug, Display};
5
6/// A Gregorian calendar date, stored as days since the Unix epoch.
7#[derive(Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Serialize)]
8#[serde(transparent)]
9#[repr(transparent)]
10pub struct Date(i32);
11
12impl<'de> serde::Deserialize<'de> for Date {
13    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
14        Self::try_from_days_since_epoch(i32::deserialize(deserializer)?)
15            .ok_or_else(|| serde::de::Error::custom("date outside supported day range"))
16    }
17}
18
19impl Date {
20    /// The Unix epoch date, 1970-01-01.
21    pub const EPOCH: Self = Self(0);
22    /// The earliest supported calendar date, 0000-01-01.
23    pub const MIN: Self = Self(-719_528);
24    /// The latest supported calendar date, 9999-12-31.
25    pub const MAX: Self = Self(2_932_896);
26
27    // March-based Gregorian cycles put the leap day at the end of a year.
28    // The cycle contains 400 * 365 + 97 days; 1970-01-01 is day 719468
29    // after 0000-03-01 in this calendar.
30    const DAYS_PER_CYCLE: i32 = 146_097;
31    const MARCH_EPOCH_OFFSET: i32 = 719_468;
32
33    /// Build a date from exact calendar parts.
34    ///
35    /// Returns `None` when any component is out of range.
36    #[must_use]
37    pub fn try_new(y: i32, m: u8, d: u8) -> Option<Self> {
38        if !(0..=9_999).contains(&y) {
39            return None;
40        }
41        let month_days = match m {
42            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
43            4 | 6 | 9 | 11 => 30,
44            2 if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) => 29,
45            2 => 28,
46            _ => return None,
47        };
48        if d == 0 || d > month_days {
49            return None;
50        }
51
52        let year = y - i32::from(m <= 2);
53        let cycle = year.div_euclid(400);
54        let cycle_year = year.rem_euclid(400);
55        let march_month = i32::from(m) + if m > 2 { -3 } else { 9 };
56        let cycle_day = 365 * cycle_year + cycle_year / 4 - cycle_year / 100
57            + (153 * march_month + 2) / 5
58            + i32::from(d)
59            - 1;
60
61        Self::try_from_days_since_epoch(
62            cycle * Self::DAYS_PER_CYCLE + cycle_day - Self::MARCH_EPOCH_OFFSET,
63        )
64    }
65
66    /// Construct from the bounded internal day-count representation.
67    #[must_use]
68    pub const fn try_from_days_since_epoch(days: i32) -> Option<Self> {
69        if days < Self::MIN.0 || days > Self::MAX.0 {
70            None
71        } else {
72            Some(Self(days))
73        }
74    }
75
76    /// Return the internal day-count representation.
77    #[must_use]
78    pub const fn as_days_since_epoch(self) -> i32 {
79        self.0
80    }
81
82    /// Fallible conversion from `i64` day-count representation.
83    #[must_use]
84    pub fn try_from_i64(days: i64) -> Option<Self> {
85        i32::try_from(days)
86            .ok()
87            .and_then(Self::try_from_days_since_epoch)
88    }
89
90    /// Fallible conversion from `u64` day-count representation.
91    #[must_use]
92    pub fn try_from_u64(days: u64) -> Option<Self> {
93        i32::try_from(days)
94            .ok()
95            .and_then(Self::try_from_days_since_epoch)
96    }
97
98    /// Add a signed number of days without leaving the supported calendar.
99    #[must_use]
100    pub fn checked_add_days(self, days: i64) -> Option<Self> {
101        i64::from(self.0)
102            .checked_add(days)
103            .and_then(Self::try_from_i64)
104    }
105
106    /// Subtract a signed number of days without leaving the supported calendar.
107    #[must_use]
108    pub fn checked_sub_days(self, days: i64) -> Option<Self> {
109        i64::from(self.0)
110            .checked_sub(days)
111            .and_then(Self::try_from_i64)
112    }
113
114    /// Return the signed number of days from `earlier` to this date.
115    #[must_use]
116    pub fn days_since(self, earlier: Self) -> i64 {
117        i64::from(self.0) - i64::from(earlier.0)
118    }
119
120    /// Returns the year component (e.g. 2025).
121    #[must_use]
122    pub fn year(self) -> i32 {
123        self.calendar_parts().0
124    }
125
126    /// Returns the month component (1-12).
127    #[must_use]
128    pub fn month(self) -> u8 {
129        self.calendar_parts().1
130    }
131
132    /// Returns the day-of-month component (1-31).
133    #[must_use]
134    pub fn day(self) -> u8 {
135        self.calendar_parts().2
136    }
137
138    /// Parse a strict ISO `YYYY-MM-DD` string into a `Date`.
139    #[must_use]
140    pub fn parse(s: &str) -> Option<Self> {
141        let bytes = s.as_bytes();
142        if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
143            return None;
144        }
145
146        // Decode one strict fixed-width payload before calendar admission.
147        let year = parse_ascii_i32(&bytes[0..4])?;
148        let month = parse_ascii_u8(&bytes[5..7])?;
149        let day = parse_ascii_u8(&bytes[8..10])?;
150
151        Self::try_new(year, month, day)
152    }
153
154    // Invert the March-based cycle used by try_new. Accepted epoch days keep
155    // all arithmetic in i32 and yield months 1..=12 and days 1..=31.
156    fn calendar_parts(self) -> (i32, u8, u8) {
157        let march_day = self.0 + Self::MARCH_EPOCH_OFFSET;
158        let cycle = march_day.div_euclid(Self::DAYS_PER_CYCLE);
159        let cycle_day = march_day.rem_euclid(Self::DAYS_PER_CYCLE);
160        let cycle_year =
161            (cycle_day - cycle_day / 1_460 + cycle_day / 36_524 - cycle_day / 146_096) / 365;
162        let year = cycle * 400 + cycle_year;
163        let march_ordinal = cycle_day - (365 * cycle_year + cycle_year / 4 - cycle_year / 100);
164        let march_month = (5 * march_ordinal + 2) / 153;
165        let day = march_ordinal - (153 * march_month + 2) / 5 + 1;
166        let month = march_month + if march_month < 10 { 3 } else { -9 };
167
168        (year + i32::from(month <= 2), month as u8, day as u8)
169    }
170}
171
172impl Debug for Date {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        write!(f, "Date({self})")
175    }
176}
177
178impl Display for Date {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        let (year, month, day) = self.calendar_parts();
181
182        write!(f, "{year:04}-{month:02}-{day:02}")
183    }
184}
185
186fn parse_ascii_i32(bytes: &[u8]) -> Option<i32> {
187    bytes.iter().try_fold(0_i32, |value, byte| {
188        byte.checked_sub(b'0')
189            .filter(|digit| *digit <= 9)
190            .and_then(|digit| value.checked_mul(10)?.checked_add(i32::from(digit)))
191    })
192}
193
194fn parse_ascii_u8(bytes: &[u8]) -> Option<u8> {
195    bytes.iter().try_fold(0_u8, |value, byte| {
196        byte.checked_sub(b'0')
197            .filter(|digit| *digit <= 9)
198            .and_then(|digit| value.checked_mul(10)?.checked_add(digit))
199    })
200}