relate-core 1.0.0

Core values, errors, and IDs for Relate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! OpenCypher temporal values (ADR-0021).

use std::cmp::Ordering;
use std::fmt;

use chrono::{NaiveDate, NaiveDateTime, NaiveTime, Timelike, Weekday};

use crate::{Error, Value};

mod arith;
mod between;
mod clock;
mod component;
mod construct;
mod duration;
mod duration_pattern;
mod exact;
mod field;
mod field_rules;
mod format;
mod parse;
mod pattern;
#[cfg(test)]
mod test_support;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_arith;
#[cfg(test)]
mod tests_between;
#[cfg(test)]
mod tests_clock;
#[cfg(test)]
mod tests_duration;
#[cfg(test)]
mod tests_fields;
#[cfg(test)]
mod tests_pattern;
#[cfg(test)]
mod tests_ranges;
mod truncate;
mod zone;

use zone::{add_offset, zone_kind, ZoneSpec};

pub use arith::{
    add_duration, civil_epoch_days, civil_from_days, negate_duration, scale_duration, sub_duration,
};
pub use between::{duration_between, duration_between_unit, BetweenUnit};
pub use clock::{
    clock_access, clock_spelling, clock_spelling_rows, clock_spellings, construct_clock,
    now_epoch_millis, now_utc_dt, ClockKind, ClockMode, QueryClockGuard,
};
pub use construct::{
    accepts_pattern, construct_date, construct_datetime, construct_duration,
    construct_localdatetime, construct_localtime, construct_named, construct_time, is_constructor,
    samples_clock,
};
pub use format::format_pattern;
pub use parse::{
    datetime_from_epoch, datetime_from_epoch_millis, padded_iso_date_value, parse_iso,
    parse_pattern,
};
pub use truncate::{truncate, truncate_now};
pub use zone::{zone_offset_at, zone_offset_at_utc, zone_region, ZoneError, MAX_OFFSET_SECONDS};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Temporal {
    Date(NaiveDate),
    /// Out-of-range proleptic date (TCK ±999999999).
    CivilDate {
        year: i64,
        month: u32,
        day: u32,
    },
    LocalTime(NaiveTime),
    Time {
        time: NaiveTime,
        offset: i32,
    },
    LocalDateTime(NaiveDateTime),
    CivilDateTime {
        year: i64,
        month: u32,
        day: u32,
        time: NaiveTime,
    },
    DateTime {
        utc: NaiveDateTime,
        offset: i32,
        zone: Option<String>,
    },
    Duration {
        months: i64,
        days: i64,
        nanos: i128,
    },
}

/// The six temporal type kinds, one per Cypher type name — the variant
/// grouping the type-name spelling and the ORDER BY sub-ranks both key
/// off, so it exists in one place. Declared in the ORDER BY rank order:
/// ZONED DATETIME < LOCAL DATETIME < DATE < ZONED TIME < LOCAL TIME <
/// DURATION (live Neo4j 2026.10.1, value-independent), so a kind's
/// discriminant is that rank's offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TemporalKind {
    DateTime,
    LocalDateTime,
    Date,
    Time,
    LocalTime,
    Duration,
}

impl TemporalKind {
    /// The kind's lowercase wire name — the `Temporal::kind_name`
    /// spelling, owned by the kind so the variant partition has one
    /// owner.
    pub(crate) fn name(self) -> &'static str {
        match self {
            TemporalKind::DateTime => "datetime",
            TemporalKind::LocalDateTime => "localdatetime",
            TemporalKind::Date => "date",
            TemporalKind::Time => "time",
            TemporalKind::LocalTime => "localtime",
            TemporalKind::Duration => "duration",
        }
    }
}

impl Temporal {
    /// This value's type kind — the one spelling of the variant grouping
    /// (the civil out-of-range forms share their kind's name).
    pub(crate) fn kind(&self) -> TemporalKind {
        match self {
            Temporal::DateTime { .. } => TemporalKind::DateTime,
            Temporal::LocalDateTime(_) | Temporal::CivilDateTime { .. } => {
                TemporalKind::LocalDateTime
            }
            Temporal::Date(_) | Temporal::CivilDate { .. } => TemporalKind::Date,
            Temporal::Time { .. } => TemporalKind::Time,
            Temporal::LocalTime(_) => TemporalKind::LocalTime,
            Temporal::Duration { .. } => TemporalKind::Duration,
        }
    }
}

