Skip to main content

logicaffeine_base/
temporal.rs

1//! Exact calendar primitives — the bedrock of the time tower.
2//!
3//! Everything here is **exact integer arithmetic** over a single absolute coordinate: the day
4//! count since the Unix epoch (1970-01-01). Two calendars are projected onto that coordinate —
5//! the **proleptic Gregorian** calendar (the civil default) and the **proleptic Julian** calendar
6//! (for historical dates and the Gregorian/Julian divergence) — so a date in either calendar is
7//! just a different *lens* on the same day number, and converting between them is lossless.
8//!
9//! The Gregorian conversions are Howard Hinnant's branch-light `days_from_civil`/`civil_from_days`
10//! (valid for any year, no lookup tables). The Julian conversions go through the Julian Day Number
11//! (`JDN`); the epoch 1970-01-01 is `JDN 2440588`. ISO-8601 week dates are derived from the day
12//! number directly. Weekday is `0 = Sunday … 6 = Saturday`; ISO weekday is `1 = Monday … 7 = Sunday`.
13
14/// The Julian Day Number of the Unix epoch (1970-01-01, Gregorian).
15pub const UNIX_EPOCH_JDN: i64 = 2_440_588;
16
17/// The IERS leap-second table: `(year, month, day, TAI−UTC seconds)` — the cumulative offset that
18/// takes effect at 00:00:00 UTC of the listed date. SmoothUTC (this module's default) ignores leap
19/// seconds; this table is the bridge to atomic time (TAI), which has no leaps. Through 2017-01-01
20/// (the most recent leap second; none scheduled since — the leap second is being phased out by 2035).
21const LEAP_SECONDS: &[(i64, u32, u32, i64)] = &[
22    (1972, 1, 1, 10),
23    (1972, 7, 1, 11),
24    (1973, 1, 1, 12),
25    (1974, 1, 1, 13),
26    (1975, 1, 1, 14),
27    (1976, 1, 1, 15),
28    (1977, 1, 1, 16),
29    (1978, 1, 1, 17),
30    (1979, 1, 1, 18),
31    (1980, 1, 1, 19),
32    (1981, 7, 1, 20),
33    (1982, 7, 1, 21),
34    (1983, 7, 1, 22),
35    (1985, 7, 1, 23),
36    (1988, 1, 1, 24),
37    (1990, 1, 1, 25),
38    (1991, 1, 1, 26),
39    (1992, 7, 1, 27),
40    (1993, 7, 1, 28),
41    (1994, 7, 1, 29),
42    (1996, 1, 1, 30),
43    (1997, 7, 1, 31),
44    (1999, 1, 1, 32),
45    (2006, 1, 1, 33),
46    (2009, 1, 1, 34),
47    (2012, 7, 1, 35),
48    (2015, 7, 1, 36),
49    (2017, 1, 1, 37),
50];
51
52/// The fixed `TT − TAI` offset: Terrestrial Time runs 32.184 s ahead of atomic time, exactly.
53pub const TT_MINUS_TAI_NANOS: i64 = 32_184_000_000;
54
55/// `TAI − UTC` (whole seconds) in effect at a SmoothUTC/Unix instant — the count of leap seconds
56/// (plus the 1972 base of 10) inserted on/before it. Constant between leap seconds; `10` before 1972.
57pub fn tai_minus_utc(unix_seconds: i64) -> i64 {
58    let mut offset = LEAP_SECONDS[0].3; // pre-1972 floor (10)
59    for &(y, m, d, value) in LEAP_SECONDS {
60        let effective = days_from_civil(y, m, d) * SECONDS_PER_DAY;
61        if effective <= unix_seconds {
62            offset = value;
63        } else {
64            break;
65        }
66    }
67    offset
68}
69
70/// Convert a SmoothUTC/Unix instant in **nanoseconds** to **TAI** nanoseconds (leap-second exact).
71pub fn tai_nanos_from_unix_nanos(unix_ns: i64) -> i64 {
72    let secs = unix_ns.div_euclid(NANOS_PER_SECOND);
73    unix_ns + tai_minus_utc(secs) * NANOS_PER_SECOND
74}
75
76/// Convert a SmoothUTC/Unix instant in **nanoseconds** to **Terrestrial Time (TT)** nanoseconds:
77/// `TT = TAI + 32.184 s` — the continuous astronomical scale ephemerides are tabulated against.
78pub fn tt_nanos_from_unix_nanos(unix_ns: i64) -> i64 {
79    tai_nanos_from_unix_nanos(unix_ns) + TT_MINUS_TAI_NANOS
80}
81
82/// The inverse: **TT** nanoseconds back to a SmoothUTC/Unix instant in nanoseconds.
83pub fn unix_nanos_from_tt_nanos(tt_ns: i64) -> i64 {
84    let tai_ns = tt_ns - TT_MINUS_TAI_NANOS;
85    // Recover the UTC second to know which leap offset applies, then subtract it at nanosecond scale.
86    let unix_secs = tai_to_unix_seconds(tai_ns.div_euclid(NANOS_PER_SECOND));
87    tai_ns - tai_minus_utc(unix_secs) * NANOS_PER_SECOND
88}
89
90/// Convert a SmoothUTC/Unix instant (seconds) to **TAI** (atomic time) seconds: `TAI = UTC + (TAI−UTC)`.
91pub fn unix_to_tai_seconds(unix_seconds: i64) -> i64 {
92    unix_seconds + tai_minus_utc(unix_seconds)
93}
94
95/// The inverse: **TAI** seconds back to a SmoothUTC/Unix instant. The offset is monotone in UTC, so
96/// a first guess (`tai − offset(tai)`) corrected against `offset(guess)` converges in one step.
97pub fn tai_to_unix_seconds(tai_seconds: i64) -> i64 {
98    let mut unix = tai_seconds - tai_minus_utc(tai_seconds);
99    for _ in 0..2 {
100        unix = tai_seconds - tai_minus_utc(unix);
101    }
102    unix
103}
104
105/// A **Hybrid Logical Clock** timestamp: a physical instant (nanoseconds) plus a logical counter
106/// that breaks ties and preserves causality when the physical clock stalls, jumps backward, or two
107/// events share a nanosecond. The total order is lexicographic `(physical_nanos, logical)` — so the
108/// derived `Ord` *is* the HLC order. This is the causally-consistent timestamp the `SyncClock` CRDT
109/// keys on: it stays monotonic and orders happens-before correctly even across machines whose wall
110/// clocks disagree (the bounded-skew / interplanetary case the campaign targets).
111#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
112pub struct Hlc {
113    pub physical_nanos: i64,
114    pub logical: u32,
115}
116
117impl Hlc {
118    /// The zero timestamp (before any event).
119    pub const ZERO: Hlc = Hlc {
120        physical_nanos: 0,
121        logical: 0,
122    };
123
124    /// Stamp a **local event** (or a send) given the current physical clock `now_nanos`. Advances
125    /// the physical component to `max(self, now)`; the logical counter increments when physical
126    /// does not move (a stall or backward jump) and resets to 0 when it does.
127    pub fn tick(self, now_nanos: i64) -> Hlc {
128        let physical = self.physical_nanos.max(now_nanos);
129        let logical = if physical == self.physical_nanos {
130            self.logical + 1
131        } else {
132            0
133        };
134        Hlc {
135            physical_nanos: physical,
136            logical,
137        }
138    }
139
140    /// Stamp the **receipt** of a message carrying timestamp `remote`, at local physical clock
141    /// `now_nanos`. Merges both clocks plus wall time, keeping the result strictly after both
142    /// inputs (the HLC receive rule) so causality (`send → receive`) is always preserved.
143    pub fn recv(self, remote: Hlc, now_nanos: i64) -> Hlc {
144        let physical = self
145            .physical_nanos
146            .max(remote.physical_nanos)
147            .max(now_nanos);
148        let logical = if physical == self.physical_nanos && physical == remote.physical_nanos {
149            self.logical.max(remote.logical) + 1
150        } else if physical == self.physical_nanos {
151            self.logical + 1
152        } else if physical == remote.physical_nanos {
153            remote.logical + 1
154        } else {
155            0
156        };
157        Hlc {
158            physical_nanos: physical,
159            logical,
160        }
161    }
162}
163
164/// A bound on a remote node's current time: it lies somewhere in `[lower_nanos, upper_nanos]`. The
165/// width is the irreducible uncertainty — across a light-delay you can never pin a remote clock
166/// tighter than the physics allows. The `intersect` of two valid bounds is a lattice meet (it never
167/// widens), which is what makes a [`SyncClock`] conflict-free.
168#[derive(Clone, Copy, Debug, PartialEq, Eq)]
169pub struct EstimateInterval {
170    pub lower_nanos: i64,
171    pub upper_nanos: i64,
172}
173
174impl EstimateInterval {
175    pub fn new(lower_nanos: i64, upper_nanos: i64) -> Self {
176        EstimateInterval {
177            lower_nanos,
178            upper_nanos,
179        }
180    }
181    /// The uncertainty width (`upper − lower`).
182    pub fn width(&self) -> i64 {
183        self.upper_nanos - self.lower_nanos
184    }
185    pub fn contains(&self, t: i64) -> bool {
186        self.lower_nanos <= t && t <= self.upper_nanos
187    }
188    /// The tightest interval consistent with both — the meet. Commutative, associative, idempotent.
189    pub fn intersect(&self, other: &EstimateInterval) -> EstimateInterval {
190        EstimateInterval {
191            lower_nanos: self.lower_nanos.max(other.lower_nanos),
192            upper_nanos: self.upper_nanos.min(other.upper_nanos),
193        }
194    }
195}
196
197/// The freshest remote time you can possibly *know*: an event happening at a node `light_delay_nanos`
198/// away cannot be observed before `now − light_delay`. This is the light-cone horizon — the reason a
199/// distributed clock's knowledge is principled-uncertain rather than sloppy.
200pub fn knowable_horizon(now_nanos: i64, light_delay_nanos: i64) -> i64 {
201    now_nanos - light_delay_nanos
202}
203
204/// A **light-cone-aware CRDT clock**: a Hybrid Logical Clock (causal order) plus per-node knowledge
205/// intervals (light-cone-bounded estimates of each peer's current time). Its `merge` is a join over
206/// a lattice — `max` on the HLC, interval intersection per node — so replicas separated by bounded
207/// (even interplanetary) delay converge conflict-free, regardless of message order. This realises
208/// "spacelike separation = CRDT concurrency": events with no shared light cone need no total order,
209/// only this commutative/associative/idempotent merge.
210#[derive(Clone, Debug, PartialEq, Eq)]
211pub struct SyncClock {
212    pub hlc: Hlc,
213    pub knowledge: std::collections::BTreeMap<u64, EstimateInterval>,
214}
215
216impl SyncClock {
217    pub fn new() -> Self {
218        SyncClock {
219            hlc: Hlc::ZERO,
220            knowledge: std::collections::BTreeMap::new(),
221        }
222    }
223
224    /// Stamp a local event (advance the HLC); knowledge is carried unchanged.
225    pub fn tick(&self, now_nanos: i64) -> SyncClock {
226        SyncClock {
227            hlc: self.hlc.tick(now_nanos),
228            knowledge: self.knowledge.clone(),
229        }
230    }
231
232    /// Record (and tighten) what this clock knows about node `node`'s current time. A fresh node is
233    /// inserted; a known node's interval is intersected, so observation can only *narrow* knowledge.
234    pub fn observe(&self, node: u64, interval: EstimateInterval) -> SyncClock {
235        let mut knowledge = self.knowledge.clone();
236        knowledge
237            .entry(node)
238            .and_modify(|iv| *iv = iv.intersect(&interval))
239            .or_insert(interval);
240        SyncClock {
241            hlc: self.hlc,
242            knowledge,
243        }
244    }
245
246    /// The CRDT join with another replica — `max` HLC (the lattice join on the derived total order),
247    /// per-node interval intersection on shared keys, union of distinct keys. Commutative,
248    /// associative, and idempotent, so gossip converges regardless of message order.
249    pub fn merge(&self, other: &SyncClock) -> SyncClock {
250        let mut knowledge = self.knowledge.clone();
251        for (&node, &interval) in &other.knowledge {
252            knowledge
253                .entry(node)
254                .and_modify(|iv| *iv = iv.intersect(&interval))
255                .or_insert(interval);
256        }
257        SyncClock {
258            hlc: self.hlc.max(other.hlc),
259            knowledge,
260        }
261    }
262}
263
264impl Default for SyncClock {
265    fn default() -> Self {
266        SyncClock::new()
267    }
268}
269
270/// Nanoseconds in one SI second.
271pub const NANOS_PER_SECOND: i64 = 1_000_000_000;
272/// Seconds in one civil day (SmoothUTC: no leap seconds, so every day is exactly 86 400 s).
273pub const SECONDS_PER_DAY: i64 = 86_400;
274/// Nanoseconds in one civil day.
275pub const NANOS_PER_DAY: i64 = SECONDS_PER_DAY * NANOS_PER_SECOND;
276
277/// A civil (wall-clock) date-time, calendar + time-of-day, with no zone — the human-readable
278/// decomposition of a **SmoothUTC** instant (nanoseconds since the Unix epoch, leap-second-free).
279#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
280pub struct CivilDateTime {
281    pub year: i64,
282    pub month: u32,
283    pub day: u32,
284    pub hour: u32,
285    pub minute: u32,
286    pub second: u32,
287    pub nanosecond: u32,
288}
289
290/// Decompose a SmoothUTC instant (nanoseconds since 1970-01-01T00:00:00) into its civil date-time.
291/// Floor division makes pre-epoch instants correct (e.g. `-1 ns` is `1969-12-31T23:59:59.999999999`).
292pub fn civil_from_unix_nanos(ns: i64) -> CivilDateTime {
293    let day = ns.div_euclid(NANOS_PER_DAY);
294    let rem = ns.rem_euclid(NANOS_PER_DAY); // [0, NANOS_PER_DAY)
295    let (year, month, d) = civil_from_days(day);
296    let secs = rem / NANOS_PER_SECOND;
297    CivilDateTime {
298        year,
299        month,
300        day: d,
301        hour: (secs / 3600) as u32,
302        minute: ((secs % 3600) / 60) as u32,
303        second: (secs % 60) as u32,
304        nanosecond: (rem % NANOS_PER_SECOND) as u32,
305    }
306}
307
308/// The inverse: the SmoothUTC instant (nanoseconds since the epoch) of a civil date-time.
309pub fn unix_nanos_from_civil(dt: CivilDateTime) -> i64 {
310    let days = days_from_civil(dt.year, dt.month, dt.day);
311    let secs = dt.hour as i64 * 3600 + dt.minute as i64 * 60 + dt.second as i64;
312    days * NANOS_PER_DAY + secs * NANOS_PER_SECOND + dt.nanosecond as i64
313}
314
315/// A UTC-offset transition: from `at_unix_seconds` (a UTC instant) onward, the zone's local time is
316/// `UTC + offset_seconds`. A timezone is a list of these, sorted ascending — the shape every IANA
317/// zone reduces to. DST is just two alternating offsets with transitions twice a year.
318#[derive(Clone, Copy, Debug, PartialEq, Eq)]
319pub struct ZoneTransition {
320    pub at_unix_seconds: i64,
321    pub offset_seconds: i32,
322}
323
324/// How to resolve a local civil time that maps ambiguously to UTC: in a DST **fold** (the hour
325/// repeated when clocks fall back, so a local time occurs twice) or a **gap** (the hour skipped
326/// when clocks spring forward, so a local time never occurs). `Earlier` picks the earlier instant,
327/// `Later` the later one.
328#[derive(Clone, Copy, Debug, PartialEq, Eq)]
329pub enum Fold {
330    Earlier,
331    Later,
332}
333
334/// The UTC offset (seconds) a zone has at `instant_ns`. `transitions` must be sorted ascending by
335/// `at_unix_seconds`; `base_offset` applies before the first transition.
336pub fn offset_at(transitions: &[ZoneTransition], base_offset: i32, instant_ns: i64) -> i32 {
337    let secs = instant_ns.div_euclid(NANOS_PER_SECOND);
338    let mut off = base_offset;
339    for t in transitions {
340        if t.at_unix_seconds <= secs {
341            off = t.offset_seconds;
342        } else {
343            break;
344        }
345    }
346    off
347}
348
349/// The local civil date-time of a UTC instant in a zone (apply the offset in effect).
350pub fn to_local(
351    transitions: &[ZoneTransition],
352    base_offset: i32,
353    instant_ns: i64,
354) -> CivilDateTime {
355    let off = offset_at(transitions, base_offset, instant_ns);
356    civil_from_unix_nanos(instant_ns + off as i64 * NANOS_PER_SECOND)
357}
358
359/// The UTC instant of a local civil date-time in a zone. A local time normally maps to exactly one
360/// instant; in a DST fold it maps to two (resolved by `fold`); in a DST gap it maps to none (the
361/// boundary instants are returned, `fold` choosing which). This is the offset-dependent inverse of
362/// [`to_local`], solved by testing each candidate offset for self-consistency.
363pub fn from_local(
364    transitions: &[ZoneTransition],
365    base_offset: i32,
366    civil: CivilDateTime,
367    fold: Fold,
368) -> i64 {
369    let local_ns = unix_nanos_from_civil(civil);
370    // The distinct offsets the zone ever uses are the only candidates.
371    let mut offsets: Vec<i32> = vec![base_offset];
372    for t in transitions {
373        if !offsets.contains(&t.offset_seconds) {
374            offsets.push(t.offset_seconds);
375        }
376    }
377    // A candidate is self-consistent when the offset it assumes is actually the one in effect at
378    // the UTC instant it implies: `offset_at(local − offset) == offset`.
379    let mut valid: Vec<i64> = Vec::new();
380    for o in &offsets {
381        let utc = local_ns - *o as i64 * NANOS_PER_SECOND;
382        if offset_at(transitions, base_offset, utc) == *o {
383            valid.push(utc);
384        }
385    }
386    valid.sort_unstable();
387    valid.dedup();
388    if valid.len() >= 2 {
389        // Fold: the local time occurs twice.
390        return match fold {
391            Fold::Earlier => valid[0],
392            Fold::Later => *valid.last().unwrap(),
393        };
394    }
395    if valid.len() == 1 {
396        return valid[0];
397    }
398    // Gap: the local time never occurs — return a boundary instant per `fold`.
399    let mut cands: Vec<i64> = offsets
400        .iter()
401        .map(|o| local_ns - *o as i64 * NANOS_PER_SECOND)
402        .collect();
403    cands.sort_unstable();
404    match fold {
405        Fold::Earlier => cands[0],
406        Fold::Later => *cands.last().unwrap(),
407    }
408}
409
410/// A POSIX-style DST transition rule: the `week`-th `weekday` of `month`, at `time_seconds` local.
411/// `week` is `1..=5` (5 = the last occurrence); `weekday` is `0 = Sunday … 6 = Saturday`. This is
412/// the `Mm.w.d` form a TZ string uses (e.g. `M3.2.0` = the 2nd Sunday of March), and it generates
413/// one transition per year — enough to express any zone with a regular DST schedule.
414#[derive(Clone, Copy, Debug, PartialEq, Eq)]
415pub struct DstRule {
416    pub month: u32,
417    pub week: u32,
418    pub weekday: u32,
419    pub time_seconds: i64,
420}
421
422/// The day-of-month of the `week`-th `weekday` of `(year, month)` — e.g. the 2nd Sunday of March,
423/// or (with `week = 5`) the last Sunday of October. `week` is `1..=5`, `weekday` `0 = Sun … 6 = Sat`.
424pub fn nth_weekday_of_month(year: i64, month: u32, week: u32, weekday: u32) -> u32 {
425    let first = days_from_civil(year, month, 1);
426    let first_weekday = weekday_from_days(first);
427    let to_first = (weekday + 7 - first_weekday) % 7; // days from the 1st to the first `weekday`
428    let mut day = 1 + to_first + (week - 1) * 7;
429    let last = last_day_of_month(year, month);
430    while day > last {
431        day -= 7; // `week = 5` past the month's end → the last occurrence
432    }
433    day
434}
435
436/// The two UTC transitions for `year` of a zone with a regular DST schedule: spring-forward
437/// (`std_offset → dst_offset`) at `start`, fall-back (`dst_offset → std_offset`) at `end`. Each
438/// rule's `time_seconds` is wall-clock local in the offset in effect just before the transition.
439pub fn dst_transitions_for_year(
440    std_offset: i32,
441    dst_offset: i32,
442    start: DstRule,
443    end: DstRule,
444    year: i64,
445) -> [ZoneTransition; 2] {
446    // A rule's local wall-clock time is in the offset in effect just before the jump, so the UTC
447    // instant is `local − pre_offset`. The new offset takes effect from there.
448    let transition = |rule: DstRule, pre_offset: i32, new_offset: i32| {
449        let day = nth_weekday_of_month(year, rule.month, rule.week, rule.weekday);
450        let local = days_from_civil(year, rule.month, day) * SECONDS_PER_DAY + rule.time_seconds;
451        ZoneTransition {
452            at_unix_seconds: local - pre_offset as i64,
453            offset_seconds: new_offset,
454        }
455    };
456    [
457        transition(start, std_offset, dst_offset), // spring forward: STD → DST
458        transition(end, dst_offset, std_offset),   // fall back: DST → STD
459    ]
460}
461
462/// A named time zone: its standard UTC offset, and an optional DST schedule `(dst_offset, spring
463/// rule, fall rule)`. A zone with `dst = None` is a fixed offset (UTC, IST, JST). DST transitions
464/// are *generated* per year from the rules, so a `ZoneSpec` is tiny — no transition table.
465#[derive(Clone, Copy, Debug, PartialEq, Eq)]
466pub struct ZoneSpec {
467    pub name: &'static str,
468    pub std_offset: i32,
469    pub dst: Option<(i32, DstRule, DstRule)>,
470}
471
472impl ZoneSpec {
473    /// The zone's UTC transitions for every year in `start_year..=end_year`, sorted ascending
474    /// (empty for a fixed-offset zone).
475    pub fn transitions(&self, start_year: i64, end_year: i64) -> Vec<ZoneTransition> {
476        let mut v = Vec::new();
477        if let Some((dst_offset, start, end)) = self.dst {
478            for y in start_year..=end_year {
479                let pair = dst_transitions_for_year(self.std_offset, dst_offset, start, end, y);
480                v.extend_from_slice(&pair);
481            }
482            v.sort_by_key(|t| t.at_unix_seconds);
483        }
484        v
485    }
486
487    /// The local civil date-time of a UTC instant in this zone (DST resolved from the rules).
488    pub fn to_local(&self, instant_ns: i64) -> CivilDateTime {
489        if self.dst.is_none() {
490            return civil_from_unix_nanos(instant_ns + self.std_offset as i64 * NANOS_PER_SECOND);
491        }
492        // Generate transitions for the instant's year ±1 so it is always past the first one (this
493        // makes `std_offset` as the pre-first base harmless, including the southern hemisphere).
494        let (year, _, _) = civil_from_days(instant_ns.div_euclid(NANOS_PER_DAY));
495        let tz = self.transitions(year - 1, year + 1);
496        to_local(&tz, self.std_offset, instant_ns)
497    }
498}
499
500/// The **local-as-UTC instant** of a UTC instant in a named zone: the nanoseconds that, read back
501/// with the plain UTC calendar functions, yield the zone's *local* wall-clock components. This is
502/// the lowering target for zoned component reads (`the hour of m in "Asia/Tokyo"`): a local clock
503/// face encoded as an instant, so every UTC extractor composes onto it unchanged. `None` if the
504/// zone is unknown. (Not a real instant — it is the wall clock; do not re-format it with a `Z`.)
505pub fn local_instant_nanos(instant_ns: i64, zone_name: &str) -> Option<i64> {
506    let zone = zone_by_name(zone_name)?;
507    Some(unix_nanos_from_civil(zone.to_local(instant_ns)))
508}
509
510/// Format a UTC instant as the **local wall-clock time in a named zone**, with its offset —
511/// `2024-07-01T08:00:00-04:00` (the timezone-aware "relative read" of an instant). `None` if the
512/// zone is unknown. The space-aware/zoned generalisation of [`format_rfc3339`].
513pub fn format_zoned(instant_ns: i64, zone_name: &str) -> Option<String> {
514    let zone = zone_by_name(zone_name)?;
515    let local = zone.to_local(instant_ns);
516    // local-as-UTC minus the true instant is exactly the zone's offset at that moment.
517    let offset_secs = (unix_nanos_from_civil(local) - instant_ns) / NANOS_PER_SECOND;
518    let sign = if offset_secs < 0 { '-' } else { '+' };
519    let abs = offset_secs.abs();
520    Some(format!(
521        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}{}{:02}:{:02}",
522        local.year,
523        local.month,
524        local.day,
525        local.hour,
526        local.minute,
527        local.second,
528        sign,
529        abs / 3600,
530        (abs % 3600) / 60,
531    ))
532}
533
534/// Look up a [`ZoneSpec`] by IANA name (e.g. `"America/New_York"`, `"UTC"`, `"Australia/Sydney"`).
535/// `None` for an unknown zone. A growable registry seeded with common zones (POSIX-rule based);
536/// the full IANA set ingests later.
537pub fn zone_by_name(name: &str) -> Option<ZoneSpec> {
538    // North-American DST: 2nd Sunday of March → 1st Sunday of November, both at 02:00 local.
539    let us = (
540        DstRule {
541            month: 3,
542            week: 2,
543            weekday: 0,
544            time_seconds: 2 * 3600,
545        },
546        DstRule {
547            month: 11,
548            week: 1,
549            weekday: 0,
550            time_seconds: 2 * 3600,
551        },
552    );
553    // EU DST changes at 01:00 UTC: the local wall-clock time is `01:00 + std` (pre-transition).
554    let eu = |std_h: i64| {
555        (
556            DstRule {
557                month: 3,
558                week: 5,
559                weekday: 0,
560                time_seconds: (std_h + 1) * 3600,
561            },
562            DstRule {
563                month: 10,
564                week: 5,
565                weekday: 0,
566                time_seconds: (std_h + 2) * 3600,
567            },
568        )
569    };
570    let spec = match name {
571        "UTC" | "Etc/UTC" | "Zulu" => ZoneSpec {
572            name: "UTC",
573            std_offset: 0,
574            dst: None,
575        },
576        "America/New_York" => ZoneSpec {
577            name: "America/New_York",
578            std_offset: -5 * 3600,
579            dst: Some((-4 * 3600, us.0, us.1)),
580        },
581        "America/Chicago" => ZoneSpec {
582            name: "America/Chicago",
583            std_offset: -6 * 3600,
584            dst: Some((-5 * 3600, us.0, us.1)),
585        },
586        "America/Denver" => ZoneSpec {
587            name: "America/Denver",
588            std_offset: -7 * 3600,
589            dst: Some((-6 * 3600, us.0, us.1)),
590        },
591        "America/Los_Angeles" => ZoneSpec {
592            name: "America/Los_Angeles",
593            std_offset: -8 * 3600,
594            dst: Some((-7 * 3600, us.0, us.1)),
595        },
596        "America/Phoenix" => ZoneSpec {
597            name: "America/Phoenix",
598            std_offset: -7 * 3600,
599            dst: None,
600        },
601        "Europe/London" | "Europe/Dublin" | "Europe/Lisbon" => {
602            let (s, e) = eu(0);
603            ZoneSpec {
604                name: "Europe/London",
605                std_offset: 0,
606                dst: Some((3600, s, e)),
607            }
608        }
609        "Europe/Paris" | "Europe/Berlin" | "Europe/Madrid" | "Europe/Rome" | "Europe/Amsterdam" => {
610            let (s, e) = eu(1);
611            ZoneSpec {
612                name: "Europe/Paris",
613                std_offset: 3600,
614                dst: Some((2 * 3600, s, e)),
615            }
616        }
617        "Asia/Kolkata" | "Asia/Calcutta" => ZoneSpec {
618            name: "Asia/Kolkata",
619            std_offset: 5 * 3600 + 1800,
620            dst: None,
621        },
622        "Asia/Tokyo" => ZoneSpec {
623            name: "Asia/Tokyo",
624            std_offset: 9 * 3600,
625            dst: None,
626        },
627        "Asia/Shanghai" => ZoneSpec {
628            name: "Asia/Shanghai",
629            std_offset: 8 * 3600,
630            dst: None,
631        },
632        "Australia/Sydney" => ZoneSpec {
633            name: "Australia/Sydney",
634            std_offset: 10 * 3600,
635            // Southern hemisphere: spring-forward in October, fall-back in April.
636            dst: Some((
637                11 * 3600,
638                DstRule {
639                    month: 10,
640                    week: 1,
641                    weekday: 0,
642                    time_seconds: 2 * 3600,
643                },
644                DstRule {
645                    month: 4,
646                    week: 1,
647                    weekday: 0,
648                    time_seconds: 3 * 3600,
649                },
650            )),
651        },
652        _ => return None,
653    };
654    Some(spec)
655}
656
657/// Add a **calendar span** (`months` then `days`) to a civil date-time — the *civil* (wall-clock)
658/// operation, distinct from adding a physical `Duration`. Months are applied first with
659/// **end-of-month clamping** (`Jan 31 + 1 month = Feb 28/29`), then whole `days` roll over exactly
660/// through the day number. The time-of-day is preserved. (`Span` arithmetic on a *zoned* value is
661/// where it diverges from a physical duration across a DST boundary; in UTC the two agree.)
662pub fn add_span(dt: CivilDateTime, months: i64, days: i64) -> CivilDateTime {
663    let total = (dt.year * 12 + (dt.month as i64 - 1)) + months;
664    let new_year = total.div_euclid(12);
665    let new_month = (total.rem_euclid(12) + 1) as u32;
666    let clamped_day = dt.day.min(last_day_of_month(new_year, new_month));
667    let z = days_from_civil(new_year, new_month, clamped_day) + days;
668    let (year, month, day) = civil_from_days(z);
669    CivilDateTime {
670        year,
671        month,
672        day,
673        ..dt
674    }
675}
676
677/// Add a **calendar span** (`months`, then `days`) to a date held as days since 1970-01-01 — the
678/// civil `Date + Span` every tier computes: months clamp at the end of the month and respect leap
679/// years (`Jan 31 + 1 month = Feb 28/29`), then whole days roll over. Month and day arithmetic wraps
680/// at `i32`, as `Int` span arithmetic does everywhere. `Date - Span` is this with both parts negated.
681pub fn date_add_span(days_since_epoch: i32, months: i32, days: i32) -> i32 {
682    let z = days_since_epoch + 719468;
683    let era = if z >= 0 {
684        z / 146097
685    } else {
686        (z - 146096) / 146097
687    };
688    let doe = (z - era * 146097) as u32;
689    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
690    let y = yoe as i32 + era * 400;
691    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
692    let mp = (5 * doy + 2) / 153;
693    let d = doy - (153 * mp + 2) / 5 + 1;
694    let m = if mp < 10 { mp + 3 } else { mp - 9 };
695    let mut year = y + if m <= 2 { 1 } else { 0 };
696    let mut month = m as i32;
697    let mut day = d as i32;
698
699    let total_months = year
700        .wrapping_mul(12)
701        .wrapping_add(month - 1)
702        .wrapping_add(months);
703    year = total_months / 12;
704    month = total_months % 12 + 1;
705    if month <= 0 {
706        month += 12;
707        year -= 1;
708    }
709
710    let last = last_day_of_month(year as i64, month as u32) as i32;
711    if day > last {
712        day = last;
713    }
714
715    let yp = year - if month <= 2 { 1 } else { 0 };
716    let era2 = if yp >= 0 { yp / 400 } else { (yp - 399) / 400 };
717    let yoe2 = (yp - era2 * 400) as u32;
718    let mp2 = if month > 2 {
719        month as u32 - 3
720    } else {
721        month as u32 + 9
722    };
723    let doy2 = (153 * mp2 + 2) / 5 + day as u32 - 1;
724    let doe2 = yoe2 * 365 + yoe2 / 4 - yoe2 / 100 + doy2;
725    let result = era2 * 146097 + doe2 as i32 - 719468;
726
727    result.wrapping_add(days)
728}
729
730/// The number of **complete calendar months** from instant `a` to instant `b` (signed; negative when
731/// `b` precedes `a`). A month is complete only when `b` reaches at least `a + k months` under the same
732/// end-of-month-clamping, time-of-day-preserving rule as [`add_span`] — so `Jan 15 → Mar 14` is 1
733/// month (not 2), `Jan 31 → Feb 28` (non-leap) is a full month, and one hour short of a month is 0.
734pub fn months_between(a_nanos: i64, b_nanos: i64) -> i64 {
735    if b_nanos < a_nanos {
736        return -months_between(b_nanos, a_nanos);
737    }
738    let a = civil_from_unix_nanos(a_nanos);
739    let b = civil_from_unix_nanos(b_nanos);
740    let mut months = (b.year - a.year) * 12 + (b.month as i64 - a.month as i64);
741    // Matching only year+month can overshoot by the day/time-of-day; if `a + months` lands after `b`
742    // the final month has not completed, so step back one. (At most one correction is ever needed.)
743    if unix_nanos_from_civil(add_span(a, months, 0)) > b_nanos {
744        months -= 1;
745    }
746    months
747}
748
749/// The number of **complete calendar years** from `a` to `b` (signed) — complete 12-month periods,
750/// so `2020-06-01 → 2024-03-01` is 3 (the fourth year, ending 2024-06-01, has not arrived).
751pub fn years_between(a_nanos: i64, b_nanos: i64) -> i64 {
752    months_between(a_nanos, b_nanos) / 12
753}
754
755/// True if a day number falls on a weekend (Saturday or Sunday).
756pub fn is_weekend(z: i64) -> bool {
757    matches!(iso_weekday_from_days(z), 6 | 7) // ISO: 6 = Saturday, 7 = Sunday
758}
759
760/// The count of **business days** (Mon–Fri) in the half-open interval between two day numbers.
761/// Signed by direction (`b < a` yields a negative count); `[a, b)` so adjacent days differ by 1.
762pub fn business_days_between(a: i64, b: i64) -> i64 {
763    if a == b {
764        return 0;
765    }
766    let (lo, hi, sign) = if a < b { (a, b, 1) } else { (b, a, -1) };
767    let span = hi - lo;
768    let full_weeks = span / 7;
769    let mut count = full_weeks * 5;
770    let mut d = lo + full_weeks * 7;
771    while d < hi {
772        if !is_weekend(d) {
773            count += 1;
774        }
775        d += 1;
776    }
777    sign * count
778}
779
780/// Advance a day number by `n` **business days** (skipping weekends): `n > 0` moves forward,
781/// `n < 0` backward. Landing rule is "next business day in the direction of travel", so
782/// `add_business_days(friday, 1)` is the following Monday and `add_business_days(monday, -1)` is
783/// the preceding Friday.
784pub fn add_business_days(z: i64, n: i64) -> i64 {
785    let step = if n >= 0 { 1 } else { -1 };
786    let mut remaining = n.abs();
787    let mut d = z;
788    while remaining > 0 {
789        d += step;
790        if !is_weekend(d) {
791            remaining -= 1;
792        }
793    }
794    d
795}
796
797/// Format a **physical duration** (nanoseconds) as a compact human string — `1h30m`, `500ms`,
798/// `1.5s`, `2d`, `-45m`, `0s`. Largest unit first; zero components omitted; sub-second fractions
799/// trimmed. The inverse of [`parse_duration`]. (This is a *physical* elapsed time, distinct from a
800/// calendar `Span`: it has no months — those aren't a fixed number of nanoseconds.)
801pub fn format_duration(nanos: i64) -> String {
802    if nanos == 0 {
803        return "0s".to_string();
804    }
805    const D: u128 = 86_400_000_000_000;
806    const H: u128 = 3_600_000_000_000;
807    const M: u128 = 60_000_000_000;
808    const S: u128 = 1_000_000_000;
809    const MS: u128 = 1_000_000;
810    const US: u128 = 1_000;
811    let mut out = String::new();
812    if nanos < 0 {
813        out.push('-');
814    }
815    let mut abs = (nanos as i128).unsigned_abs();
816    // A fractional sub-unit, trimmed of trailing zeros (`frac` has `width` digits).
817    let frac_str = |frac: u128, width: usize| -> String {
818        let mut f = format!("{:0width$}", frac, width = width);
819        while f.ends_with('0') {
820            f.pop();
821        }
822        f
823    };
824    if abs >= S {
825        let d = abs / D;
826        abs %= D;
827        let h = abs / H;
828        abs %= H;
829        let m = abs / M;
830        abs %= M;
831        if d > 0 {
832            out += &format!("{d}d");
833        }
834        if h > 0 {
835            out += &format!("{h}h");
836        }
837        if m > 0 {
838            out += &format!("{m}m");
839        }
840        let (secs, frac) = (abs / S, abs % S);
841        if frac == 0 {
842            if secs > 0 {
843                out += &format!("{secs}s");
844            }
845        } else {
846            out += &format!("{secs}.{}s", frac_str(frac, 9));
847        }
848    } else if abs >= MS {
849        let (w, frac) = (abs / MS, abs % MS);
850        out += &(if frac == 0 {
851            format!("{w}ms")
852        } else {
853            format!("{w}.{}ms", frac_str(frac, 6))
854        });
855    } else if abs >= US {
856        let (w, frac) = (abs / US, abs % US);
857        out += &(if frac == 0 {
858            format!("{w}us")
859        } else {
860            format!("{w}.{}us", frac_str(frac, 3))
861        });
862    } else {
863        out += &format!("{abs}ns");
864    }
865    out
866}
867
868/// Parse a **physical duration** string into nanoseconds — `1h30m`, `90m`, `1.5s`, `500ms`, `2d`,
869/// `-1h`, `1d2h3m4s`. Units: `d h m s ms us`/`µs` `ns`. `None` on malformed input or i64 overflow.
870pub fn parse_duration(s: &str) -> Option<i64> {
871    let b = s.as_bytes();
872    let mut i = 0;
873    let neg = match b.first() {
874        Some(&b'-') => {
875            i += 1;
876            true
877        }
878        Some(&b'+') => {
879            i += 1;
880            false
881        }
882        _ => false,
883    };
884    if i >= b.len() {
885        return None;
886    }
887    let mut total: i128 = 0;
888    let mut saw_any = false;
889    while i < b.len() {
890        let int_start = i;
891        while i < b.len() && b[i].is_ascii_digit() {
892            i += 1;
893        }
894        let int_str = &s[int_start..i];
895        let mut frac_str = "";
896        if i < b.len() && b[i] == b'.' {
897            i += 1;
898            let frac_start = i;
899            while i < b.len() && b[i].is_ascii_digit() {
900                i += 1;
901            }
902            frac_str = &s[frac_start..i];
903        }
904        if int_str.is_empty() && frac_str.is_empty() {
905            return None; // a unit with no number
906        }
907        let rest = &s[i..];
908        let (unit_nanos, ulen): (i128, usize) = if rest.starts_with("ms") {
909            (1_000_000, 2)
910        } else if rest.starts_with("ns") {
911            (1, 2)
912        } else if rest.starts_with("us") {
913            (1_000, 2)
914        } else if rest.starts_with("µs") {
915            (1_000, "µs".len())
916        } else if rest.starts_with('s') {
917            (1_000_000_000, 1)
918        } else if rest.starts_with('m') {
919            (60_000_000_000, 1)
920        } else if rest.starts_with('h') {
921            (3_600_000_000_000, 1)
922        } else if rest.starts_with('d') {
923            (86_400_000_000_000, 1)
924        } else {
925            return None; // unknown / missing unit
926        };
927        i += ulen;
928        let int_val: i128 = if int_str.is_empty() {
929            0
930        } else {
931            int_str.parse().ok()?
932        };
933        total = total.checked_add(int_val.checked_mul(unit_nanos)?)?;
934        if !frac_str.is_empty() {
935            let frac_val: i128 = frac_str.parse().ok()?;
936            let mut denom: i128 = 1;
937            for _ in 0..frac_str.len() {
938                denom *= 10;
939            }
940            total = total.checked_add(frac_val * unit_nanos / denom)?;
941        }
942        saw_any = true;
943    }
944    if !saw_any {
945        return None;
946    }
947    i64::try_from(if neg { -total } else { total }).ok()
948}
949
950/// Format a SmoothUTC instant as an **RFC 3339 / ISO 8601** UTC timestamp (`Z` zone), e.g.
951/// `1970-01-01T00:00:00Z` or `2024-03-10T07:30:00.123456789Z`. Sub-second precision appears only
952/// when nonzero, with trailing zeros trimmed.
953pub fn format_rfc3339(instant_ns: i64) -> String {
954    let c = civil_from_unix_nanos(instant_ns);
955    let mut s = format!(
956        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}",
957        c.year, c.month, c.day, c.hour, c.minute, c.second
958    );
959    if c.nanosecond != 0 {
960        let mut frac = format!("{:09}", c.nanosecond);
961        while frac.ends_with('0') {
962            frac.pop();
963        }
964        s.push('.');
965        s.push_str(&frac);
966    }
967    s.push('Z');
968    s
969}
970
971/// Format a **time-of-day** (nanoseconds from midnight) as `HH:MM:SS`, with a trailing sub-second
972/// fraction only when nonzero (trailing zeros trimmed) — e.g. `07:30:45`, `16:00:00`,
973/// `07:30:45.5`. The clock face is lossless to the nanosecond; the input is normalised modulo a day
974/// so a negative or overflowing value still maps onto `[00:00:00, 24:00:00)`.
975pub fn format_time_of_day(nanos_from_midnight: i64) -> String {
976    let rem = nanos_from_midnight.rem_euclid(NANOS_PER_DAY);
977    let secs = rem / NANOS_PER_SECOND;
978    let mut s = format!(
979        "{:02}:{:02}:{:02}",
980        secs / 3600,
981        (secs % 3600) / 60,
982        secs % 60
983    );
984    let nanos = (rem % NANOS_PER_SECOND) as u32;
985    if nanos != 0 {
986        let mut frac = format!("{:09}", nanos);
987        while frac.ends_with('0') {
988            frac.pop();
989        }
990        s.push('.');
991        s.push_str(&frac);
992    }
993    s
994}
995
996/// Parse an **RFC 3339 / ISO 8601** timestamp into a SmoothUTC instant (nanoseconds since epoch).
997/// Accepts a `Z` zone or a numeric `±HH:MM` offset (normalized to UTC); `None` on malformed input.
998pub fn parse_rfc3339(s: &str) -> Option<i64> {
999    let b = s.as_bytes();
1000    // The fixed `YYYY-MM-DDTHH:MM:SS` prefix is 19 bytes; a zone always follows.
1001    if b.len() < 20 {
1002        return None;
1003    }
1004    let digits = |start: usize, len: usize| -> Option<i64> {
1005        let mut v: i64 = 0;
1006        for i in start..start + len {
1007            let c = *b.get(i)?;
1008            if !c.is_ascii_digit() {
1009                return None;
1010            }
1011            v = v * 10 + (c - b'0') as i64;
1012        }
1013        Some(v)
1014    };
1015    if b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' {
1016        return None;
1017    }
1018    let year = digits(0, 4)?;
1019    let month = digits(5, 2)? as u32;
1020    let day = digits(8, 2)? as u32;
1021    let hour = digits(11, 2)? as u32;
1022    let minute = digits(14, 2)? as u32;
1023    let second = digits(17, 2)? as u32;
1024    if !(1..=12).contains(&month) || !(1..=last_day_of_month(year, month)).contains(&day) {
1025        return None;
1026    }
1027    if hour > 23 || minute > 59 || second > 59 {
1028        return None;
1029    }
1030    let mut pos = 19;
1031    // Optional fractional seconds, scaled to nanoseconds (9 digits; extra digits truncated).
1032    let mut nanosecond: u32 = 0;
1033    if b.get(pos) == Some(&b'.') {
1034        pos += 1;
1035        let (mut frac, mut count) = (0u64, 0u32);
1036        while let Some(&c) = b.get(pos) {
1037            if !c.is_ascii_digit() {
1038                break;
1039            }
1040            if count < 9 {
1041                frac = frac * 10 + (c - b'0') as u64;
1042                count += 1;
1043            }
1044            pos += 1;
1045        }
1046        if count == 0 {
1047            return None; // a '.' with no digits
1048        }
1049        for _ in count..9 {
1050            frac *= 10;
1051        }
1052        nanosecond = frac as u32;
1053    }
1054    // Zone: `Z` (UTC) or a numeric `±HH:MM` offset.
1055    let offset_seconds: i64 = match b.get(pos) {
1056        Some(&b'Z') => {
1057            pos += 1;
1058            0
1059        }
1060        Some(&c) if c == b'+' || c == b'-' => {
1061            let sign = if c == b'+' { 1 } else { -1 };
1062            let oh = digits(pos + 1, 2)?;
1063            if b.get(pos + 3) != Some(&b':') {
1064                return None;
1065            }
1066            let om = digits(pos + 4, 2)?;
1067            if oh > 23 || om > 59 {
1068                return None;
1069            }
1070            pos += 6;
1071            sign * (oh * 3600 + om * 60)
1072        }
1073        _ => return None,
1074    };
1075    if pos != b.len() {
1076        return None; // trailing garbage
1077    }
1078    let civil = CivilDateTime {
1079        year,
1080        month,
1081        day,
1082        hour,
1083        minute,
1084        second,
1085        nanosecond,
1086    };
1087    Some(unix_nanos_from_civil(civil) - offset_seconds * NANOS_PER_SECOND)
1088}
1089
1090/// True if `year` is a leap year in the proleptic **Gregorian** calendar (every 4th year, except
1091/// centuries, except every 400th).
1092pub fn is_gregorian_leap(year: i64) -> bool {
1093    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
1094}
1095
1096/// True if `year` is a leap year in the proleptic **Julian** calendar (every 4th year, no
1097/// century exception).
1098pub fn is_julian_leap(year: i64) -> bool {
1099    year.rem_euclid(4) == 0
1100}
1101
1102/// Days since 1970-01-01 for a **Gregorian** civil date. Howard Hinnant's algorithm — exact for
1103/// any year, `month` in `1..=12`, `day` in `1..=last_day_of_month`.
1104pub fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
1105    let y = if month <= 2 { year - 1 } else { year };
1106    let era = (if y >= 0 { y } else { y - 399 }) / 400;
1107    let yoe = (y - era * 400) as i64; // [0, 399]
1108    let m = month as i64;
1109    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day as i64 - 1; // [0, 365]
1110    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
1111    era * 146097 + doe - 719468
1112}
1113
1114/// The inverse of [`days_from_civil`]: the **Gregorian** `(year, month, day)` of a day number.
1115pub fn civil_from_days(z: i64) -> (i64, u32, u32) {
1116    let z = z + 719468;
1117    let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
1118    let doe = z - era * 146097; // [0, 146096]
1119    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; // [0, 399]
1120    let y = yoe + era * 400;
1121    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
1122    let mp = (5 * doy + 2) / 153; // [0, 11]
1123    let day = (doy - (153 * mp + 2) / 5 + 1) as u32; // [1, 31]
1124    let month = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32; // [1, 12]
1125    let year = if month <= 2 { y + 1 } else { y };
1126    (year, month, day)
1127}
1128
1129/// The last day (28–31) of a **Gregorian** month.
1130pub fn last_day_of_month(year: i64, month: u32) -> u32 {
1131    match month {
1132        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
1133        4 | 6 | 9 | 11 => 30,
1134        2 => {
1135            if is_gregorian_leap(year) {
1136                29
1137            } else {
1138                28
1139            }
1140        }
1141        _ => 0,
1142    }
1143}
1144
1145/// The weekday of a day number: `0 = Sunday … 6 = Saturday`. (1970-01-01 was a Thursday = 4.)
1146pub fn weekday_from_days(z: i64) -> u32 {
1147    (z + 4).rem_euclid(7) as u32
1148}
1149
1150/// The ISO-8601 weekday of a day number: `1 = Monday … 7 = Sunday`.
1151pub fn iso_weekday_from_days(z: i64) -> u32 {
1152    (z + 3).rem_euclid(7) as u32 + 1
1153}
1154
1155/// The 1-based day of the **Gregorian** year (`1..=366`).
1156pub fn day_of_year(year: i64, month: u32, day: u32) -> u32 {
1157    (days_from_civil(year, month, day) - days_from_civil(year, 1, 1) + 1) as u32
1158}
1159
1160/// The **ISO-8601 week date** of a day number: `(iso_year, week, iso_weekday)`, with
1161/// `week` in `1..=53` and `iso_weekday` in `1..=7` (Monday … Sunday). The ISO year can differ
1162/// from the civil year near January 1 / December 31 (e.g. 2021-01-01 is ISO 2020-W53-5).
1163pub fn iso_week_from_days(z: i64) -> (i64, u32, u32) {
1164    let iso_dow = iso_weekday_from_days(z);
1165    // The Thursday of this ISO week (days 1..7 = Mon..Sun, so Thursday = day 4) names the ISO year.
1166    let thursday = z + (4 - iso_dow as i64);
1167    let (iso_year, _, _) = civil_from_days(thursday);
1168    // ISO week 1 is the week containing January 4 (equivalently, the year's first Thursday); its
1169    // Monday anchors week numbering. (Jan 4's *week's* Thursday is always in `iso_year`, unlike
1170    // Jan 1's, which can fall in the previous year.)
1171    let jan4 = days_from_civil(iso_year, 1, 4);
1172    let week1_monday = jan4 - (iso_weekday_from_days(jan4) as i64 - 1);
1173    let week = ((z - week1_monday) / 7 + 1) as u32;
1174    (iso_year, week, iso_dow)
1175}
1176
1177/// The inverse of [`iso_week_from_days`]: the day number of an ISO-8601 week date
1178/// `(iso_year, week, iso_weekday)` (week `1..=53`, weekday `1..=7` Monday … Sunday).
1179pub fn days_from_iso_week(iso_year: i64, week: u32, iso_weekday: u32) -> i64 {
1180    let jan4 = days_from_civil(iso_year, 1, 4);
1181    let week1_monday = jan4 - (iso_weekday_from_days(jan4) as i64 - 1);
1182    week1_monday + (week as i64 - 1) * 7 + (iso_weekday as i64 - 1)
1183}
1184
1185/// The Julian Day Number of a **Julian-calendar** date (proleptic, `month` in `1..=12`).
1186pub fn jdn_from_julian(year: i64, month: u32, day: u32) -> i64 {
1187    let a = (14 - month as i64) / 12;
1188    let y = year + 4800 - a;
1189    let m = month as i64 + 12 * a - 3;
1190    day as i64 + (153 * m + 2) / 5 + 365 * y + y / 4 - 32083
1191}
1192
1193/// The inverse of [`jdn_from_julian`]: the **Julian-calendar** `(year, month, day)` of a JDN.
1194pub fn julian_from_jdn(jdn: i64) -> (i64, u32, u32) {
1195    let c = jdn + 32082;
1196    let d = (4 * c + 3) / 1461;
1197    let e = c - (1461 * d) / 4;
1198    let m = (5 * e + 2) / 153;
1199    let day = (e - (153 * m + 2) / 5 + 1) as u32;
1200    let month = (m + 3 - 12 * (m / 10)) as u32;
1201    let year = d - 4800 + m / 10;
1202    (year, month, day)
1203}
1204
1205/// Days since 1970-01-01 for a **Julian-calendar** date.
1206pub fn days_from_julian(year: i64, month: u32, day: u32) -> i64 {
1207    jdn_from_julian(year, month, day) - UNIX_EPOCH_JDN
1208}
1209
1210/// The inverse: the **Julian-calendar** `(year, month, day)` of a day number.
1211pub fn julian_from_days(z: i64) -> (i64, u32, u32) {
1212    julian_from_jdn(z + UNIX_EPOCH_JDN)
1213}
1214
1215#[cfg(test)]
1216#[path = "../../logicaffeine_tests/unit/logicaffeine_base/temporal/tests.rs"]
1217mod tests;