Skip to main content

relate_core/temporal/
zone.rs

1//! Zone resolution: classifying a zone string, resolving an IANA zone to
2//! its UTC offset at a wall clock or at a UTC instant, and the
3//! [`ResolvedZone`] a `timezone` field names (ADR-0178; extracted from
4//! `construct.rs` per ADR-0340).
5
6use chrono::{DateTime, NaiveDateTime, Offset, TimeZone};
7use chrono_tz::Tz;
8
9use crate::{Error, Result, Value};
10
11use super::{map_temporal, Temporal};
12
13/// How a zone string is spelled. Classified once so every consumer matches
14/// on the kind instead of re-probing the string's shape: the formatting side
15/// in `mod.rs` and the resolution side here cannot drift apart.
16#[derive(Clone, Copy)]
17pub(super) enum ZoneSpec<'a> {
18    /// An IANA name (`Europe/Stockholm`).
19    Iana(&'a str),
20    /// `Z` / `z`: UTC.
21    Utc,
22    /// A numeric fixed-offset spelling (`+01:00`, `-0500`, …).
23    Fixed(&'a str),
24    /// A `GMT`/`UTC` prefixed fixed offset (`GMT+03:00`, `UTC`), which the
25    /// reference engine keeps verbatim as the value's time zone. Split from
26    /// [`ZoneSpec::Fixed`] so a consumer reads the classification instead of
27    /// re-probing the leading sign.
28    Prefixed(&'a str),
29    /// Any other string. The formatting path falls back to the stored
30    /// numeric offset for it.
31    Other(&'a str),
32}
33
34/// The numeric tail of a `GMT`/`UTC` prefixed fixed-offset spelling, or
35/// `None` when `z` carries no such prefix. The one prefix rule: the zone
36/// classifier and [`parse_offset`] both read it, so the accepted prefix set
37/// cannot drift. The probe is ASCII-case-insensitive (`Gmt+01:00`, `uTc`),
38/// never a hand-enumerated casing table.
39pub(super) fn strip_zone_prefix(z: &str) -> Option<&str> {
40    let (prefix, rest) = z.split_at_checked(3)?;
41    (prefix.eq_ignore_ascii_case("GMT") || prefix.eq_ignore_ascii_case("UTC")).then_some(rest)
42}
43
44/// A `GMT`/`UTC` prefixed fixed-offset spelling (`GMT`, `UTC`, `GMT+03:00`,
45/// `UTC-05:30`).
46fn is_prefixed_fixed_offset(z: &str) -> bool {
47    strip_zone_prefix(z)
48        .is_some_and(|rest| rest.is_empty() || rest.starts_with('+') || rest.starts_with('-'))
49}
50
51pub(super) fn zone_kind(z: &str) -> ZoneSpec<'_> {
52    if z.contains('/') {
53        ZoneSpec::Iana(z)
54    } else if z.eq_ignore_ascii_case("Z") {
55        ZoneSpec::Utc
56    } else if z.starts_with('+') || z.starts_with('-') {
57        ZoneSpec::Fixed(z)
58    } else if is_prefixed_fixed_offset(z) {
59        ZoneSpec::Prefixed(z)
60    } else {
61        ZoneSpec::Other(z)
62    }
63}
64
65/// Why an IANA wall clock could not be resolved to a UTC offset.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum ZoneError {
68    /// `zone` does not name a zone in the engine's IANA database.
69    UnknownZone,
70    /// `local` falls in a DST gap: the wall clock never occurs in `zone`.
71    NonexistentWallTime,
72}
73
74/// The outcome of resolving a wall clock in an IANA zone — chrono's
75/// `LocalResult` under a typed name so its two consumers (the resolver
76/// [`zone_offset_at`] and the zoned-literal parse) match on one vocabulary
77/// and cannot drift when a new outcome appears.
78pub(super) enum LocalResolution {
79    /// Exactly one instant maps to the wall clock.
80    Unique(DateTime<Tz>),
81    /// A DST fall-back overlap: the wall clock occurs twice.
82    Ambiguous {
83        earlier: DateTime<Tz>,
84        later: DateTime<Tz>,
85    },
86    /// A DST gap: the wall clock never occurs in the zone.
87    None,
88}
89
90impl LocalResolution {
91    /// The one ADR-0178 overlap fold: a unique wall clock is itself, a DST
92    /// overlap keeps its earliest (pre-transition) occurrence, a gap has
93    /// none — each caller maps `None` to its own error.
94    pub(super) fn earliest(self) -> Option<DateTime<Tz>> {
95        match self {
96            LocalResolution::Unique(dt) => Some(dt),
97            LocalResolution::Ambiguous { earlier, .. } => Some(earlier),
98            LocalResolution::None => None,
99        }
100    }
101}
102
103/// Resolve the wall clock `local` in `tz` — the one call site of chrono's
104/// `from_local_datetime`. Each consumer spells its own policy on the
105/// outcome: [`zone_offset_at`] keeps the earliest occurrence (ADR-0178),
106/// while the zoned-literal parse keeps its supplied-offset
107/// disambiguation.
108pub(super) fn resolve_local(tz: Tz, local: NaiveDateTime) -> LocalResolution {
109    match tz.from_local_datetime(&local) {
110        chrono::LocalResult::Single(dt) => LocalResolution::Unique(dt),
111        chrono::LocalResult::Ambiguous(earlier, later) => {
112            LocalResolution::Ambiguous { earlier, later }
113        }
114        chrono::LocalResult::None => LocalResolution::None,
115    }
116}
117
118/// Resolve the IANA wall clock `local` in `zone` to its UTC offset in
119/// seconds (ADR-0178).
120///
121/// A unique wall time yields its offset; a DST overlap yields the earliest
122/// (pre-transition) occurrence's offset. An unknown `zone` name and a wall
123/// time inside a DST gap are the two error outcomes.
124pub fn zone_offset_at(zone: &str, local: NaiveDateTime) -> std::result::Result<i32, ZoneError> {
125    let tz: Tz = zone.parse().map_err(|_| ZoneError::UnknownZone)?;
126    let dt = resolve_local(tz, local)
127        .earliest()
128        .ok_or(ZoneError::NonexistentWallTime)?;
129    Ok(dt.offset().fix().local_minus_utc())
130}
131
132/// How a wall clock stands in an IANA zone, before a caller applies its
133/// policy. [`resolve_local`] folds a gap into `None`; construction needs the
134/// two offsets on either side to shift the clock forward (Neo4j's
135/// `ZonedDateTime` rule), so they are carried here.
136enum WallClock {
137    /// Exactly one offset maps to the wall clock.
138    Unique { offset: i32 },
139    /// A DST fall-back overlap: the wall clock occurs twice.
140    Ambiguous { earlier: i32, later: i32 },
141    /// A DST gap: `local` never occurs; the zone's offset steps from
142    /// `before` to `after` across the transition.
143    Gap { before: i32, after: i32 },
144}
145
146/// How a wall clock resolves against its zone — the one typed policy every
147/// wall-clock resolver consults instead of re-spelling the earlier/later
148/// match. Its main decision is which occurrence of a DST overlap (a wall
149/// clock that occurs twice) is kept; [`Self::admits_unique`] and
150/// [`Self::shifts_gap`] answer the two other questions a supplied offset
151/// (`Require`/`Reject`) changes, so the resolver never re-matches variants.
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153pub(super) enum OverlapPolicy {
154    /// The earliest (pre-transition) occurrence (ADR-0178).
155    Earliest,
156    /// The occurrence at this offset when it is one of the two (a source
157    /// `datetime`'s stored offset), else the earliest.
158    Prefer(i32),
159    /// Only the occurrence at this offset (an offset written beside a
160    /// bracketed zone); another offset is ambiguous.
161    Require(i32),
162    /// Neither occurrence: the overlap itself is ambiguous (a literal that
163    /// wrote no offset).
164    Reject,
165}
166
167impl OverlapPolicy {
168    /// Whether a wall clock that occurs once, at `offset`, is accepted: only
169    /// a [`Self::Require`]d offset can contradict the zone's own.
170    pub(super) fn admits_unique(self, offset: i32) -> bool {
171        match self {
172            Self::Require(want) => want == offset,
173            Self::Earliest | Self::Prefer(_) | Self::Reject => true,
174        }
175    }
176
177    /// Whether a wall clock inside a DST gap (it never occurs) may shift
178    /// forward: an explicit [`Self::Require`]d offset cannot name it.
179    pub(super) fn shifts_gap(self) -> bool {
180        !matches!(self, Self::Require(_))
181    }
182
183    /// The offset of the occurrence this policy keeps, or `None` when the
184    /// overlap is ambiguous under it.
185    pub(super) fn pick(self, earlier: i32, later: i32) -> Option<i32> {
186        match self {
187            Self::Earliest => Some(earlier),
188            Self::Prefer(want) if want == later => Some(later),
189            Self::Prefer(_) => Some(earlier),
190            Self::Require(want) if want == earlier || want == later => Some(want),
191            Self::Require(_) | Self::Reject => None,
192        }
193    }
194}
195
196/// The offset at a UTC instant, without the wall-clock resolution policy.
197fn offset_at_utc(tz: Tz, utc: NaiveDateTime) -> i32 {
198    tz.from_utc_datetime(&utc).offset().fix().local_minus_utc()
199}
200
201/// Classify `local` in `zone` (the wall-clock twin of
202/// [`zone_offset_at_utc`]). An unknown zone name is the only error; a gap
203/// carries the offsets on either side so a caller can shift forward.
204fn wall_clock(zone: &str, local: NaiveDateTime) -> Result<WallClock> {
205    let tz: Tz = zone.parse().map_err(|_| unknown_zone_err(zone))?;
206    Ok(match resolve_local(tz, local) {
207        LocalResolution::Unique(dt) => WallClock::Unique {
208            offset: dt.offset().fix().local_minus_utc(),
209        },
210        LocalResolution::Ambiguous { earlier, later } => WallClock::Ambiguous {
211            earlier: earlier.offset().fix().local_minus_utc(),
212            later: later.offset().fix().local_minus_utc(),
213        },
214        LocalResolution::None => {
215            // The transition is within the gap around `local`; transitions
216            // are months apart, so ±15h on the UTC timeline lands on either
217            // side of it.
218            let before = local
219                .checked_sub_signed(chrono::Duration::hours(15))
220                .map(|probe| offset_at_utc(tz, probe))
221                .ok_or_else(super::range_err)?;
222            let after = local
223                .checked_add_signed(chrono::Duration::hours(15))
224                .map(|probe| offset_at_utc(tz, probe))
225                .ok_or_else(super::range_err)?;
226            WallClock::Gap { before, after }
227        }
228    })
229}
230
231/// The one spelling of a supplied offset contradicting its zone's own.
232pub(super) fn zone_offset_mismatch(zone: &str) -> Error {
233    Error::ty(format!("Timezone and offset do not match: {zone}"))
234}
235
236/// Resolve a wall clock the way Neo4j's constructors do: a unique time
237/// stands (under [`OverlapPolicy::Require`] its offset must be the supplied
238/// one, else [`zone_offset_mismatch`]); an overlap picks its occurrence by
239/// `overlap` (an unpicked overlap is the ambiguous-datetime error); a gap
240/// shifts the wall clock forward by the gap and resolves at the
241/// post-transition offset (`datetime('2020-03-29T02:30[Europe/Stockholm]')`
242/// is `03:30+02:00`) — except under `Require`, where an explicit offset
243/// cannot name a wall clock that never occurs (ambiguous-datetime error).
244/// Returns the resolved wall clock and its offset.
245pub(super) fn resolve_wall_forward(
246    zone: &str,
247    local: NaiveDateTime,
248    overlap: OverlapPolicy,
249) -> Result<(NaiveDateTime, i32)> {
250    match wall_clock(zone, local)? {
251        WallClock::Unique { offset } if overlap.admits_unique(offset) => Ok((local, offset)),
252        WallClock::Unique { .. } => Err(zone_offset_mismatch(zone)),
253        WallClock::Ambiguous { earlier, later } => {
254            let offset = overlap
255                .pick(earlier, later)
256                .ok_or_else(ambiguous_datetime_err)?;
257            Ok((local, offset))
258        }
259        WallClock::Gap { .. } if !overlap.shifts_gap() => Err(ambiguous_datetime_err()),
260        WallClock::Gap { before, after } => {
261            let shift = after - before;
262            if shift <= 0 {
263                return Err(ambiguous_datetime_err());
264            }
265            let shifted = local
266                .checked_add_signed(chrono::Duration::seconds(i64::from(shift)))
267                .ok_or_else(super::range_err)?;
268            // The shifted clock must now be a unique post-transition time;
269            // anything else means the probe did not bracket one gap.
270            match wall_clock(zone, shifted)? {
271                WallClock::Unique { offset } if offset == after => Ok((shifted, offset)),
272                _ => Err(ambiguous_datetime_err()),
273            }
274        }
275    }
276}
277
278/// Resolve the IANA zone `zone` at the UTC instant `utc` to its UTC offset
279/// in seconds (ADR-0329, ADR-0340). Unlike a wall clock
280/// ([`zone_offset_at`]), an instant is never ambiguous, so an unknown zone
281/// is the only failure (`ZoneError::NonexistentWallTime` is unreachable
282/// here). The Bolt DateTimeZoneIdUTC decoder and UTC-instant zone
283/// conversion share this rule.
284pub fn zone_offset_at_utc(zone: &str, utc: NaiveDateTime) -> std::result::Result<i32, ZoneError> {
285    let tz: Tz = zone.parse().map_err(|_| ZoneError::UnknownZone)?;
286    Ok(tz.from_utc_datetime(&utc).offset().fix().local_minus_utc())
287}
288
289/// The IANA zone a short zone name (a `z` pattern field, e.g. `CEST`)
290/// denotes. Java resolves these through its built-in `ZoneName` table; the
291/// engine carries the subset its acceptance suite exercises, and an
292/// unrecognized spelling is a typed error at the call site — never a silent
293/// zero offset. Day-saving names map to the region whose rules decide the
294/// offset (the `CEST` spelling is Europe/Paris summer time).
295pub(super) fn zone_from_short_name(name: &str) -> Option<&'static str> {
296    ZONE_NAMES
297        .iter()
298        .find(|row| row.short_names.iter().any(|n| n.eq_ignore_ascii_case(name)))
299        .map(|row| row.zone)
300}
301
302/// How the formatter spells a zone in a `z`/`v` pattern field, for the
303/// zones the engine carries display names for.
304pub(super) struct ZoneDisplay {
305    /// `z`..`zzz`: the abbreviation.
306    pub(super) short_summer: &'static str,
307    /// `v`: the generic abbreviation.
308    pub(super) short_generic: &'static str,
309    /// `zzzz`: the long daylight-saving name.
310    pub(super) long_summer: &'static str,
311    /// `vvvv`: the long generic name.
312    pub(super) long_generic: &'static str,
313}
314
315/// One row of the zone-name vocabulary: the short names that denote `zone`
316/// (the parse direction, [`zone_from_short_name`]) and, where carried, the
317/// display spellings the formatter renders back ([`zone_display`]).
318struct ZoneNameRow {
319    short_names: &'static [&'static str],
320    zone: &'static str,
321    display: Option<ZoneDisplay>,
322}
323
324const ZONE_NAMES: [ZoneNameRow; 5] = [
325    ZoneNameRow {
326        short_names: &["CET", "CEST"],
327        zone: "Europe/Paris",
328        display: Some(ZoneDisplay {
329            short_summer: "CEST",
330            short_generic: "CET",
331            long_summer: "Central European Summer Time",
332            long_generic: "Central European Time",
333        }),
334    },
335    ZoneNameRow {
336        short_names: &["UTC"],
337        zone: "UTC",
338        display: None,
339    },
340    ZoneNameRow {
341        short_names: &["EST", "EDT"],
342        zone: "America/New_York",
343        display: None,
344    },
345    ZoneNameRow {
346        short_names: &["PST", "PDT"],
347        zone: "America/Los_Angeles",
348        display: None,
349    },
350    ZoneNameRow {
351        short_names: &["JST"],
352        zone: "Asia/Tokyo",
353        display: None,
354    },
355];
356
357/// The display spellings for `zone`, if the vocabulary carries any.
358pub(super) fn zone_display(zone: &str) -> Option<&'static ZoneDisplay> {
359    ZONE_NAMES
360        .iter()
361        .find(|row| row.zone == zone)
362        .and_then(|row| row.display.as_ref())
363}
364
365/// The IANA region a `Temporal::DateTime` zone names, or `None` for an
366/// offset-only zone (no zone, `Z`, a numeric offset, any other spelling).
367/// The typed classification behind the Bolt DateTime vs DateTimeZoneId
368/// struct choice (ADR-0325), on the same [`zone_kind`] rule the formatter
369/// uses.
370pub fn zone_region(zone: Option<&str>) -> Option<&str> {
371    match zone.map(zone_kind) {
372        Some(ZoneSpec::Iana(name)) => Some(name),
373        // Every other spelling is offset-only; the classification answers it.
374        _ => None,
375    }
376}
377
378/// The reading an IANA zone offset is resolved at: a local wall-clock time
379/// (constructing a zoned value from local fields) or a UTC instant
380/// (converting an already-UTC value into the zone). The one discriminator
381/// [`offset_from_map`] takes, so the map probe exists once.
382pub(super) enum IanaAt {
383    Local(NaiveDateTime),
384    Utc(NaiveDateTime),
385}
386
387/// The one spelling of the "ambiguous datetime" failure: a wall clock a DST
388/// overlap leaves ambiguous, or one a DST gap never produces. The resolver's
389/// [`ZoneError::NonexistentWallTime`] outcome and the zoned-literal parse
390/// arms all consult it, so the text cannot drift (ADR-0178, ADR-0340).
391pub(super) fn ambiguous_datetime_err() -> Error {
392    Error::ty("ambiguous datetime")
393}
394
395/// The one spelling of the "unknown timezone" failure: a zone name the tz
396/// database does not carry. Both readings of the name — the resolver's
397/// [`ZoneError::UnknownZone`] outcome and the zoned-literal parse — consult
398/// it, so the text cannot drift (ADR-0178, ADR-0340).
399pub(super) fn unknown_zone_err(zone: &str) -> Error {
400    Error::ty(format!("unknown timezone '{zone}'"))
401}
402
403/// One failure vocabulary for both readings: the resolver's typed outcome
404/// mapped back to this path's message (ADR-0178, ADR-0340).
405fn iana_offset_at(zone: &str, at: IanaAt) -> Result<i32> {
406    let resolved = match at {
407        IanaAt::Local(local) => zone_offset_at(zone, local),
408        IanaAt::Utc(utc) => zone_offset_at_utc(zone, utc),
409    };
410    resolved.map_err(|e| match e {
411        ZoneError::UnknownZone => unknown_zone_err(zone),
412        ZoneError::NonexistentWallTime => ambiguous_datetime_err(),
413    })
414}
415
416/// The offset and zone a `timezone` field (or an inherited source) names:
417/// the domain concept the constructors carry between signatures.
418#[derive(Debug, Clone, PartialEq, Eq)]
419pub(super) struct ResolvedZone {
420    /// UTC offset in seconds.
421    pub(super) offset: i32,
422    /// The zone spelling to keep, or `None` for an offset-only source.
423    pub(super) zone: Option<String>,
424}
425
426impl ResolvedZone {
427    /// UTC with zone `Z`: the documented default when no zone is named.
428    pub(super) fn utc() -> Self {
429        Self {
430            offset: 0,
431            zone: Some("Z".into()),
432        }
433    }
434}
435
436/// The largest UTC offset the offset grammar accepts (`±18:00`), the bound
437/// the reference engine enforces on a zone offset. Public so a surface that
438/// builds a zoned value from components (the C ABI's params builder,
439/// ADR-0502 §4) applies the same bound instead of re-deriving it.
440pub const MAX_OFFSET_SECONDS: i64 = 18 * 3600;
441
442/// The one spelling of an invalid offset (`+45`, a non-numeric field, an
443/// out-of-range value).
444fn invalid_offset(s: &str) -> Error {
445    Error::argument_error(format!("invalid timezone offset '{s}'"))
446}
447
448/// The UTC offset in seconds a zone spelling denotes: `Z`, a signed
449/// numeric spelling — an hour run with optional minute and second fields,
450/// compact (`-0130`) or colon-separated (`+01:30`) — or a `GMT`/`UTC`
451/// prefixed one (`GMT+03:00`, bare `UTC`). The one offset grammar, beside
452/// the classifier it shares [`strip_zone_prefix`] with. The grammar
453/// carries at most one leading sign — the sign is optional, so a pattern
454/// field reading an unsigned digit run takes it as positive — and the
455/// digit-or-colon tail check is the typed rejection that answers a second
456/// sign character, never a sign silently folded away.
457///
458/// The sum is checked through `unsigned_abs`: a user-controlled field can
459/// saturate the signed total to `i64::MIN`, whose `abs()` panics in debug
460/// builds, so the magnitude — never the signed value — is what the bound
461/// compares.
462pub(super) fn parse_offset(s: &str) -> Result<i32> {
463    if s == "Z" || s == "z" {
464        return Ok(0);
465    }
466    // A `GMT`/`UTC` prefixed fixed offset (`GMT+03:00`, `UTC`) is the same
467    // offset as its numeric tail; the prefix is the zone spelling the value
468    // renders, not part of the arithmetic.
469    let numeric = strip_zone_prefix(s).unwrap_or(s);
470    if numeric.is_empty() {
471        return Ok(0);
472    }
473    // One optional sign, then digits: `strip_prefix` strips exactly one
474    // occurrence, so a second sign character survives into the tail — and
475    // the digit-or-colon check below is the rejection that catches it.
476    let sign: i64 = if numeric.starts_with('-') { -1 } else { 1 };
477    let rest = numeric.strip_prefix(['+', '-']).unwrap_or(numeric);
478    if !rest.chars().all(|c| c.is_ascii_digit() || c == ':') {
479        return Err(invalid_offset(s));
480    }
481    // Fields are user-controlled digit runs; a field that is not a number is
482    // a typed rejection, never a silent zero.
483    let field = |value: &str| -> Result<i64> { value.parse().map_err(|_| invalid_offset(s)) };
484    let (h, m, sec): (i64, i64, i64) = if rest.contains(':') {
485        // The split spells the optional minute/second defaulting once:
486        // a shorter arm's missing fields are 0, a longer one is the typed
487        // rejection — no per-field collect-then-index pair.
488        match rest.split(':').collect::<Vec<_>>().as_slice() {
489            [h] => (field(h)?, 0, 0),
490            [h, m] => (field(h)?, field(m)?, 0),
491            [h, m, sec] => (field(h)?, field(m)?, field(sec)?),
492            _ => return Err(invalid_offset(s)),
493        }
494    } else {
495        // The digit check above already proved the run is ASCII digits, so
496        // the byte-sliced fields below are whole numerals.
497        match rest.len() {
498            0..=2 => (field(rest)?, 0, 0),
499            4 => (field(&rest[..2])?, field(&rest[2..])?, 0),
500            6 => (field(&rest[..2])?, field(&rest[2..4])?, field(&rest[4..])?),
501            _ => return Err(invalid_offset(s)),
502        }
503    };
504    let total = sign
505        * h.saturating_mul(3600)
506            .saturating_add(m.saturating_mul(60))
507            .saturating_add(sec);
508    if total.unsigned_abs() > MAX_OFFSET_SECONDS as u64 {
509        return Err(invalid_offset(s));
510    }
511    i32::try_from(total).map_err(|_| invalid_offset(s))
512}
513
514/// The [`ResolvedZone`] a classified zone spelling names at `at` — the one
515/// zone-resolution seam: an IANA region and a short zone name (`CET`, `EST`,
516/// …) both resolve through the tz database, an offset spelling through
517/// [`parse_offset`], and `Z` is UTC. A consumer with a wall clock reads
518/// [`offset_from_map_local`]; this seam itself never shifts one.
519fn resolved_zone(spec: ZoneSpec<'_>, spelling: &str, at: IanaAt) -> Result<ResolvedZone> {
520    Ok(match spec {
521        ZoneSpec::Iana(name) | ZoneSpec::Other(name) => ResolvedZone {
522            offset: iana_offset_at(name, at)?,
523            zone: Some(String::from(spelling)),
524        },
525        ZoneSpec::Utc => ResolvedZone::utc(),
526        ZoneSpec::Fixed(s) | ZoneSpec::Prefixed(s) => ResolvedZone {
527            offset: parse_offset(s)?,
528            zone: Some(String::from(spelling)),
529        },
530    })
531}
532
533/// The [`ResolvedZone`] a `timezone` string names, resolved at `at`: the
534/// single `zone_kind` match behind [`offset_from_map`].
535pub(super) fn offset_for_zone(z: &str, at: IanaAt) -> Result<ResolvedZone> {
536    resolved_zone(zone_kind(z), z, at)
537}
538
539/// The [`ResolvedZone`] a map's `timezone` field names, resolved at `at`
540/// (ADR-0340): the one map entry point, for both the local wall-clock and
541/// the UTC-instant readings ([`IanaAt`]). A caller with no instant of its
542/// own states the `now()` it resolves the zone at. A missing field is the
543/// documented UTC default; a present but non-string value is a typed error,
544/// never a silent default.
545pub(super) fn offset_from_map(
546    m: &std::collections::BTreeMap<String, Value>,
547    at: IanaAt,
548) -> Result<ResolvedZone> {
549    match m.get("timezone") {
550        None => Ok(ResolvedZone::utc()),
551        Some(Value::String(z)) => offset_for_zone(z, at),
552        Some(_) => Err(Error::argument_error("timezone must be STRING")),
553    }
554}
555
556/// A map's inherited zone source: the [`ResolvedZone`] plus
557/// the overlap policy its construction fact fixes. Only a `datetime` field's
558/// stored offset is authoritative for a DST overlap (Neo4j's
559/// `datetime({datetime: x})` keeps `x`'s offset, while
560/// `datetime({date: x, time: x})` resolves the new wall clock at the zone's
561/// earliest occurrence).
562struct SourceZone {
563    zone: ResolvedZone,
564    overlap: OverlapPolicy,
565}
566
567/// The [`SourceZone`] a map's inherited source contributes, probing the
568/// `time` and `datetime` fields in that order: `Time` contributes its
569/// offset only, `DateTime` contributes its offset plus zone, and any other
570/// value yields `None` (no inheritable source). [`apply_timezone`] resolves
571/// the zone at the local wall clock when the map names its own timezone.
572fn source_offset_zone(m: &std::collections::BTreeMap<String, Value>) -> Option<SourceZone> {
573    for k in ["time", "datetime"] {
574        if let Some(t) = map_temporal(m, k) {
575            // Only a `datetime` field's stored offset is authoritative for a
576            // DST overlap; every other source resolves at the earliest.
577            let (offset, zone, overlap) = match (k, t) {
578                (_, Temporal::Time { offset, .. }) => (*offset, None, OverlapPolicy::Earliest),
579                ("datetime", Temporal::DateTime { offset, zone, .. }) => {
580                    (*offset, zone.clone(), OverlapPolicy::Prefer(*offset))
581                }
582                (_, Temporal::DateTime { offset, zone, .. }) => {
583                    (*offset, zone.clone(), OverlapPolicy::Earliest)
584                }
585                _ => continue,
586            };
587            return Some(SourceZone {
588                zone: ResolvedZone { offset, zone },
589                overlap,
590            });
591        }
592    }
593    None
594}
595
596/// `utc + offset seconds` is the zone's wall clock at the UTC instant `utc`,
597/// erroring instead of panicking when the result would fall outside chrono's
598/// range. The additive twin of [`sub_offset`].
599pub(super) fn add_offset(utc: NaiveDateTime, offset: i32) -> Result<NaiveDateTime> {
600    utc.checked_add_signed(chrono::Duration::seconds(i64::from(offset)))
601        .ok_or_else(super::range_err)
602}
603
604/// `local - offset seconds`, erroring instead of panicking when the result
605/// would fall outside chrono's range.
606pub(super) fn sub_offset(local: NaiveDateTime, offset: i32) -> Result<NaiveDateTime> {
607    local
608        .checked_sub_signed(chrono::Duration::seconds(i64::from(offset)))
609        .ok_or_else(super::range_err)
610}
611
612/// `(utc, zone)` after inheriting or converting a map timezone. The
613/// inherited source is derived from the same map ([`source_offset_zone`]),
614/// so callers never thread it.
615pub(super) fn apply_timezone(
616    local: NaiveDateTime,
617    m: &std::collections::BTreeMap<String, Value>,
618) -> Result<(NaiveDateTime, ResolvedZone)> {
619    match source_offset_zone(m) {
620        Some(src) => {
621            // Resolve the source zone at the local wall clock; an explicitly
622            // named zone then reads that instant, else the source keeps its
623            // own offset and zone.
624            let (local, offset) = source_wall(&src, local)?;
625            let utc = sub_offset(local, offset)?;
626            if m.contains_key("timezone") {
627                return Ok((utc, offset_from_map(m, IanaAt::Utc(utc))?));
628            }
629            Ok((
630                utc,
631                ResolvedZone {
632                    offset,
633                    zone: src.zone.zone,
634                },
635            ))
636        }
637        // No inherited source: the map's own `timezone` (or UTC when it
638        // names none) resolves the wall clock.
639        None => {
640            let (local, resolved) = offset_from_map_local(m, local)?;
641            Ok((sub_offset(local, resolved.offset)?, resolved))
642        }
643    }
644}
645
646/// Resolve an inherited [`SourceZone`] at the local wall clock: an IANA
647/// zone resolves with [`resolve_wall_forward`] (a gap shifts the clock, and
648/// a `datetime` source's offset disambiguates an overlap); anything else
649/// keeps the stored offset. Returns the possibly shifted wall clock and its
650/// offset.
651fn source_wall(source: &SourceZone, local: NaiveDateTime) -> Result<(NaiveDateTime, i32)> {
652    match source.zone.zone.as_deref().map(zone_kind) {
653        Some(ZoneSpec::Iana(name)) => resolve_wall_forward(name, local, source.overlap),
654        _ => Ok((local, source.zone.offset)),
655    }
656}
657
658/// [`offset_from_map`]'s local-wall-clock reading for the constructors: the
659/// wall clock (shifted forward when it falls in a DST gap) and the zone it
660/// resolves in; an overlap resolves at its earliest occurrence.
661///
662/// Only an IANA region has a wall clock to shift or an overlap to
663/// disambiguate; every other spelling answers through the one
664/// [`resolved_zone`] seam, so `ZoneSpec::Other` means the same thing here as
665/// it does in [`offset_for_zone`] (a tz-database name, not a numeric
666/// offset).
667pub(super) fn offset_from_map_local(
668    m: &std::collections::BTreeMap<String, Value>,
669    local: NaiveDateTime,
670) -> Result<(NaiveDateTime, ResolvedZone)> {
671    match m.get("timezone") {
672        None => Ok((local, ResolvedZone::utc())),
673        Some(Value::String(z)) => {
674            let spec = zone_kind(z);
675            Ok(match spec {
676                ZoneSpec::Iana(name) => {
677                    let (local, offset) =
678                        resolve_wall_forward(name, local, OverlapPolicy::Earliest)?;
679                    (
680                        local,
681                        ResolvedZone {
682                            offset,
683                            zone: Some(z.to_string()),
684                        },
685                    )
686                }
687                _ => (local, resolved_zone(spec, z, IanaAt::Local(local))?),
688            })
689        }
690        Some(_) => Err(Error::argument_error("timezone must be STRING")),
691    }
692}
693
694#[cfg(test)]
695mod tests {
696    use chrono::NaiveDate;
697
698    use super::*;
699
700    /// The one overlap policy: each variant keeps or rejects its own
701    /// occurrence, so no resolver re-spells the earlier/later match.
702    #[test]
703    fn overlap_policy_picks_the_occurrence_it_names() {
704        let (earlier, later) = (7200, 3600);
705        assert_eq!(OverlapPolicy::Earliest.pick(earlier, later), Some(earlier));
706        assert_eq!(
707            OverlapPolicy::Prefer(later).pick(earlier, later),
708            Some(later)
709        );
710        assert_eq!(OverlapPolicy::Prefer(0).pick(earlier, later), Some(earlier));
711        assert_eq!(
712            OverlapPolicy::Require(later).pick(earlier, later),
713            Some(later)
714        );
715        assert_eq!(OverlapPolicy::Require(0).pick(earlier, later), None);
716        assert_eq!(OverlapPolicy::Reject.pick(earlier, later), None);
717    }
718
719    /// A supplied offset is `Require`d by the one resolver: it must name the
720    /// zone's own occurrence, and cannot name a wall clock in a DST gap.
721    #[test]
722    fn resolve_wall_forward_requires_a_supplied_offset() {
723        let at = |m, d, h| {
724            NaiveDate::from_ymd_opt(2020, m, d)
725                .unwrap()
726                .and_hms_opt(h, 30, 0)
727                .unwrap()
728        };
729        let zone = "Europe/Stockholm";
730        // Unique wall clock: the matching offset stands, another is a mismatch.
731        let summer = at(7, 1, 12);
732        assert_eq!(
733            resolve_wall_forward(zone, summer, OverlapPolicy::Require(7200)).unwrap(),
734            (summer, 7200)
735        );
736        assert_eq!(
737            resolve_wall_forward(zone, summer, OverlapPolicy::Require(3600))
738                .unwrap_err()
739                .to_string(),
740            zone_offset_mismatch(zone).to_string()
741        );
742        // Overlap: `Require` picks the named occurrence, `Reject` refuses.
743        let overlap = at(10, 25, 2);
744        assert_eq!(
745            resolve_wall_forward(zone, overlap, OverlapPolicy::Require(3600))
746                .unwrap()
747                .1,
748            3600
749        );
750        assert!(resolve_wall_forward(zone, overlap, OverlapPolicy::Reject).is_err());
751        // Gap: an explicit offset is ambiguous; without one the clock shifts.
752        let gap = at(3, 29, 2);
753        assert!(resolve_wall_forward(zone, gap, OverlapPolicy::Require(3600)).is_err());
754        assert_eq!(
755            resolve_wall_forward(zone, gap, OverlapPolicy::Reject).unwrap(),
756            (at(3, 29, 3), 7200)
757        );
758    }
759
760    /// ADR-0340: the UTC-instant resolver shares the typed failure
761    /// vocabulary; an instant is never ambiguous, so an unknown zone is
762    /// the only error.
763    #[test]
764    fn zone_offset_at_utc_is_typed_and_unambiguous() {
765        let at =
766            |s: &str| NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M").expect("test instant");
767        // Either side of the 2021-10-31 Stockholm fall-back: two instants,
768        // two offsets.
769        assert_eq!(
770            zone_offset_at_utc("Europe/Stockholm", at("2021-10-31T00:30")),
771            Ok(7200)
772        );
773        assert_eq!(
774            zone_offset_at_utc("Europe/Stockholm", at("2021-10-31T01:30")),
775            Ok(3600)
776        );
777        assert_eq!(
778            zone_offset_at_utc("Mars/Base", at("2021-10-31T01:30")),
779            Err(ZoneError::UnknownZone)
780        );
781        // The wall-clock resolver's gap outcome cannot arise at an instant:
782        // the local reading 2021-03-28T02:30 does not exist, while the UTC
783        // instant 00:30 resolves normally (01:30 CET, before the switch).
784        let gap = NaiveDate::from_ymd_opt(2021, 3, 28)
785            .unwrap()
786            .and_hms_opt(2, 30, 0)
787            .unwrap();
788        assert_eq!(
789            zone_offset_at("Europe/Stockholm", gap),
790            Err(ZoneError::NonexistentWallTime)
791        );
792        let before_transition = NaiveDate::from_ymd_opt(2021, 3, 28)
793            .unwrap()
794            .and_hms_opt(0, 30, 0)
795            .unwrap();
796        assert_eq!(
797            zone_offset_at_utc("Europe/Stockholm", before_transition),
798            Ok(3600)
799        );
800    }
801
802    /// F-1-27: a missing `timezone` key is the documented UTC default; a
803    /// present but non-string value is a typed error, never a silent default.
804    #[test]
805    fn offset_from_map_distinguishes_missing_from_malformed_timezone() {
806        let at = || {
807            IanaAt::Local(
808                NaiveDate::from_ymd_opt(2021, 1, 1)
809                    .unwrap()
810                    .and_hms_opt(0, 0, 0)
811                    .unwrap(),
812            )
813        };
814        let missing = std::collections::BTreeMap::new();
815        assert_eq!(
816            offset_from_map(&missing, at()),
817            Ok(ResolvedZone {
818                offset: 0,
819                zone: Some("Z".into()),
820            })
821        );
822        let malformed = [("timezone".into(), Value::Int(42))]
823            .into_iter()
824            .collect::<std::collections::BTreeMap<_, _>>();
825        assert_eq!(
826            offset_from_map(&malformed, at()),
827            Err(Error::argument_error("timezone must be STRING"))
828        );
829    }
830
831    /// LABS-871: the offset grammar carries at most one leading sign — a
832    /// second sign character is the digit-or-colon tail check's typed
833    /// rejection, never a sign silently folded away: `--01:00` used to
834    /// answer `-01:00`.
835    #[test]
836    fn parse_offset_carries_at_most_one_leading_sign() {
837        assert_eq!(parse_offset("+01:00"), Ok(3600));
838        assert_eq!(parse_offset("-01:00"), Ok(-3600));
839        assert_eq!(parse_offset("-0130"), Ok(-5400));
840        assert_eq!(parse_offset("-05"), Ok(-18000));
841        assert_eq!(parse_offset("Z"), Ok(0));
842        assert_eq!(parse_offset("UTC"), Ok(0));
843        assert_eq!(parse_offset("GMT+03:00"), Ok(10800));
844        for s in [
845            "--01:00",
846            "+-01:00",
847            "++01:00",
848            "-+01:00",
849            "UTC+-01:00",
850            "GMT--05:00",
851        ] {
852            assert_eq!(parse_offset(s), Err(invalid_offset(s)), "{s}");
853        }
854    }
855
856    /// `iana_offset_at` renders the same `unknown timezone` message for
857    /// both readings (the message single-sourced with ADR-0340).
858    #[test]
859    fn iana_offset_at_renders_one_unknown_zone_message() {
860        let local = NaiveDate::from_ymd_opt(2021, 3, 28)
861            .unwrap()
862            .and_hms_opt(12, 0, 0)
863            .unwrap();
864        let expected = Error::ty("unknown timezone 'Not/AZone'");
865        assert_eq!(
866            iana_offset_at("Not/AZone", IanaAt::Local(local)),
867            Err(expected.clone())
868        );
869        assert_eq!(
870            iana_offset_at("Not/AZone", IanaAt::Utc(local)),
871            Err(expected)
872        );
873    }
874}