/// The zone half of a `DateTime`'s equality identity (TCK TemporalCompare):
/// an IANA zone is identified by its name — so the two halves of a DST
/// fall-back overlap stay equal — and every other spelling (`Z`, `+00:00`,
/// `UTC`, …) by the UTC offset it denotes, so `Z` equals `+00:00` while a
/// named zone never equals the offset it happens to denote.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ZoneId {
    Named(String),
    Offset(i32),
}

impl ZoneId {
    /// The identity of a `DateTime`'s `zone` at `offset`.
    pub fn of(zone: Option<&str>, offset: i32) -> ZoneId {
        match zone_region(zone) {
            Some(name) => ZoneId::Named(name.to_string()),
            None => ZoneId::Offset(offset),
        }
    }
}

impl Temporal {
    /// The one place a duration's stored `(months, days, nanos)` triple is
    /// assembled, and the one place its representability bound lives: the
    /// sub-day part must fit Neo4j's `i64` seconds field (inclusive of
    /// `2^63`, the `f64` image of `i64::MAX` that the scaling path still
    /// casts back), and the duration's average length in seconds
    /// (`months * AVG_SECONDS_PER_MONTH + days * 86400 + seconds`) must fit
    /// an `i64` (`DurationValue.assertNoOverflow`). Every producer — the ISO
    /// numeral parser, the pattern parser, the map constructor, scaling and
    /// duration addition — builds through this seam, so one value is
    /// accepted or rejected regardless of how it was spelled; a value past
    /// the bound is Neo4j's interval-field overflow, never a silently larger
    /// duration. Neo4j's constructor enforces the same bound (verified
    /// against Neo4j 5: `duration({months: 4000000000000})` errors, while the
    /// same value via `* 1.0` errors identically).
    pub(crate) fn duration_checked(months: i64, days: i64, nanos: i128) -> Result<Temporal, Error> {
        let seconds = nanos.div_euclid(NANOS_PER_SECOND);
        if !(-MAX_DURATION_SECONDS..=MAX_DURATION_SECONDS).contains(&seconds) {
            return Err(range_err());
        }
        // `seconds` can equal ±2^63, one past `i64`; the average-length sum
        // stays in i128 and the final `i64::try_from` rejects an out-of-range
        // total, so the clamp only keeps the sum's own arithmetic in range.
        let seconds = seconds.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
        let average = i128::from(months) * AVG_SECONDS_PER_MONTH
            + i128::from(days) * (NANOS_PER_DAY / NANOS_PER_SECOND)
            + seconds;
        i64::try_from(average).map_err(|_| range_err())?;
        Ok(Temporal::Duration {
            months,
            days,
            nanos,
        })
    }

    /// [`Temporal::duration_checked`] with the strict stored-model bound for
    /// producers whose arithmetic is exact (the ISO and pattern parsers, the
    /// all-integer map constructor, negation and addition). Neo4j's duration
    /// stores its sub-day part as an `i64` seconds field, so exactly `2^63`
    /// seconds is not representable (`duration('PT9223372036854775808S')`
    /// overflows); only the `f64` scaling path produces that image by
    /// rounding `i64::MAX` and casts it back, which is why the shared seam
    /// accepts it.
    pub(crate) fn duration_checked_exact(
        months: i64,
        days: i64,
        nanos: i128,
    ) -> Result<Temporal, Error> {
        if nanos.div_euclid(NANOS_PER_SECOND) > i128::from(i64::MAX) {
            return Err(range_err());
        }
        Self::duration_checked(months, days, nanos)
    }

