Skip to main content

fprint_fp3/
date.rs

1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Enrollment-date <-> GLib Julian-day conversion.
6//!
7//! libfprint stores the enrollment date as `g_date_get_julian()`: the proleptic-Gregorian
8//! day number where `0001-01-01` is Julian day **1**. An unset/invalid date is written as
9//! the `G_MININT32` sentinel. The arithmetic lives only here; the domain model
10//! ([`EnrollDate`]) stays a plain `(year, month, day)`.
11//!
12//! The calendar math is Howard Hinnant's branch-free `days_from_civil` /`civil_from_days`
13//! (a public-domain algorithm), anchored so that day 0 is `1970-01-01`. Adding
14//! [`EPOCH_OFFSET`] then shifts onto GLib's `0001-01-01 = 1` origin.
15//!
16//! ## The representable range
17//!
18//! [`EnrollDate`] holds an `i32` year, so it spans about 4.3 billion years; an FP3 Julian day
19//! is an `i32` count of *days*, so it spans about 11.7 million. **The domain model is therefore
20//! wider than the wire**, and [`to_julian`] is partial: a date outside
21//! `-5879610-06-23 ..= 5879611-07-11` has no FP3 encoding and yields
22//! [`Fp3Error::DateOutOfRange`]. Those two dates are the exact ends — they map to `i32::MIN + 1`
23//! and `i32::MAX`. `G_MININT32` is excluded rather than used: the wire spends it on "unset", so
24//! the one date that would land there is not representable either.
25//!
26//! The arithmetic is `i64` end to end, and only the final Julian day is narrowed to `i32`. The
27//! intermediate day count legitimately leaves `i32` for dates whose Julian day is still in range
28//! (the day count and the Julian day differ by [`EPOCH_OFFSET`]), so narrowing before the shift
29//! would reject — or silently wrap — dates that FP3 can hold.
30
31use fprint_core::EnrollDate;
32
33use crate::error::{Fp3Error, Result};
34
35/// GLib's "date unset" sentinel (`G_MININT32`), written when [`EnrollDate`] is absent.
36pub(crate) const G_MININT32: i32 = i32::MIN;
37
38/// Julian day of the Unix epoch (`1970-01-01`), i.e. the offset between Hinnant's
39/// epoch-relative day count and GLib's `0001-01-01 = 1` Julian day.
40const EPOCH_OFFSET: i64 = 719_163;
41
42/// Days from `1970-01-01` to `year-month-day` in the proleptic Gregorian calendar.
43///
44/// Howard Hinnant's `days_from_civil`: exact for the whole `i32` year range, valid for any
45/// `month` in `1..=12` and `day` in `1..=31`. Intermediate math is done in `i64` so no
46/// step can overflow before the (in-range) result is returned.
47fn days_from_civil(year: i32, month: u8, day: u8) -> i64 {
48    let y = year as i64 - if month <= 2 { 1 } else { 0 };
49    let era = if y >= 0 { y } else { y - 399 } / 400;
50    let yoe = y - era * 400; // [0, 399]
51    let m = month as i64;
52    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day as i64 - 1; // [0, 365]
53    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
54    era * 146097 + doe - 719468
55}
56
57/// Inverse of [`days_from_civil`]: an epoch-relative day count back to `(year, month, day)`.
58fn civil_from_days(z: i64) -> (i32, u8, u8) {
59    let z = z + 719468;
60    let era = if z >= 0 { z } else { z - 146096 } / 146097;
61    let doe = z - era * 146097; // [0, 146096]
62    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; // [0, 399]
63    let y = yoe + era * 400;
64    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
65    let mp = (5 * doy + 2) / 153; // [0, 11]
66    let day = (doy - (153 * mp + 2) / 5 + 1) as u8; // [1, 31]
67    let month = (if mp < 10 { mp + 3 } else { mp - 9 }) as u8; // [1, 12]
68    let year = (y + if month <= 2 { 1 } else { 0 }) as i32;
69    (year, month, day)
70}
71
72/// Encode an [`EnrollDate`] as a GLib Julian day.
73///
74/// Partial, because [`EnrollDate`]'s `i32` year outranges the wire's `i32` day count: a date
75/// whose Julian day leaves `i32`, or lands exactly on the `G_MININT32` "unset" sentinel, has no
76/// FP3 encoding and gives [`Fp3Error::DateOutOfRange`]. Total over every `EnrollDate` value —
77/// including an unvalidated `month`/`day` — because the calendar math is `i64` and only the
78/// result is narrowed.
79pub(crate) fn to_julian(date: EnrollDate) -> Result<i32> {
80    let julian = days_from_civil(date.year, date.month, date.day) + EPOCH_OFFSET;
81    match i32::try_from(julian) {
82        Ok(j) if j != G_MININT32 => Ok(j),
83        _ => Err(Fp3Error::DateOutOfRange(date)),
84    }
85}
86
87/// Decode a GLib Julian day back into an [`EnrollDate`]. `G_MININT32` (the "unset"
88/// sentinel) yields `None`.
89pub(crate) fn from_julian(julian: i32) -> Option<EnrollDate> {
90    if julian == G_MININT32 {
91        return None;
92    }
93    let (year, month, day) = civil_from_days(i64::from(julian) - EPOCH_OFFSET);
94    Some(EnrollDate::new(year, month, day))
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    #[test]
102    fn anchors_match_glib() {
103        // GLib's g_date: 0001-01-01 is Julian day 1; the Unix epoch is 719163.
104        assert_eq!(to_julian(EnrollDate::new(1, 1, 1)).unwrap(), 1);
105        assert_eq!(to_julian(EnrollDate::new(1970, 1, 1)).unwrap(), 719_163);
106        // One modern date, cross-checked against a known g_date value.
107        assert_eq!(to_julian(EnrollDate::new(2026, 7, 15)).unwrap(), 739_812);
108    }
109
110    #[test]
111    fn date_conversion_roundtrips() {
112        let dates = [
113            EnrollDate::new(1, 1, 1),
114            EnrollDate::new(1970, 1, 1),
115            EnrollDate::new(2000, 2, 29), // leap day
116            EnrollDate::new(2026, 7, 15),
117            EnrollDate::new(2999, 12, 31),
118        ];
119        for d in dates {
120            assert_eq!(from_julian(to_julian(d).unwrap()), Some(d));
121        }
122    }
123
124    #[test]
125    fn sentinel_is_none_both_ways() {
126        assert_eq!(from_julian(G_MININT32), None);
127        assert_eq!(from_julian(i32::MIN), None);
128    }
129
130    /// The extreme Julian day a non-sentinel blob can carry, and the date it decodes to. Its
131    /// epoch-relative day count is `-2148202810`, which does **not** fit `i32` even though the
132    /// Julian day itself is exactly `i32::MIN + 1`, which does.
133    const EDGE_JULIAN: i32 = i32::MIN + 1;
134    fn edge_date() -> EnrollDate {
135        EnrollDate::new(-5_879_610, 6, 23)
136    }
137
138    /// **A date is encodable whenever its Julian day fits `i32`, not whenever its intermediate
139    /// day count does.** The two differ by [`EPOCH_OFFSET`], so narrowing the day count first
140    /// wraps this date's `-2148202810` to `2146764486` and overflows the shift.
141    #[test]
142    fn julian_at_the_i32_edge_is_not_truncated() {
143        let edge = edge_date();
144        assert_eq!(from_julian(EDGE_JULIAN), Some(edge));
145        assert_eq!(to_julian(edge).unwrap(), EDGE_JULIAN);
146        assert!(days_from_civil(edge.year, edge.month, edge.day) < i64::from(i32::MIN));
147    }
148
149    /// The domain model's `i32` year outranges the wire's `i32` day count by ~365x, so the ends
150    /// of the year range have no encoding. `EnrollDate.year` is public and unvalidated, so
151    /// `to_bytes` reaches this with no hostile bytes involved.
152    #[test]
153    fn dates_outside_the_julian_i32_range_are_rejected() {
154        for year in [i32::MIN, i32::MAX, -5_879_611, 5_879_612] {
155            let date = EnrollDate::new(year, 1, 1);
156            assert!(
157                matches!(to_julian(date), Err(Fp3Error::DateOutOfRange(d)) if d == date),
158                "year {year} must be rejected, not wrapped"
159            );
160        }
161    }
162
163    /// The wire spends `G_MININT32` on "unset", so the one date whose Julian day would land
164    /// there is unrepresentable — encoding it would decode back as `None`.
165    #[test]
166    fn the_date_colliding_with_the_unset_sentinel_is_rejected() {
167        // One day before the edge date is exactly `G_MININT32`.
168        let collides = EnrollDate::new(-5_879_610, 6, 22);
169        assert_eq!(
170            days_from_civil(collides.year, collides.month, collides.day) + EPOCH_OFFSET,
171            i64::from(G_MININT32)
172        );
173        assert!(matches!(
174            to_julian(collides),
175            Err(Fp3Error::DateOutOfRange(_))
176        ));
177    }
178
179    /// The representable range, to the day: `EDGE_DATE` maps to `i32::MIN + 1` and
180    /// `5879611-07-11` to `i32::MAX`, and the date on either side of those has no Julian day.
181    /// **The bound is exact, not approximate** — the docs quote these dates.
182    #[test]
183    fn the_representable_range_ends_exactly_here() {
184        let date = |year, month, day| EnrollDate::new(year, month, day);
185
186        assert_eq!(to_julian(edge_date()).unwrap(), i32::MIN + 1);
187        assert_eq!(to_julian(date(5_879_611, 7, 11)).unwrap(), i32::MAX);
188
189        // One day below is the sentinel; one day above overflows `i32`.
190        assert!(matches!(
191            to_julian(date(-5_879_610, 6, 22)),
192            Err(Fp3Error::DateOutOfRange(_))
193        ));
194        assert!(matches!(
195            to_julian(date(5_879_611, 7, 12)),
196            Err(Fp3Error::DateOutOfRange(_))
197        ));
198    }
199
200    /// `to_julian` never panics, for any `EnrollDate` value — including the unvalidated
201    /// `month`/`day` the public struct permits.
202    #[test]
203    fn to_julian_is_total_over_unvalidated_fields() {
204        for year in [i32::MIN, -1, 0, 1970, i32::MAX] {
205            for month in [0u8, 1, 12, 13, u8::MAX] {
206                for day in [0u8, 1, 31, 32, u8::MAX] {
207                    let _ = to_julian(EnrollDate::new(year, month, day));
208                }
209            }
210        }
211    }
212}