Skip to main content

relate_core/temporal/
mod.rs

1//! OpenCypher temporal values (ADR-0021).
2
3use std::cmp::Ordering;
4use std::fmt;
5
6use chrono::{NaiveDate, NaiveDateTime, NaiveTime, Timelike, Weekday};
7
8use crate::{Error, Value};
9
10mod arith;
11mod between;
12mod clock;
13mod component;
14mod construct;
15mod duration;
16mod duration_pattern;
17mod exact;
18mod field;
19mod field_rules;
20mod format;
21mod parse;
22mod pattern;
23#[cfg(test)]
24mod test_support;
25#[cfg(test)]
26mod tests;
27#[cfg(test)]
28mod tests_arith;
29#[cfg(test)]
30mod tests_between;
31#[cfg(test)]
32mod tests_clock;
33#[cfg(test)]
34mod tests_duration;
35#[cfg(test)]
36mod tests_fields;
37#[cfg(test)]
38mod tests_pattern;
39#[cfg(test)]
40mod tests_ranges;
41mod truncate;
42mod zone;
43
44use zone::{add_offset, zone_kind, ZoneSpec};
45
46pub use arith::{
47    add_duration, civil_epoch_days, civil_from_days, negate_duration, scale_duration, sub_duration,
48};
49pub use between::{duration_between, duration_between_unit, BetweenUnit};
50pub use clock::{
51    clock_access, clock_spelling, clock_spelling_rows, clock_spellings, construct_clock,
52    now_epoch_millis, now_utc_dt, ClockKind, ClockMode, QueryClockGuard,
53};
54pub use construct::{
55    accepts_pattern, construct_date, construct_datetime, construct_duration,
56    construct_localdatetime, construct_localtime, construct_named, construct_time, is_constructor,
57    samples_clock,
58};
59pub use format::format_pattern;
60pub use parse::{
61    datetime_from_epoch, datetime_from_epoch_millis, padded_iso_date_value, parse_iso,
62    parse_pattern,
63};
64pub use truncate::{truncate, truncate_now};
65pub use zone::{zone_offset_at, zone_offset_at_utc, zone_region, ZoneError, MAX_OFFSET_SECONDS};
66
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub enum Temporal {
69    Date(NaiveDate),
70    /// Out-of-range proleptic date (TCK ±999999999).
71    CivilDate {
72        year: i64,
73        month: u32,
74        day: u32,
75    },
76    LocalTime(NaiveTime),
77    Time {
78        time: NaiveTime,
79        offset: i32,
80    },
81    LocalDateTime(NaiveDateTime),
82    CivilDateTime {
83        year: i64,
84        month: u32,
85        day: u32,
86        time: NaiveTime,
87    },
88    DateTime {
89        utc: NaiveDateTime,
90        offset: i32,
91        zone: Option<String>,
92    },
93    Duration {
94        months: i64,
95        days: i64,
96        nanos: i128,
97    },
98}
99
100/// The six temporal type kinds, one per Cypher type name — the variant
101/// grouping the type-name spelling and the ORDER BY sub-ranks both key
102/// off, so it exists in one place. Declared in the ORDER BY rank order:
103/// ZONED DATETIME < LOCAL DATETIME < DATE < ZONED TIME < LOCAL TIME <
104/// DURATION (live Neo4j 2026.10.1, value-independent), so a kind's
105/// discriminant is that rank's offset.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub(crate) enum TemporalKind {
108    DateTime,
109    LocalDateTime,
110    Date,
111    Time,
112    LocalTime,
113    Duration,
114}
115
116impl TemporalKind {
117    /// The kind's lowercase wire name — the `Temporal::kind_name`
118    /// spelling, owned by the kind so the variant partition has one
119    /// owner.
120    pub(crate) fn name(self) -> &'static str {
121        match self {
122            TemporalKind::DateTime => "datetime",
123            TemporalKind::LocalDateTime => "localdatetime",
124            TemporalKind::Date => "date",
125            TemporalKind::Time => "time",
126            TemporalKind::LocalTime => "localtime",
127            TemporalKind::Duration => "duration",
128        }
129    }
130}
131
132impl Temporal {
133    /// This value's type kind — the one spelling of the variant grouping
134    /// (the civil out-of-range forms share their kind's name).
135    pub(crate) fn kind(&self) -> TemporalKind {
136        match self {
137            Temporal::DateTime { .. } => TemporalKind::DateTime,
138            Temporal::LocalDateTime(_) | Temporal::CivilDateTime { .. } => {
139                TemporalKind::LocalDateTime
140            }
141            Temporal::Date(_) | Temporal::CivilDate { .. } => TemporalKind::Date,
142            Temporal::Time { .. } => TemporalKind::Time,
143            Temporal::LocalTime(_) => TemporalKind::LocalTime,
144            Temporal::Duration { .. } => TemporalKind::Duration,
145        }
146    }
147}
148
149/// The zone half of a `DateTime`'s equality identity (TCK TemporalCompare):
150/// an IANA zone is identified by its name — so the two halves of a DST
151/// fall-back overlap stay equal — and every other spelling (`Z`, `+00:00`,
152/// `UTC`, …) by the UTC offset it denotes, so `Z` equals `+00:00` while a
153/// named zone never equals the offset it happens to denote.
154#[derive(Debug, Clone, PartialEq, Eq, Hash)]
155pub enum ZoneId {
156    Named(String),
157    Offset(i32),
158}
159
160impl ZoneId {
161    /// The identity of a `DateTime`'s `zone` at `offset`.
162    pub fn of(zone: Option<&str>, offset: i32) -> ZoneId {
163        match zone_region(zone) {
164            Some(name) => ZoneId::Named(name.to_string()),
165            None => ZoneId::Offset(offset),
166        }
167    }
168}
169
170impl Temporal {
171    /// The one place a duration's stored `(months, days, nanos)` triple is
172    /// assembled, and the one place its representability bound lives: the
173    /// sub-day part must fit Neo4j's `i64` seconds field (inclusive of
174    /// `2^63`, the `f64` image of `i64::MAX` that the scaling path still
175    /// casts back), and the duration's average length in seconds
176    /// (`months * AVG_SECONDS_PER_MONTH + days * 86400 + seconds`) must fit
177    /// an `i64` (`DurationValue.assertNoOverflow`). Every producer — the ISO
178    /// numeral parser, the pattern parser, the map constructor, scaling and
179    /// duration addition — builds through this seam, so one value is
180    /// accepted or rejected regardless of how it was spelled; a value past
181    /// the bound is Neo4j's interval-field overflow, never a silently larger
182    /// duration. Neo4j's constructor enforces the same bound (verified
183    /// against Neo4j 5: `duration({months: 4000000000000})` errors, while the
184    /// same value via `* 1.0` errors identically).
185    pub(crate) fn duration_checked(months: i64, days: i64, nanos: i128) -> Result<Temporal, Error> {
186        let seconds = nanos.div_euclid(NANOS_PER_SECOND);
187        if !(-MAX_DURATION_SECONDS..=MAX_DURATION_SECONDS).contains(&seconds) {
188            return Err(range_err());
189        }
190        // `seconds` can equal ±2^63, one past `i64`; the average-length sum
191        // stays in i128 and the final `i64::try_from` rejects an out-of-range
192        // total, so the clamp only keeps the sum's own arithmetic in range.
193        let seconds = seconds.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
194        let average = i128::from(months) * AVG_SECONDS_PER_MONTH
195            + i128::from(days) * (NANOS_PER_DAY / NANOS_PER_SECOND)
196            + seconds;
197        i64::try_from(average).map_err(|_| range_err())?;
198        Ok(Temporal::Duration {
199            months,
200            days,
201            nanos,
202        })
203    }
204
205    /// [`Temporal::duration_checked`] with the strict stored-model bound for
206    /// producers whose arithmetic is exact (the ISO and pattern parsers, the
207    /// all-integer map constructor, negation and addition). Neo4j's duration
208    /// stores its sub-day part as an `i64` seconds field, so exactly `2^63`
209    /// seconds is not representable (`duration('PT9223372036854775808S')`
210    /// overflows); only the `f64` scaling path produces that image by
211    /// rounding `i64::MAX` and casts it back, which is why the shared seam
212    /// accepts it.
213    pub(crate) fn duration_checked_exact(
214        months: i64,
215        days: i64,
216        nanos: i128,
217    ) -> Result<Temporal, Error> {
218        if nanos.div_euclid(NANOS_PER_SECOND) > i128::from(i64::MAX) {
219            return Err(range_err());
220        }
221        Self::duration_checked(months, days, nanos)
222    }
223
224    pub fn kind_name(&self) -> &'static str {
225        self.kind().name()
226    }
227
228    /// Whether the value carries a calendar date — the one statement of the
229    /// capability partition, beside the type. The field policy
230    /// (`field_rules::check_sources`), the truncation granularity rule and
231    /// the part readers all read it, so no consumer keeps its own variant
232    /// list.
233    pub fn has_date(&self) -> bool {
234        matches!(
235            self,
236            Temporal::Date(_)
237                | Temporal::CivilDate { .. }
238                | Temporal::LocalDateTime(_)
239                | Temporal::CivilDateTime { .. }
240                | Temporal::DateTime { .. }
241        )
242    }
243
244    /// Whether the value carries a time of day (see [`Temporal::has_date`]).
245    pub fn has_time(&self) -> bool {
246        matches!(
247            self,
248            Temporal::LocalTime(_)
249                | Temporal::Time { .. }
250                | Temporal::LocalDateTime(_)
251                | Temporal::CivilDateTime { .. }
252                | Temporal::DateTime { .. }
253        )
254    }
255
256    /// Whether the value carries both halves (the `datetime` source field).
257    pub fn has_date_and_time(&self) -> bool {
258        self.has_date() && self.has_time()
259    }
260
261    pub fn iso_string(&self) -> String {
262        self.render(false)
263    }
264
265    /// The full-precision ISO rendering: [`Temporal::iso_string`] with
266    /// the time-of-day's seconds always present. The value layer's
267    /// temporal rendering policy for every string-producing surface —
268    /// `toString` (top-level, nested in a map or accepted list, or
269    /// through `toStringOrNull`) and the interpolated-string scalar
270    /// path — one rendering for one value, however it was built or
271    /// wherever it is embedded (ADR-0448).
272    pub fn full_seconds_string(&self) -> String {
273        self.render(true)
274    }
275
276    /// The one ISO renderer both public forms delegate to: identical
277    /// except for the time-of-day's seconds-omission rule
278    /// (`format_time`'s `%H:%M` truncation for a whole minute), which
279    /// `full_seconds` disables.
280    fn render(&self, full_seconds: bool) -> String {
281        match self {
282            Temporal::Date(d) => d.format("%Y-%m-%d").to_string(),
283            Temporal::CivilDate { year, month, day } => format_civil_date(*year, *month, *day),
284            Temporal::LocalTime(t) => format_time(*t, full_seconds),
285            Temporal::Time { time, offset } => {
286                format!(
287                    "{}{}",
288                    format_time(*time, full_seconds),
289                    format_zone_suffix(*offset, None)
290                )
291            }
292            Temporal::LocalDateTime(dt) => format_local_dt(*dt, full_seconds),
293            Temporal::CivilDateTime {
294                year,
295                month,
296                day,
297                time,
298            } => format!(
299                "{}T{}",
300                format_civil_date(*year, *month, *day),
301                format_time(*time, full_seconds)
302            ),
303            Temporal::DateTime { utc, offset, zone } => {
304                // A deliberate, stated fallback — not a silent one: the
305                // Bolt parameter decoders accept any i32 offset, so a
306                // crafted or extreme `utc + offset` can leave chrono's
307                // range (constructors cannot, parameters can); rendering
308                // has no error channel and must not panic on a decodable
309                // value, so the UTC wall clock renders beside the
310                // offset/zone suffix. (`local_of` is the identity
311                // helper's stricter form; render does not use it.)
312                let local = add_offset(*utc, *offset).unwrap_or(*utc);
313                format!(
314                    "{}{}",
315                    format_local_dt(local, full_seconds),
316                    format_zone_suffix(*offset, zone.as_deref())
317                )
318            }
319            Temporal::Duration {
320                months,
321                days,
322                nanos,
323            } => format_duration(*months, *days, *nanos),
324        }
325    }
326
327    /// One component accessor (`d.year`, `t.offsetMinutes`, `dur.months`).
328    /// The reference engine rejects a component the value's kind does not
329    /// carry, so [`component::read`] is the whole policy: the reader answers
330    /// a component its kind carries or the read is a typed error.
331    pub fn component(&self, key: &str) -> Result<Value, Error> {
332        component::read(self, key)
333    }
334
335    /// Cypher `=` between two values of the same temporal kind (`false` for
336    /// unlike kinds). The relation is deliberately *not* the ordering one:
337    ///
338    /// * `Time` — local time **and** offset, so `12:00+01:00` and `11:00Z`
339    ///   (the same instant) are different times, while `12:00Z` and
340    ///   `12:00+00:00` are the same.
341    /// * `DateTime` — local date-time **and** zone identity, so the two
342    ///   halves of a DST fall-back overlap (`02:30+02:00[Europe/Stockholm]`
343    ///   and `02:30+01:00[Europe/Stockholm]`) are equal even though they are
344    ///   different instants, while `[Europe/Stockholm]` never equals
345    ///   `+01:00` (`ZoneId`).
346    pub fn equals(&self, other: &Temporal) -> bool {
347        match (self, other) {
348            (Temporal::Date(a), Temporal::Date(b)) => a == b,
349            (
350                Temporal::CivilDate {
351                    year: ya,
352                    month: ma,
353                    day: da,
354                },
355                Temporal::CivilDate {
356                    year: yb,
357                    month: mb,
358                    day: db,
359                },
360            ) => (ya, ma, da) == (yb, mb, db),
361            (Temporal::LocalTime(a), Temporal::LocalTime(b)) => a == b,
362            (
363                Temporal::Time {
364                    time: a,
365                    offset: oa,
366                },
367                Temporal::Time {
368                    time: b,
369                    offset: ob,
370                },
371            ) => a == b && oa == ob,
372            (Temporal::LocalDateTime(a), Temporal::LocalDateTime(b)) => a == b,
373            (
374                Temporal::CivilDateTime {
375                    year: ya,
376                    month: ma,
377                    day: da,
378                    time: ta,
379                },
380                Temporal::CivilDateTime {
381                    year: yb,
382                    month: mb,
383                    day: db,
384                    time: tb,
385                },
386            ) => (ya, ma, da, ta) == (yb, mb, db, tb),
387            (Temporal::DateTime { .. }, Temporal::DateTime { .. }) => {
388                self.datetime_eq_identity() == other.datetime_eq_identity()
389            }
390            (
391                Temporal::Duration {
392                    months: am,
393                    days: ad,
394                    nanos: an,
395                },
396                Temporal::Duration {
397                    months: bm,
398                    days: bd,
399                    nanos: bn,
400                },
401            ) => (am, ad, an) == (bm, bd, bn),
402            _ => false,
403        }
404    }
405
406    /// The two components [`Self::equals`] compares for a zoned `DateTime`:
407    /// its local wall clock and its [`ZoneId`]. `None` for every other
408    /// temporal kind. This is the `=` identity only; the property index,
409    /// uniqueness probe and `MERGE` key the finer equivalence identity
410    /// (UTC instant plus zone), so the two halves of a DST fall-back overlap
411    /// are equal yet separate index entries (LABS-785).
412    pub fn datetime_eq_identity(&self) -> Option<(NaiveDateTime, ZoneId)> {
413        match self {
414            Temporal::DateTime { utc, offset, zone } => Some((
415                local_of(*utc, *offset),
416                ZoneId::of(zone.as_deref(), *offset),
417            )),
418            _ => None,
419        }
420    }
421
422    /// Three-valued ordering for `<`, `>`, `<=`, `>=` (`None` is the null
423    /// result of comparing incomparable values):
424    ///
425    /// * `Time` — UTC nanos-of-day (not wrapped at midnight, so it can be
426    ///   negative), then the offset, so two times at the same instant still
427    ///   order.
428    /// * `DateTime` — instant (nanos included), then offset, then a plain
429    ///   offset before a named zone, then the zone name.
430    /// * `Duration` — not orderable at all; only `=` is defined for it.
431    pub fn compare(&self, other: &Temporal) -> Option<Ordering> {
432        match (self, other) {
433            (Temporal::Date(a), Temporal::Date(b)) => Some(a.cmp(b)),
434            (
435                Temporal::CivilDate {
436                    year: ya,
437                    month: ma,
438                    day: da,
439                },
440                Temporal::CivilDate {
441                    year: yb,
442                    month: mb,
443                    day: db,
444                },
445            ) => Some((ya, ma, da).cmp(&(yb, mb, db))),
446            (Temporal::LocalTime(a), Temporal::LocalTime(b)) => Some(a.cmp(b)),
447            (Temporal::LocalDateTime(a), Temporal::LocalDateTime(b)) => Some(a.cmp(b)),
448            (
449                Temporal::Time {
450                    time: a,
451                    offset: oa,
452                },
453                Temporal::Time {
454                    time: b,
455                    offset: ob,
456                },
457            ) => Some(
458                utc_time_nanos(*a, *oa)
459                    .cmp(&utc_time_nanos(*b, *ob))
460                    .then(oa.cmp(ob)),
461            ),
462            (
463                Temporal::DateTime {
464                    utc: ua,
465                    offset: oa,
466                    zone: za,
467                },
468                Temporal::DateTime {
469                    utc: ub,
470                    offset: ob,
471                    zone: zb,
472                },
473            ) => Some(
474                ua.cmp(ub)
475                    .then_with(|| oa.cmp(ob))
476                    // A named (IANA) zone sorts after the plain offset it
477                    // equals, by name: `None < Some(_)`.
478                    .then_with(|| zone_region(za.as_deref()).cmp(&zone_region(zb.as_deref()))),
479            ),
480            (Temporal::Duration { .. }, Temporal::Duration { .. }) => None,
481            _ => None,
482        }
483    }
484
485    /// `IS SAME INSTANT` (Cypher 25 chronological comparison): the UTC
486    /// instant for the two zoned kinds — `DateTime` by its stored UTC half,
487    /// `Time` by [`utc_time_nanos`] — and [`Self::equals`] for the non-zoned
488    /// kinds, whose clock already *is* the instant. Unlike kinds are `false`
489    /// here too; the operator's mixed-kind null/false policy stays with the
490    /// caller, this relation only answers for a comparable pair.
491    pub fn same_instant(&self, other: &Temporal) -> bool {
492        match (self, other) {
493            (Temporal::DateTime { utc: a, .. }, Temporal::DateTime { utc: b, .. }) => a == b,
494            (
495                Temporal::Time {
496                    time: a,
497                    offset: oa,
498                },
499                Temporal::Time {
500                    time: b,
501                    offset: ob,
502                },
503            ) => utc_time_nanos(*a, *oa) == utc_time_nanos(*b, *ob),
504            _ => self.equals(other),
505        }
506    }
507
508    /// `IS BEFORE`/`IS AFTER` ordering (Cypher 25): the instant alone for
509    /// the zoned kinds — [`Self::compare`] also ranks equal instants by
510    /// offset and then zone, which a chronological operator must not — and
511    /// [`Self::compare`] for every other kind (durations stay unordered:
512    /// `None`).
513    pub fn instant_ordering(&self, other: &Temporal) -> Option<Ordering> {
514        match (self, other) {
515            (Temporal::DateTime { utc: a, .. }, Temporal::DateTime { utc: b, .. }) => {
516                Some(a.cmp(b))
517            }
518            (
519                Temporal::Time {
520                    time: a,
521                    offset: oa,
522                },
523                Temporal::Time {
524                    time: b,
525                    offset: ob,
526                },
527            ) => Some(utc_time_nanos(*a, *oa).cmp(&utc_time_nanos(*b, *ob))),
528            _ => self.compare(other),
529        }
530    }
531
532    /// Total order for `ORDER BY`, `min` and `max`: [`Self::compare`] where it
533    /// is defined, the `(months, days, nanos)` triple for durations (which
534    /// equality alone cannot rank), and `Equal` across unlike kinds — the
535    /// callers keep unlike temporals distinct by the value type rank.
536    pub(crate) fn total_cmp(&self, other: &Temporal) -> Ordering {
537        match (self, other) {
538            (
539                Temporal::Duration {
540                    months: am,
541                    days: ad,
542                    nanos: an,
543                },
544                Temporal::Duration {
545                    months: bm,
546                    days: bd,
547                    nanos: bn,
548                },
549            ) => (am, ad, an).cmp(&(bm, bd, bn)),
550            _ => self.compare(other).unwrap_or(Ordering::Equal),
551        }
552    }
553}
554
555impl fmt::Display for Temporal {
556    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
557        write!(f, "{}", self.iso_string())
558    }
559}
560
561/// The signed, zero-padded civil-date form both civil variants render:
562/// a negative year is zero-padded to nine digits behind the sign.
563fn format_civil_date(year: i64, month: u32, day: u32) -> String {
564    if year < 0 {
565        format!("-{year:09}-{month:02}-{day:02}", year = year.unsigned_abs())
566    } else {
567        format!("+{year}-{month:02}-{day:02}")
568    }
569}
570
571/// The time-of-day renderer: `full_seconds` disables the whole-minute
572/// truncation (`%H:%M`) — the one place the seconds-omission fact
573/// lives, consulted by both of `render`'s modes (ADR-0448).
574fn format_time(t: NaiveTime, full_seconds: bool) -> String {
575    let n = t.nanosecond();
576    if n == 0 {
577        if t.second() == 0 && !full_seconds {
578            t.format("%H:%M").to_string()
579        } else {
580            t.format("%H:%M:%S").to_string()
581        }
582    } else {
583        let s = format!("{n:09}");
584        let trim = s.trim_end_matches('0');
585        format!(
586            "{:02}:{:02}:{:02}.{}",
587            t.hour(),
588            t.minute(),
589            t.second(),
590            trim
591        )
592    }
593}
594
595fn format_local_dt(dt: NaiveDateTime, full_seconds: bool) -> String {
596    format!(
597        "{}T{}",
598        dt.date().format("%Y-%m-%d"),
599        format_time(dt.time(), full_seconds)
600    )
601}
602
603fn format_offset(secs: i32) -> String {
604    let sign = if secs >= 0 { '+' } else { '-' };
605    let abs = secs.unsigned_abs();
606    let h = abs / 3600;
607    let m = (abs % 3600) / 60;
608    let s = abs % 60;
609    if s != 0 {
610        format!("{sign}{h:02}:{m:02}:{s:02}")
611    } else if m == 0 {
612        format!("{sign}{h:02}:00")
613    } else {
614        format!("{sign}{h:02}:{m:02}")
615    }
616}
617
618fn format_zone_suffix(offset: i32, zone: Option<&str>) -> String {
619    // One classification, one rule: the IANA arm brackets its region name
620    // over the offset-only spelling; `Z` is UTC; every offset spelling
621    // renders through the one zero-offset rule.
622    match zone.map(zone_kind) {
623        Some(ZoneSpec::Iana(name)) => format!("{}[{name}]", format_zone_offset(offset)),
624        Some(ZoneSpec::Utc) => "Z".into(),
625        Some(ZoneSpec::Fixed(_) | ZoneSpec::Prefixed(_) | ZoneSpec::Other(_)) | None => {
626            format_zone_offset(offset)
627        }
628    }
629}
630
631/// The offset-only spelling a zoneless clock value renders: `Z` at zero, the
632/// numeric offset otherwise. The one zero-offset rule, shared by the ISO
633/// suffix ([`format_zone_suffix`]) and the `timezone`/`offset` accessors so
634/// one stored offset has one spelling.
635fn format_zone_offset(offset: i32) -> String {
636    if offset == 0 {
637        "Z".into()
638    } else {
639        format_offset(offset)
640    }
641}
642
643fn format_duration(months: i64, days: i64, nanos: i128) -> String {
644    if months == 0 && days == 0 && nanos == 0 {
645        return "PT0S".into();
646    }
647    let mut s = String::from("P");
648    let y = months / 12;
649    let mo = months % 12;
650    if y != 0 {
651        s.push_str(&format!("{y}Y"));
652    }
653    if mo != 0 {
654        s.push_str(&format!("{mo}M"));
655    }
656    if days != 0 {
657        s.push_str(&format!("{days}D"));
658    }
659    let neg_t = nanos < 0;
660    let mut n = nanos.unsigned_abs();
661    let hours = n / 3_600_000_000_000;
662    n %= 3_600_000_000_000;
663    let mins = n / 60_000_000_000;
664    n %= 60_000_000_000;
665    let secs = n / 1_000_000_000;
666    let nano = n % 1_000_000_000;
667    if hours != 0 || mins != 0 || secs != 0 || nano != 0 {
668        s.push('T');
669        let sign = if neg_t { "-" } else { "" };
670        if hours != 0 {
671            s.push_str(&format!("{sign}{hours}H"));
672        }
673        if mins != 0 {
674            s.push_str(&format!("{sign}{mins}M"));
675        }
676        if secs != 0 || nano != 0 {
677            if nano == 0 {
678                s.push_str(&format!("{sign}{secs}S"));
679            } else {
680                let frac = format!("{nano:09}").trim_end_matches('0').to_string();
681                s.push_str(&format!("{sign}{secs}.{frac}S"));
682            }
683        }
684    }
685    s
686}
687
688fn time_to_nanos(t: NaiveTime) -> i64 {
689    t.num_seconds_from_midnight() as i64 * 1_000_000_000 + t.nanosecond() as i64
690}
691
692/// Nanoseconds of the UTC clock time a `Time` denotes. Deliberately *not*
693/// wrapped at midnight: an offset can push the wall clock out of the day, and
694/// the ordering contract is this signed value plus the offset.
695pub(super) fn utc_time_nanos(t: NaiveTime, offset: i32) -> i64 {
696    time_to_nanos(t) - i64::from(offset) * 1_000_000_000
697}
698
699/// The wall clock a zoned instant reads at (`utc + offset`). Constructors
700/// keep the sum inside chrono's range, but the Bolt parameter decoders
701/// accept any i32 offset (the render path's comment at the `DateTime` arm
702/// documents this input class), and equality bucketing has no error
703/// channel — so an out-of-range sum degrades to the UTC wall clock, the
704/// same stated fallback render uses, instead of panicking. Deterministic
705/// per payload, so `a = b` still implies one bucket.
706fn local_of(utc: NaiveDateTime, offset: i32) -> NaiveDateTime {
707    add_offset(utc, offset).unwrap_or(utc)
708}
709
710/// `n` is always a within-day nanosecond count (rem_euclid at the call sites),
711/// so the conversion is infallible in practice; fall back instead of unwrap.
712fn nanos_to_time(n: i64) -> NaiveTime {
713    let secs = (n / 1_000_000_000) as u32;
714    let nano = (n % 1_000_000_000) as u32;
715    NaiveTime::from_num_seconds_from_midnight_opt(secs, nano).unwrap_or(NaiveTime::MIN)
716}
717
718/// Error returned when a temporal computation overflows the representable
719/// range (chrono dates ±262143 years, i64 duration months/days, i128 nanos).
720/// The honest contract for out-of-range results is an error, never a panic.
721pub(super) fn range_err() -> Error {
722    Error::ty("temporal value out of range")
723}
724
725/// The one spelling of a duration arithmetic overflow: Neo4j's 22N28
726/// (`ArithmeticException`) text, naming the operation that overflowed
727/// (`duration()` for construction, the field for pattern formatting).
728pub(super) fn duration_overflow_err(operation: &str) -> Error {
729    Error::ty(format!(
730        "the result of the operation '{operation}' has caused an overflow"
731    ))
732}
733
734/// Narrow one i128 lane total to the i64 a duration component stores.
735/// Components that overflow individually but cancel stay representable because
736/// the lanes are summed before this check (Neo4j's exact wide arithmetic).
737pub(super) fn checked_lane(value: i128, operation: &str) -> crate::Result<i64> {
738    i64::try_from(value).map_err(|_| duration_overflow_err(operation))
739}
740
741/// The `Temporal` payload a field map holds under `k`, or `None` when the
742/// key is absent or non-temporal. Shared by the constructors and the zone
743/// resolution (`construct.rs`, `zone.rs`); the scalar extraction is the
744/// canonical [`Value::as_temporal`]. The field *policy* never reads a source
745/// field through this — a present non-temporal value is a typed rejection
746/// there (`field_rules`), not an absent field.
747pub(super) fn map_temporal<'a>(
748    map: &'a std::collections::BTreeMap<String, Value>,
749    k: &str,
750) -> Option<&'a Temporal> {
751    map.get(k).and_then(Value::as_temporal)
752}
753
754/// The value a `(spelling, value)` table names, or `None` — the one keyed
755/// table lookup behind every `from_name` ([`clock::ClockKind`],
756/// [`component::Component`], its duration sibling), so no table is walked by
757/// a hand-rolled copy.
758pub(super) fn lookup<T: Copy>(table: &[(&str, T)], name: &str) -> Option<T> {
759    table
760        .iter()
761        .find(|(spelling, _)| *spelling == name)
762        .map(|(_, value)| *value)
763}
764
765/// f64 → i128 with a range error; 1e38 is comfortably below i128::MAX ≈ 1.7e38.
766pub(super) fn f64_to_i128_range(v: f64) -> Result<i128, Error> {
767    if v.is_finite() && v.abs() < 1.0e38 {
768        Ok(v as i128)
769    } else {
770        Err(range_err())
771    }
772}
773
774/// f64 → i64 with a range error — Neo4j's `DurationValue.safeDoubleToLong`
775/// seam: the stored month and day fields are `i64`, so an out-of-range
776/// fraction fold is a typed range error, never a saturating cast.
777pub(super) fn f64_to_i64_range(v: f64) -> Result<i64, Error> {
778    i64::try_from(f64_to_i128_range(v)?).map_err(|_| range_err())
779}
780
781fn weekday_from_i(i: i64) -> Weekday {
782    // `i.rem_euclid(7)` is total (unlike `(i - 1).rem_euclid(7)`, which
783    // overflows at i64::MIN) and selects the same weekday for every input:
784    // 1..=6 -> Mon..Sat, 0 -> Sun.
785    match i.rem_euclid(7) {
786        1 => Weekday::Mon,
787        2 => Weekday::Tue,
788        3 => Weekday::Wed,
789        4 => Weekday::Thu,
790        5 => Weekday::Fri,
791        6 => Weekday::Sat,
792        _ => Weekday::Sun,
793    }
794}
795
796/// The duration field vocabulary — fields, tiers, unit scales and the
797/// average-month/overflow facts — lives in [`field`]; these names are the
798/// facade the sibling modules read through `super::`.
799use field::{
800    DurationField, AVG_NANOS_PER_MONTH, AVG_SECONDS_PER_MONTH, DAYS_PER_WEEK, MAX_DURATION_SECONDS,
801    MONTHS_PER_QUARTER, MONTHS_PER_YEAR, NANOS_PER_DAY, NANOS_PER_HOUR, NANOS_PER_MICRO,
802    NANOS_PER_MILLI, NANOS_PER_MINUTE, NANOS_PER_SECOND, SECONDS_PER_HOUR, SECONDS_PER_MINUTE,
803};