    pub fn kind_name(&self) -> &'static str {
        self.kind().name()
    }

    /// Whether the value carries a calendar date — the one statement of the
    /// capability partition, beside the type. The field policy
    /// (`field_rules::check_sources`), the truncation granularity rule and
    /// the part readers all read it, so no consumer keeps its own variant
    /// list.
    pub fn has_date(&self) -> bool {
        matches!(
            self,
            Temporal::Date(_)
                | Temporal::CivilDate { .. }
                | Temporal::LocalDateTime(_)
                | Temporal::CivilDateTime { .. }
                | Temporal::DateTime { .. }
        )
    }

    /// Whether the value carries a time of day (see [`Temporal::has_date`]).
    pub fn has_time(&self) -> bool {
        matches!(
            self,
            Temporal::LocalTime(_)
                | Temporal::Time { .. }
                | Temporal::LocalDateTime(_)
                | Temporal::CivilDateTime { .. }
                | Temporal::DateTime { .. }
        )
    }

    /// Whether the value carries both halves (the `datetime` source field).
    pub fn has_date_and_time(&self) -> bool {
        self.has_date() && self.has_time()
    }

    pub fn iso_string(&self) -> String {
        self.render(false)
    }

    /// The full-precision ISO rendering: [`Temporal::iso_string`] with
    /// the time-of-day's seconds always present. The value layer's
    /// temporal rendering policy for every string-producing surface —
    /// `toString` (top-level, nested in a map or accepted list, or
    /// through `toStringOrNull`) and the interpolated-string scalar
    /// path — one rendering for one value, however it was built or
    /// wherever it is embedded (ADR-0448).
    pub fn full_seconds_string(&self) -> String {
        self.render(true)
    }

    /// The one ISO renderer both public forms delegate to: identical
    /// except for the time-of-day's seconds-omission rule
    /// (`format_time`'s `%H:%M` truncation for a whole minute), which
    /// `full_seconds` disables.
    fn render(&self, full_seconds: bool) -> String {
        match self {
            Temporal::Date(d) => d.format("%Y-%m-%d").to_string(),
            Temporal::CivilDate { year, month, day } => format_civil_date(*year, *month, *day),
            Temporal::LocalTime(t) => format_time(*t, full_seconds),
            Temporal::Time { time, offset } => {
                format!(
                    "{}{}",
                    format_time(*time, full_seconds),
                    format_zone_suffix(*offset, None)
                )
            }
            Temporal::LocalDateTime(dt) => format_local_dt(*dt, full_seconds),
            Temporal::CivilDateTime {
                year,
                month,
                day,
                time,
            } => format!(
                "{}T{}",
                format_civil_date(*year, *month, *day),
                format_time(*time, full_seconds)
            ),
            Temporal::DateTime { utc, offset, zone } => {
                // A deliberate, stated fallback — not a silent one: the
                // Bolt parameter decoders accept any i32 offset, so a
                // crafted or extreme `utc + offset` can leave chrono's
                // range (constructors cannot, parameters can); rendering
                // has no error channel and must not panic on a decodable
                // value, so the UTC wall clock renders beside the
                // offset/zone suffix. (`local_of` is the identity
                // helper's stricter form; render does not use it.)
                let local = add_offset(*utc, *offset).unwrap_or(*utc);
                format!(
                    "{}{}",
                    format_local_dt(local, full_seconds),
                    format_zone_suffix(*offset, zone.as_deref())
                )
            }
            Temporal::Duration {
                months,
                days,
                nanos,
            } => format_duration(*months, *days, *nanos),
        }
    }

    /// One component accessor (`d.year`, `t.offsetMinutes`, `dur.months`).
    /// The reference engine rejects a component the value's kind does not
    /// carry, so [`component::read`] is the whole policy: the reader answers
    /// a component its kind carries or the read is a typed error.
    pub fn component(&self, key: &str) -> Result<Value, Error> {
        component::read(self, key)
    }

    /// Cypher `=` between two values of the same temporal kind (`false` for
    /// unlike kinds). The relation is deliberately *not* the ordering one:
    ///
    /// * `Time` — local time **and** offset, so `12:00+01:00` and `11:00Z`
    ///   (the same instant) are different times, while `12:00Z` and
    ///   `12:00+00:00` are the same.
    /// * `DateTime` — local date-time **and** zone identity, so the two
    ///   halves of a DST fall-back overlap (`02:30+02:00[Europe/Stockholm]`
    ///   and `02:30+01:00[Europe/Stockholm]`) are equal even though they are
    ///   different instants, while `[Europe/Stockholm]` never equals
    ///   `+01:00` (`ZoneId`).
    pub fn equals(&self, other: &Temporal) -> bool {
        match (self, other) {
            (Temporal::Date(a), Temporal::Date(b)) => a == b,
            (
                Temporal::CivilDate {
                    year: ya,
                    month: ma,
                    day: da,
                },
                Temporal::CivilDate {
                    year: yb,
                    month: mb,
                    day: db,
                },
            ) => (ya, ma, da) == (yb, mb, db),
            (Temporal::LocalTime(a), Temporal::LocalTime(b)) => a == b,
            (
                Temporal::Time {
                    time: a,
                    offset: oa,
                },
                Temporal::Time {
                    time: b,
                    offset: ob,
                },
            ) => a == b && oa == ob,
            (Temporal::LocalDateTime(a), Temporal::LocalDateTime(b)) => a == b,
            (
                Temporal::CivilDateTime {
                    year: ya,
                    month: ma,
                    day: da,
                    time: ta,
                },
                Temporal::CivilDateTime {
                    year: yb,
                    month: mb,
                    day: db,
                    time: tb,
                },
            ) => (ya, ma, da, ta) == (yb, mb, db, tb),
            (Temporal::DateTime { .. }, Temporal::DateTime { .. }) => {
                self.datetime_eq_identity() == other.datetime_eq_identity()
            }
            (
                Temporal::Duration {
                    months: am,
                    days: ad,
                    nanos: an,
                },
                Temporal::Duration {
                    months: bm,
                    days: bd,
                    nanos: bn,
                },
            ) => (am, ad, an) == (bm, bd, bn),
            _ => false,
        }
    }

    /// The two components [`Self::equals`] compares for a zoned `DateTime`:
    /// its local wall clock and its [`ZoneId`]. `None` for every other
    /// temporal kind. This is the `=` identity only; the property index,
    /// uniqueness probe and `MERGE` key the finer equivalence identity
    /// (UTC instant plus zone), so the two halves of a DST fall-back overlap
    /// are equal yet separate index entries (LABS-785).
    pub fn datetime_eq_identity(&self) -> Option<(NaiveDateTime, ZoneId)> {
        match self {
            Temporal::DateTime { utc, offset, zone } => Some((
                local_of(*utc, *offset),
                ZoneId::of(zone.as_deref(), *offset),
            )),
            _ => None,
        }
    }

    /// Three-valued ordering for `<`, `>`, `<=`, `>=` (`None` is the null
    /// result of comparing incomparable values):
    ///
    /// * `Time` — UTC nanos-of-day (not wrapped at midnight, so it can be
    ///   negative), then the offset, so two times at the same instant still
    ///   order.
    /// * `DateTime` — instant (nanos included), then offset, then a plain
    ///   offset before a named zone, then the zone name.
    /// * `Duration` — not orderable at all; only `=` is defined for it.
    pub fn compare(&self, other: &Temporal) -> Option<Ordering> {
        match (self, other) {
            (Temporal::Date(a), Temporal::Date(b)) => Some(a.cmp(b)),
            (
                Temporal::CivilDate {
                    year: ya,
                    month: ma,
                    day: da,
                },
                Temporal::CivilDate {
                    year: yb,
                    month: mb,
                    day: db,
                },
            ) => Some((ya, ma, da).cmp(&(yb, mb, db))),
            (Temporal::LocalTime(a), Temporal::LocalTime(b)) => Some(a.cmp(b)),
            (Temporal::LocalDateTime(a), Temporal::LocalDateTime(b)) => Some(a.cmp(b)),
            (
                Temporal::Time {
                    time: a,
                    offset: oa,
                },
                Temporal::Time {
                    time: b,
                    offset: ob,
                },
            ) => Some(
                utc_time_nanos(*a, *oa)
                    .cmp(&utc_time_nanos(*b, *ob))
                    .then(oa.cmp(ob)),
            ),
            (
                Temporal::DateTime {
                    utc: ua,
                    offset: oa,
                    zone: za,
                },
                Temporal::DateTime {
                    utc: ub,
                    offset: ob,
                    zone: zb,
                },
            ) => Some(
                ua.cmp(ub)
                    .then_with(|| oa.cmp(ob))
                    // A named (IANA) zone sorts after the plain offset it
                    // equals, by name: `None < Some(_)`.
                    .then_with(|| zone_region(za.as_deref()).cmp(&zone_region(zb.as_deref()))),
            ),
            (Temporal::Duration { .. }, Temporal::Duration { .. }) => None,
            _ => None,
        }
    }

    /// `IS SAME INSTANT` (Cypher 25 chronological comparison): the UTC
    /// instant for the two zoned kinds — `DateTime` by its stored UTC half,
    /// `Time` by [`utc_time_nanos`] — and [`Self::equals`] for the non-zoned
    /// kinds, whose clock already *is* the instant. Unlike kinds are `false`
    /// here too; the operator's mixed-kind null/false policy stays with the
    /// caller, this relation only answers for a comparable pair.
    pub fn same_instant(&self, other: &Temporal) -> bool {
        match (self, other) {
            (Temporal::DateTime { utc: a, .. }, Temporal::DateTime { utc: b, .. }) => a == b,
            (
                Temporal::Time {
                    time: a,
                    offset: oa,
                },
                Temporal::Time {
                    time: b,
                    offset: ob,
                },
            ) => utc_time_nanos(*a, *oa) == utc_time_nanos(*b, *ob),
            _ => self.equals(other),
        }
    }

    /// `IS BEFORE`/`IS AFTER` ordering (Cypher 25): the instant alone for
    /// the zoned kinds — [`Self::compare`] also ranks equal instants by
    /// offset and then zone, which a chronological operator must not — and
    /// [`Self::compare`] for every other kind (durations stay unordered:
    /// `None`).
    pub fn instant_ordering(&self, other: &Temporal) -> Option<Ordering> {
        match (self, other) {
            (Temporal::DateTime { utc: a, .. }, Temporal::DateTime { utc: b, .. }) => {
                Some(a.cmp(b))
            }
            (
                Temporal::Time {
                    time: a,
                    offset: oa,
                },
                Temporal::Time {
                    time: b,
                    offset: ob,
                },
            ) => Some(utc_time_nanos(*a, *oa).cmp(&utc_time_nanos(*b, *ob))),
            _ => self.compare(other),
        }
    }

    /// Total order for `ORDER BY`, `min` and `max`: [`Self::compare`] where it
    /// is defined, the `(months, days, nanos)` triple for durations (which
    /// equality alone cannot rank), and `Equal` across unlike kinds — the
    /// callers keep unlike temporals distinct by the value type rank.
    pub(crate) fn total_cmp(&self, other: &Temporal) -> Ordering {
        match (self, other) {
            (
                Temporal::Duration {
                    months: am,
                    days: ad,
                    nanos: an,
                },
                Temporal::Duration {
                    months: bm,
                    days: bd,
                    nanos: bn,
                },
            ) => (am, ad, an).cmp(&(bm, bd, bn)),
            _ => self.compare(other).unwrap_or(Ordering::Equal),
        }
    }
}

