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