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