impl fmt::Display for Temporal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.iso_string())
    }
}

/// The signed, zero-padded civil-date form both civil variants render:
/// a negative year is zero-padded to nine digits behind the sign.
fn format_civil_date(year: i64, month: u32, day: u32) -> String {
    if year < 0 {
        format!("-{year:09}-{month:02}-{day:02}", year = year.unsigned_abs())
    } else {
        format!("+{year}-{month:02}-{day:02}")
    }
}

/// The time-of-day renderer: `full_seconds` disables the whole-minute
/// truncation (`%H:%M`) — the one place the seconds-omission fact
/// lives, consulted by both of `render`'s modes (ADR-0448).
fn format_time(t: NaiveTime, full_seconds: bool) -> String {
    let n = t.nanosecond();
    if n == 0 {
        if t.second() == 0 && !full_seconds {
            t.format("%H:%M").to_string()
        } else {
            t.format("%H:%M:%S").to_string()
        }
    } else {
        let s = format!("{n:09}");
        let trim = s.trim_end_matches('0');
        format!(
            "{:02}:{:02}:{:02}.{}",
            t.hour(),
            t.minute(),
            t.second(),
            trim
        )
    }
}

fn format_local_dt(dt: NaiveDateTime, full_seconds: bool) -> String {
    format!(
        "{}T{}",
        dt.date().format("%Y-%m-%d"),
        format_time(dt.time(), full_seconds)
    )
}

