Skip to main content

kevy_time/
lib.rs

1//! Pure calendar arithmetic on epoch seconds — the date-arithmetic
2//! stone (R4a's last engine-side gap). Time columns stay declared
3//! i64 (epoch seconds; units belong to the caller, the WINDOW
4//! philosophy) — this crate is the query-side arithmetic that turns
5//! a human bound into that i64, never a new column type.
6//!
7//! Everything here is a pure function: `now` is always an argument,
8//! the stone never touches a clock. Proleptic Gregorian, UTC only
9//! (zone conversion is the application's — refused by name at the
10//! surface, not silently guessed here).
11//!
12//! The civil conversion is the standard integer-arithmetic algorithm
13//! (era/year-of-era/day-of-year decomposition over 400-year cycles),
14//! exact over the whole i64 day range the epoch can reach.
15//!
16//! ```
17//! use kevy_time::{Civil, add_months};
18//!
19//! // Epoch seconds in, calendar out, and back again.
20//! let c = Civil::from_epoch(1_700_000_000);
21//! assert_eq!((c.year(), c.month(), c.day()), (2023, 11, 14));
22//! assert_eq!((c.hour(), c.minute(), c.second()), (22, 13, 20));
23//! assert_eq!(c.to_epoch(), 1_700_000_000);
24//!
25//! // Month arithmetic clamps rather than spilling into the next month:
26//! // 31 January plus one month is the last day of February, and 2024 is
27//! // a leap year.
28//! let jan31 = Civil::from_date(2024, 1, 31).ok_or("not a date")?.to_epoch();
29//! let feb = Civil::from_epoch(add_months(jan31, 1));
30//! assert_eq!((feb.month(), feb.day()), (2, 29));
31//! # Ok::<(), &str>(())
32//! ```
33
34#![forbid(unsafe_code)]
35#![warn(missing_docs)]
36
37const SECS_PER_DAY: i64 = 86_400;
38
39/// One civil timestamp: year, month (1-12), day (1-31), hour,
40/// minute, second — UTC, proleptic Gregorian.
41///
42/// Always a real calendar instant that an `i64` epoch can hold: it is
43/// built from epoch seconds ([`Civil::from_epoch`]) or from fields that
44/// are checked ([`Civil::from_date`], [`Civil::with_time`]), so
45/// [`Civil::to_epoch`] cannot fail. Ordering is chronological.
46///
47/// # Examples
48///
49/// ```
50/// let c = kevy_time::Civil::from_epoch(0);
51/// assert_eq!((c.year(), c.month(), c.day()), (1970, 1, 1));
52/// assert_eq!((c.hour(), c.minute(), c.second()), (0, 0, 0));
53/// ```
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
55pub struct Civil {
56    y: i64,
57    m: u32,
58    d: u32,
59    h: u32,
60    min: u32,
61    s: u32,
62}
63
64/// Years past this are refused before any day arithmetic: 2^63 seconds
65/// is about 292 billion years, and the day count itself overflows for
66/// years far beyond that.
67const MAX_YEAR: i64 = 300_000_000_000;
68
69impl Civil {
70    /// Decode epoch seconds.
71    ///
72    /// ```
73    /// let c = kevy_time::Civil::from_epoch(0);
74    /// assert_eq!((c.year(), c.month(), c.day()), (1970, 1, 1));
75    /// assert_eq!((c.hour(), c.minute(), c.second()), (0, 0, 0));
76    /// ```
77    ///
78    /// Negative seconds run backwards through the epoch rather than
79    /// clamping at it.
80    ///
81    /// ```
82    /// let c = kevy_time::Civil::from_epoch(-1);
83    /// assert_eq!((c.year(), c.month(), c.day()), (1969, 12, 31));
84    /// assert_eq!((c.hour(), c.minute(), c.second()), (23, 59, 59));
85    /// ```
86    #[must_use]
87    pub fn from_epoch(secs: i64) -> Self {
88        let days = secs.div_euclid(SECS_PER_DAY);
89        let rem = secs.rem_euclid(SECS_PER_DAY) as u32;
90        let (y, m, d) = civil_from_days(days);
91        Self { y, m, d, h: rem / 3600, min: rem / 60 % 60, s: rem % 60 }
92    }
93
94    /// Midnight at the start of a date, or `None` when the date is not
95    /// on the calendar (month 13, 30 February) or lies outside what an
96    /// `i64` epoch can hold.
97    ///
98    /// ```
99    /// use kevy_time::Civil;
100    /// assert_eq!(Civil::from_date(1970, 1, 1).map(Civil::to_epoch), Some(0));
101    /// assert_eq!(Civil::from_date(2024, 2, 29).map(Civil::day), Some(29));
102    /// assert_eq!(Civil::from_date(2023, 2, 29), None);
103    /// assert_eq!(Civil::from_date(2023, 13, 1), None);
104    /// assert_eq!(Civil::from_date(i64::MAX / 2, 1, 1), None);
105    /// ```
106    #[must_use]
107    pub fn from_date(y: i64, m: u32, d: u32) -> Option<Self> {
108        if !(1..=12).contains(&m) || d == 0 || d > last_day(y, m) {
109            return None;
110        }
111        Self { y, m, d, h: 0, min: 0, s: 0 }.checked()
112    }
113
114    /// The same date at another time of day, or `None` when the time is
115    /// not on the clock (hour 24, minute 60) or the instant lies outside
116    /// what an `i64` epoch can hold.
117    ///
118    /// ```
119    /// use kevy_time::Civil;
120    /// let c = Civil::from_date(1970, 1, 1).and_then(|c| c.with_time(0, 0, 1));
121    /// assert_eq!(c.map(Civil::to_epoch), Some(1));
122    /// assert_eq!(Civil::from_epoch(0).with_time(24, 0, 0), None);
123    /// ```
124    #[must_use]
125    pub fn with_time(self, h: u32, min: u32, s: u32) -> Option<Self> {
126        if h > 23 || min > 59 || s > 59 {
127            return None;
128        }
129        Self { h, min, s, ..self }.checked()
130    }
131
132    /// Encode to epoch seconds — the exact inverse of
133    /// [`Civil::from_epoch`].
134    ///
135    /// ```
136    /// use kevy_time::Civil;
137    /// for t in [0i64, 1, -1, 951_782_400, 1_700_000_000, -2_208_988_800, i64::MAX, i64::MIN] {
138    ///     assert_eq!(Civil::from_epoch(t).to_epoch(), t, "round trip at {t}");
139    /// }
140    /// ```
141    #[must_use]
142    pub fn to_epoch(self) -> i64 {
143        // exact: every constructor checked that the instant fits
144        self.wide_epoch() as i64
145    }
146
147    /// Year (proleptic Gregorian; negative epochs decode correctly).
148    ///
149    /// ```
150    /// assert_eq!(kevy_time::Civil::from_epoch(-1).year(), 1969);
151    /// ```
152    #[must_use]
153    pub fn year(self) -> i64 {
154        self.y
155    }
156
157    /// Month, 1-12.
158    ///
159    /// ```
160    /// assert_eq!(kevy_time::Civil::from_epoch(0).month(), 1);
161    /// ```
162    #[must_use]
163    pub fn month(self) -> u32 {
164        self.m
165    }
166
167    /// Day of month, 1-31.
168    ///
169    /// ```
170    /// assert_eq!(kevy_time::Civil::from_epoch(-1).day(), 31);
171    /// ```
172    #[must_use]
173    pub fn day(self) -> u32 {
174        self.d
175    }
176
177    /// Hour, 0-23.
178    ///
179    /// ```
180    /// assert_eq!(kevy_time::Civil::from_epoch(3600).hour(), 1);
181    /// ```
182    #[must_use]
183    pub fn hour(self) -> u32 {
184        self.h
185    }
186
187    /// Minute, 0-59.
188    ///
189    /// ```
190    /// assert_eq!(kevy_time::Civil::from_epoch(60).minute(), 1);
191    /// ```
192    #[must_use]
193    pub fn minute(self) -> u32 {
194        self.min
195    }
196
197    /// Second, 0-59.
198    ///
199    /// ```
200    /// assert_eq!(kevy_time::Civil::from_epoch(59).second(), 59);
201    /// ```
202    #[must_use]
203    pub fn second(self) -> u32 {
204        self.s
205    }
206
207    /// `self` when its instant fits an `i64` epoch. The fields are
208    /// already on the calendar; this is the range half of the invariant.
209    fn checked(self) -> Option<Self> {
210        if !(-MAX_YEAR..=MAX_YEAR).contains(&self.y) {
211            return None;
212        }
213        i64::try_from(self.wide_epoch()).ok()?;
214        Some(self)
215    }
216
217    /// Epoch seconds in `i128`: on the first day an `i64` epoch reaches,
218    /// midnight itself is before `i64::MIN`, so the sum has to be formed
219    /// wider than its result.
220    fn wide_epoch(self) -> i128 {
221        i128::from(days_from_civil(self.y, self.m, self.d)) * i128::from(SECS_PER_DAY)
222            + i128::from(self.h * 3600 + self.min * 60 + self.s)
223    }
224}
225
226/// Days since the epoch for a civil date.
227fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
228    let y = if m <= 2 { y - 1 } else { y };
229    let era = if y >= 0 { y } else { y - 399 } / 400;
230    let yoe = y - era * 400;
231    let mp = i64::from(if m > 2 { m - 3 } else { m + 9 });
232    let doy = (153 * mp + 2) / 5 + i64::from(d) - 1;
233    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
234    era * 146_097 + doe - 719_468
235}
236
237/// Civil date for days since the epoch.
238fn civil_from_days(z: i64) -> (i64, u32, u32) {
239    let z = z + 719_468;
240    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
241    let doe = z - era * 146_097;
242    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
243    let y = yoe + era * 400;
244    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
245    let mp = (5 * doy + 2) / 153;
246    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
247    let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
248    (if m <= 2 { y + 1 } else { y }, m, d)
249}
250
251/// The last day of a month (leap-aware).
252fn last_day(y: i64, m: u32) -> u32 {
253    match m {
254        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
255        4 | 6 | 9 | 11 => 30,
256        _ => {
257            if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) {
258                29
259            } else {
260                28
261            }
262        }
263    }
264}
265
266/// Add `n` calendar months (negative subtracts), clamping the day to
267/// the target month's end — Jan 31 + 1mo = Feb 28 (29 in a leap
268/// year), the convention every calendar API converges on.
269///
270/// # Examples
271///
272/// The clamp is the whole point — January 31 has no counterpart in
273/// February, and every calendar API converges on the month's end rather
274/// than spilling into March:
275///
276/// ```
277/// use kevy_time::{add_months, Civil};
278/// let jan31 = Civil::from_date(2023, 1, 31).ok_or("not a date")?.to_epoch();
279/// let feb = Civil::from_epoch(add_months(jan31, 1));
280/// assert_eq!((feb.year(), feb.month(), feb.day()), (2023, 2, 28));
281///
282/// let leap = Civil::from_date(2024, 1, 31).ok_or("not a date")?.to_epoch();
283/// let feb = Civil::from_epoch(add_months(leap, 1));
284/// assert_eq!((feb.year(), feb.month(), feb.day()), (2024, 2, 29));
285/// # Ok::<(), &str>(())
286/// ```
287///
288/// Because of that clamp, adding a month is **not** reversible by
289/// subtracting one:
290///
291/// ```
292/// use kevy_time::{add_months, Civil};
293/// let jan31 = Civil::from_date(2023, 1, 31).ok_or("not a date")?.to_epoch();
294/// let back = Civil::from_epoch(add_months(add_months(jan31, 1), -1));
295/// assert_eq!((back.month(), back.day()), (1, 28), "the day did not come back");
296/// # Ok::<(), &str>(())
297/// ```
298///
299/// Negative `n` walks backwards across a year boundary:
300///
301/// ```
302/// use kevy_time::{add_months, Civil};
303/// let mar = Civil::from_date(2024, 3, 15).ok_or("not a date")?.to_epoch();
304/// let c = Civil::from_epoch(add_months(mar, -4));
305/// assert_eq!((c.year(), c.month(), c.day()), (2023, 11, 15));
306/// # Ok::<(), &str>(())
307/// ```
308pub fn add_months(secs: i64, n: i64) -> i64 {
309    checked_add_months(secs, n).unwrap_or(if n < 0 { i64::MIN } else { i64::MAX })
310}
311
312/// [`add_months`], answering `None` instead of saturating when the result
313/// leaves the range an `i64` epoch can hold.
314///
315/// The arithmetic here is unbounded in `n`: the month count, the era
316/// split and the final multiply by seconds-per-day all overflow long
317/// before `n` does. Unchecked, `@now+9223372036854775807mo` panicked in
318/// debug and returned a 1969 timestamp in release, while the same
319/// expression written in days was correctly refused — five of the seven
320/// units in [`eval`] rejected overflow and two did not.
321///
322/// # Examples
323///
324/// ```
325/// use kevy_time::checked_add_months;
326/// assert_eq!(checked_add_months(0, 1), Some(2_678_400));  // 1970-02-01
327/// assert_eq!(checked_add_months(0, i64::MAX), None);
328/// assert_eq!(checked_add_months(0, i64::MIN), None);
329/// ```
330#[must_use]
331pub fn checked_add_months(secs: i64, n: i64) -> Option<i64> {
332    let c = Civil::from_epoch(secs);
333    let months = c.y.checked_mul(12)?.checked_add(i64::from(c.m) - 1)?.checked_add(n)?;
334    let (y, m) = (months.div_euclid(12), (months.rem_euclid(12) + 1) as u32);
335    let d = c.d.min(last_day(y, m));
336    Some(Civil { y, m, d, ..c }.checked()?.to_epoch())
337}
338
339/// Evaluate one `@` query-bound expression against the caller's
340/// `now`. `None` on anything malformed — the surface refuses by
341/// name, this stone never guesses.
342///
343/// Grammar: `@now`, `@now±<n><unit>` with unit s|m|h|d|w (plain
344/// second arithmetic) or mo|y (calendar months via [`add_months`]),
345/// `@YYYY-MM-DD` (midnight) and `@YYYY-MM-DDThh:mm:ss`.
346///
347/// # Examples
348///
349/// ```
350/// use kevy_time::eval;
351/// let now = 1_700_000_000;
352/// assert_eq!(eval(b"@now", now), Some(now));
353/// assert_eq!(eval(b"@now-1h", now), Some(now - 3600));
354/// assert_eq!(eval(b"@now+7d", now), Some(now + 7 * 86_400));
355/// assert_eq!(eval(b"@1970-01-01", now), Some(0));
356/// assert_eq!(eval(b"@1970-01-01T00:00:01", now), Some(1));
357/// ```
358///
359/// `mo` and `y` go through [`add_months`], so they carry its clamp rather
360/// than a fixed number of seconds:
361///
362/// ```
363/// use kevy_time::{eval, Civil};
364/// let jan31 = Civil::from_date(2023, 1, 31).ok_or("not a date")?.to_epoch();
365/// let c = Civil::from_epoch(eval(b"@now+1mo", jan31).ok_or("no bound")?);
366/// assert_eq!((c.month(), c.day()), (2, 28));
367/// # Ok::<(), &str>(())
368/// ```
369///
370/// Anything malformed is `None`. The stone never guesses — a caller that
371/// wants a default has to say so itself:
372///
373/// ```
374/// use kevy_time::eval;
375/// for bad in [&b"now"[..], b"@", b"@now+", b"@now+5", b"@now+5x", b"@1970-1-1", b"@tomorrow"] {
376///     assert_eq!(eval(bad, 0), None, "{:?} should not parse", core::str::from_utf8(bad));
377/// }
378/// ```
379pub fn eval(expr: &[u8], now: i64) -> Option<i64> {
380    let body = expr.strip_prefix(b"@")?;
381    if let Some(rest) = body.strip_prefix(b"now") {
382        if rest.is_empty() {
383            return Some(now);
384        }
385        let (sign, rest) = match rest.first()? {
386            b'+' => (1i64, &rest[1..]),
387            b'-' => (-1i64, &rest[1..]),
388            _ => return None,
389        };
390        let digits = rest.iter().take_while(|b| b.is_ascii_digit()).count();
391        if digits == 0 {
392            return None;
393        }
394        let n: i64 = std::str::from_utf8(&rest[..digits]).ok()?.parse().ok()?;
395        return match &rest[digits..] {
396            b"s" => now.checked_add(sign * n),
397            b"m" => now.checked_add(sign.checked_mul(n.checked_mul(60)?)?),
398            b"h" => now.checked_add(sign.checked_mul(n.checked_mul(3600)?)?),
399            b"d" => now.checked_add(sign.checked_mul(n.checked_mul(SECS_PER_DAY)?)?),
400            b"w" => now.checked_add(sign.checked_mul(n.checked_mul(7 * SECS_PER_DAY)?)?),
401            // Checked, like the five above it. These two were not, so
402            // the same expression was refused in days and silently wrong
403            // in months.
404            b"mo" => checked_add_months(now, sign.checked_mul(n)?),
405            b"y" => checked_add_months(now, sign.checked_mul(n.checked_mul(12)?)?),
406            _ => None,
407        };
408    }
409    parse_literal(body)
410}
411
412/// `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ss`, validated against the real
413/// calendar (a Feb 30 is a refusal, not a wraparound).
414fn parse_literal(b: &[u8]) -> Option<i64> {
415    let num = |s: &[u8]| -> Option<i64> {
416        (!s.is_empty() && s.iter().all(u8::is_ascii_digit))
417            .then(|| std::str::from_utf8(s).ok()?.parse().ok())
418            .flatten()
419    };
420    let (date, time) = match b.len() {
421        10 => (b, None),
422        19 => {
423            if b[10] != b'T' {
424                return None;
425            }
426            (&b[..10], Some(&b[11..]))
427        }
428        _ => return None,
429    };
430    if date[4] != b'-' || date[7] != b'-' {
431        return None;
432    }
433    let (y, m, d) = (num(&date[..4])?, num(&date[5..7])? as u32, num(&date[8..10])? as u32);
434    let (h, min, s) = match time {
435        None => (0, 0, 0),
436        Some(t) => {
437            if t[2] != b':' || t[5] != b':' {
438                return None;
439            }
440            (num(&t[..2])? as u32, num(&t[3..5])? as u32, num(&t[6..8])? as u32)
441        }
442    };
443    Some(Civil::from_date(y, m, d)?.with_time(h, min, s)?.to_epoch())
444}
445
446// Send and Sync are part of the public contract: a change that loses
447// either fails to compile here rather than in a caller.
448const _: () = {
449    const fn send_sync<T: Send + Sync>() {}
450    send_sync::<Civil>();
451};
452
453#[cfg(test)]
454#[path = "lib_tests.rs"]
455mod tests;