fn format_offset(secs: i32) -> String {
    let sign = if secs >= 0 { '+' } else { '-' };
    let abs = secs.unsigned_abs();
    let h = abs / 3600;
    let m = (abs % 3600) / 60;
    let s = abs % 60;
    if s != 0 {
        format!("{sign}{h:02}:{m:02}:{s:02}")
    } else if m == 0 {
        format!("{sign}{h:02}:00")
    } else {
        format!("{sign}{h:02}:{m:02}")
    }
}

fn format_zone_suffix(offset: i32, zone: Option<&str>) -> String {
    // One classification, one rule: the IANA arm brackets its region name
    // over the offset-only spelling; `Z` is UTC; every offset spelling
    // renders through the one zero-offset rule.
    match zone.map(zone_kind) {
        Some(ZoneSpec::Iana(name)) => format!("{}[{name}]", format_zone_offset(offset)),
        Some(ZoneSpec::Utc) => "Z".into(),
        Some(ZoneSpec::Fixed(_) | ZoneSpec::Prefixed(_) | ZoneSpec::Other(_)) | None => {
            format_zone_offset(offset)
        }
    }
}

/// The offset-only spelling a zoneless clock value renders: `Z` at zero, the
/// numeric offset otherwise. The one zero-offset rule, shared by the ISO
/// suffix ([`format_zone_suffix`]) and the `timezone`/`offset` accessors so
/// one stored offset has one spelling.
fn format_zone_offset(offset: i32) -> String {
    if offset == 0 {
        "Z".into()
    } else {
        format_offset(offset)
    }
}

fn format_duration(months: i64, days: i64, nanos: i128) -> String {
    if months == 0 && days == 0 && nanos == 0 {
        return "PT0S".into();
    }
    let mut s = String::from("P");
    let y = months / 12;
    let mo = months % 12;
    if y != 0 {
        s.push_str(&format!("{y}Y"));
    }
    if mo != 0 {
        s.push_str(&format!("{mo}M"));
    }
    if days != 0 {
        s.push_str(&format!("{days}D"));
    }
    let neg_t = nanos < 0;
    let mut n = nanos.unsigned_abs();
    let hours = n / 3_600_000_000_000;
    n %= 3_600_000_000_000;
    let mins = n / 60_000_000_000;
    n %= 60_000_000_000;
    let secs = n / 1_000_000_000;
    let nano = n % 1_000_000_000;
    if hours != 0 || mins != 0 || secs != 0 || nano != 0 {
        s.push('T');
        let sign = if neg_t { "-" } else { "" };
        if hours != 0 {
            s.push_str(&format!("{sign}{hours}H"));
        }
        if mins != 0 {
            s.push_str(&format!("{sign}{mins}M"));
        }
        if secs != 0 || nano != 0 {
            if nano == 0 {
                s.push_str(&format!("{sign}{secs}S"));
            } else {
                let frac = format!("{nano:09}").trim_end_matches('0').to_string();
                s.push_str(&format!("{sign}{secs}.{frac}S"));
            }
        }
    }
    s
}

fn time_to_nanos(t: NaiveTime) -> i64 {
    t.num_seconds_from_midnight() as i64 * 1_000_000_000 + t.nanosecond() as i64
}

/// Nanoseconds of the UTC clock time a `Time` denotes. Deliberately *not*
/// wrapped at midnight: an offset can push the wall clock out of the day, and
/// the ordering contract is this signed value plus the offset.
pub(super) fn utc_time_nanos(t: NaiveTime, offset: i32) -> i64 {
    time_to_nanos(t) - i64::from(offset) * 1_000_000_000
}

/// The wall clock a zoned instant reads at (`utc + offset`). Constructors
/// keep the sum inside chrono's range, but the Bolt parameter decoders
/// accept any i32 offset (the render path's comment at the `DateTime` arm
/// documents this input class), and equality bucketing has no error
/// channel — so an out-of-range sum degrades to the UTC wall clock, the
/// same stated fallback render uses, instead of panicking. Deterministic
/// per payload, so `a = b` still implies one bucket.
fn local_of(utc: NaiveDateTime, offset: i32) -> NaiveDateTime {
    add_offset(utc, offset).unwrap_or(utc)
}

/// `n` is always a within-day nanosecond count (rem_euclid at the call sites),
/// so the conversion is infallible in practice; fall back instead of unwrap.
fn nanos_to_time(n: i64) -> NaiveTime {
    let secs = (n / 1_000_000_000) as u32;
    let nano = (n % 1_000_000_000) as u32;
    NaiveTime::from_num_seconds_from_midnight_opt(secs, nano).unwrap_or(NaiveTime::MIN)
}

/// Error returned when a temporal computation overflows the representable
/// range (chrono dates ±262143 years, i64 duration months/days, i128 nanos).
/// The honest contract for out-of-range results is an error, never a panic.
pub(super) fn range_err() -> Error {
    Error::ty("temporal value out of range")
}

/// The one spelling of a duration arithmetic overflow: Neo4j's 22N28
/// (`ArithmeticException`) text, naming the operation that overflowed
/// (`duration()` for construction, the field for pattern formatting).
pub(super) fn duration_overflow_err(operation: &str) -> Error {
    Error::ty(format!(
        "the result of the operation '{operation}' has caused an overflow"
    ))
}

/// Narrow one i128 lane total to the i64 a duration component stores.
/// Components that overflow individually but cancel stay representable because
/// the lanes are summed before this check (Neo4j's exact wide arithmetic).
pub(super) fn checked_lane(value: i128, operation: &str) -> crate::Result<i64> {
    i64::try_from(value).map_err(|_| duration_overflow_err(operation))
}

/// The `Temporal` payload a field map holds under `k`, or `None` when the
/// key is absent or non-temporal. Shared by the constructors and the zone
/// resolution (`construct.rs`, `zone.rs`); the scalar extraction is the
/// canonical [`Value::as_temporal`]. The field *policy* never reads a source
/// field through this — a present non-temporal value is a typed rejection
/// there (`field_rules`), not an absent field.
pub(super) fn map_temporal<'a>(
    map: &'a std::collections::BTreeMap<String, Value>,
    k: &str,
) -> Option<&'a Temporal> {
    map.get(k).and_then(Value::as_temporal)
}

/// The value a `(spelling, value)` table names, or `None` — the one keyed
/// table lookup behind every `from_name` ([`clock::ClockKind`],
/// [`component::Component`], its duration sibling), so no table is walked by
/// a hand-rolled copy.
pub(super) fn lookup<T: Copy>(table: &[(&str, T)], name: &str) -> Option<T> {
    table
        .iter()
        .find(|(spelling, _)| *spelling == name)
        .map(|(_, value)| *value)
}

/// f64 → i128 with a range error; 1e38 is comfortably below i128::MAX ≈ 1.7e38.
pub(super) fn f64_to_i128_range(v: f64) -> Result<i128, Error> {
    if v.is_finite() && v.abs() < 1.0e38 {
        Ok(v as i128)
    } else {
        Err(range_err())
    }
}

/// f64 → i64 with a range error — Neo4j's `DurationValue.safeDoubleToLong`
/// seam: the stored month and day fields are `i64`, so an out-of-range
/// fraction fold is a typed range error, never a saturating cast.
pub(super) fn f64_to_i64_range(v: f64) -> Result<i64, Error> {
    i64::try_from(f64_to_i128_range(v)?).map_err(|_| range_err())
}

fn weekday_from_i(i: i64) -> Weekday {
    // `i.rem_euclid(7)` is total (unlike `(i - 1).rem_euclid(7)`, which
    // overflows at i64::MIN) and selects the same weekday for every input:
    // 1..=6 -> Mon..Sat, 0 -> Sun.
    match i.rem_euclid(7) {
        1 => Weekday::Mon,
        2 => Weekday::Tue,
        3 => Weekday::Wed,
        4 => Weekday::Thu,
        5 => Weekday::Fri,
        6 => Weekday::Sat,
        _ => Weekday::Sun,
    }
}

/// The duration field vocabulary — fields, tiers, unit scales and the
/// average-month/overflow facts — lives in [`field`]; these names are the
/// facade the sibling modules read through `super::`.
use field::{
    DurationField, AVG_NANOS_PER_MONTH, AVG_SECONDS_PER_MONTH, DAYS_PER_WEEK, MAX_DURATION_SECONDS,
    MONTHS_PER_QUARTER, MONTHS_PER_YEAR, NANOS_PER_DAY, NANOS_PER_HOUR, NANOS_PER_MICRO,
    NANOS_PER_MILLI, NANOS_PER_MINUTE, NANOS_PER_SECOND, SECONDS_PER_HOUR, SECONDS_PER_MINUTE,
};