Skip to main content

jiff/tz/
ambiguous.rs

1use jcore::tz::AmbiguousOffset as JAmbiguousOffset;
2
3use crate::{
4    Timestamp, ZonedDateTime,
5    civil::DateTime,
6    error::{Error, ErrorContext, tz::ambiguous::Error as E},
7    tz::{Offset, TimeZone},
8};
9
10/// Configuration for resolving ambiguous datetimes in a particular time zone.
11///
12/// This is useful for specifying how to disambiguate ambiguous datetimes at
13/// runtime. For example, as configuration for parsing [`ZonedDateTime`] values
14/// via
15/// [`fmt::temporal::DateTimeParser::disambiguation`](crate::fmt::temporal::DateTimeParser::disambiguation).
16///
17/// Note that there is no difference in using
18/// `Disambiguation::Compatible.disambiguate(ambiguous_timestamp)` and
19/// `ambiguous_timestamp.compatible()`. They are equivalent. The purpose of
20/// this enum is to expose the disambiguation strategy as a runtime value for
21/// configuration purposes.
22///
23/// The default value is `Disambiguation::Compatible`, which matches the
24/// behavior specified in [RFC 5545 (iCalendar)]. Namely, when an ambiguous
25/// datetime is found in a fold (the clocks are rolled back), then the earlier
26/// time is selected. And when an ambiguous datetime is found in a gap (the
27/// clocks are skipped forward), then the later time is selected.
28///
29/// This enum is non-exhaustive so that other forms of disambiguation may be
30/// added in semver compatible releases.
31///
32/// [RFC 5545 (iCalendar)]: https://datatracker.ietf.org/doc/html/rfc5545
33///
34/// # Example
35///
36/// This example shows the default disambiguation mode ("compatible") when
37/// given a datetime that falls in a "gap" (i.e., a forwards DST transition).
38///
39/// ```
40/// use jiff::{civil::date, tz};
41///
42/// let newyork = tz::db().get("America/New_York")?;
43/// let ambiguous = newyork
44///     .to_ambiguous_zoned_datetime(date(2024, 3, 10).at(2, 30, 0, 0));
45///
46/// // NOTE: This is identical to `ambiguous.compatible()`.
47/// let zdt = ambiguous.disambiguate(tz::Disambiguation::Compatible)?;
48/// assert_eq!(zdt.datetime(), date(2024, 3, 10).at(3, 30, 0, 0));
49/// // In compatible mode, forward transitions select the later
50/// // time. In the EST->EDT transition, that's the -04 (EDT) offset.
51/// assert_eq!(zdt.offset(), tz::offset(-4));
52///
53/// # Ok::<(), Box<dyn std::error::Error>>(())
54/// ```
55///
56/// # Example: parsing
57///
58/// This example shows how to set the disambiguation configuration while
59/// parsing a [`ZonedDateTime`] datetime. In this example, we always prefer the
60/// earlier time.
61///
62/// ```
63/// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
64///
65/// static PARSER: DateTimeParser = DateTimeParser::new()
66///     .disambiguation(tz::Disambiguation::Earlier);
67///
68/// let zdt =
69///     PARSER.parse_zoned_datetime("2024-03-10T02:30[America/New_York]")?;
70/// // In earlier mode, forward transitions select the earlier time, unlike
71/// // in compatible mode. In this case, that's the pre-DST offset of -05.
72/// assert_eq!(zdt.datetime(), date(2024, 3, 10).at(1, 30, 0, 0));
73/// assert_eq!(zdt.offset(), tz::offset(-5));
74///
75/// # Ok::<(), Box<dyn std::error::Error>>(())
76/// ```
77#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Disambiguation {
}
#[automatically_derived]impl ::core::clone::Clone for Disambiguation {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Disambiguation { }Copy, #[automatically_derived]impl ::core::fmt::Debug for Disambiguation {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Disambiguation::Compatible => "Compatible",
                Disambiguation::Earlier => "Earlier",
                Disambiguation::Later => "Later",
                Disambiguation::Reject => "Reject",
            })
    }
}Debug, #[automatically_derived]impl ::core::default::Default for Disambiguation {
    #[inline]
    fn default() -> Self { Self::Compatible }
}Default)]
78#[cfg_attr(feature = "defmt", derive(defmt::Format))]
79#[non_exhaustive]
80pub enum Disambiguation {
81    /// In a backward transition, the earlier time is selected. In forward
82    /// transition, the later time is selected.
83    ///
84    /// This is equivalent to [`AmbiguousTimestamp::compatible`] and
85    /// [`AmbiguousZonedDateTime::compatible`].
86    #[default]
87    Compatible,
88    /// The earlier time is always selected.
89    ///
90    /// This is equivalent to [`AmbiguousTimestamp::earlier`] and
91    /// [`AmbiguousZonedDateTime::earlier`].
92    Earlier,
93    /// The later time is always selected.
94    ///
95    /// This is equivalent to [`AmbiguousTimestamp::later`] and
96    /// [`AmbiguousZonedDateTime::later`].
97    Later,
98    /// When an ambiguous datetime is encountered, this strategy will always
99    /// result in an error. This is useful if you need to require datetimes
100    /// from users to unambiguously refer to a specific instant.
101    ///
102    /// This is equivalent to [`AmbiguousTimestamp::unambiguous`] and
103    /// [`AmbiguousZonedDateTime::unambiguous`].
104    Reject,
105}
106
107/// A possibly ambiguous [`Offset`].
108///
109/// An `AmbiguousOffset` is part of both [`AmbiguousTimestamp`] and
110/// [`AmbiguousZonedDateTime`], which are created by
111/// [`TimeZone::to_ambiguous_timestamp`] and
112/// [`TimeZone::to_ambiguous_zoned_datetime`], respectively.
113///
114/// When converting a civil datetime in a particular time zone to a precise
115/// instant in time (that is, either `Timestamp` or `ZonedDateTime`), then the
116/// primary thing needed to form a precise instant in time is an [`Offset`].
117/// The problem is that some civil datetimes are ambiguous. That is, some do
118/// not exist (because they fall into a gap, where some civil time is skipped),
119/// or some are repeated (because they fall into a fold, where some civil time
120/// is repeated).
121///
122/// The purpose of this type is to represent that ambiguity when it occurs.
123/// The ambiguity is manifest through the offset choice: it is either the
124/// offset _before_ the transition or the offset _after_ the transition. This
125/// is true regardless of whether the ambiguity occurs as a result of a gap
126/// or a fold.
127///
128/// It is generally considered very rare to need to inspect values of this type
129/// directly. Instead, higher level routines like
130/// [`AmbiguousZonedDateTime::compatible`] or
131/// [`AmbiguousZonedDateTime::unambiguous`] will implement a strategy for you.
132///
133/// # Example
134///
135/// This example shows how the "compatible" disambiguation strategy is
136/// implemented. Recall that the "compatible" strategy chooses the offset
137/// corresponding to the civil datetime after a gap, and the offset
138/// corresponding to the civil datetime before a gap.
139///
140/// ```
141/// use jiff::{civil::date, tz::{self, AmbiguousOffset}};
142///
143/// let tz = tz::db().get("America/New_York")?;
144/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
145/// let offset = match tz.to_ambiguous_timestamp(dt).offset() {
146///     AmbiguousOffset::Unambiguous { offset } => offset,
147///     // This is counter-intuitive, but in order to get the civil datetime
148///     // *after* the gap, we need to select the offset from *before* the
149///     // gap.
150///     AmbiguousOffset::Gap { before, .. } => before,
151///     AmbiguousOffset::Fold { before, .. } => before,
152/// };
153/// assert_eq!(offset.to_timestamp(dt)?.to_string(), "2024-03-10T07:30:00Z");
154///
155/// # Ok::<(), Box<dyn std::error::Error>>(())
156/// ```
157#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for AmbiguousOffset {
}
#[automatically_derived]impl ::core::clone::Clone for AmbiguousOffset {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Offset>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for AmbiguousOffset { }Copy, #[automatically_derived]impl ::core::fmt::Debug for AmbiguousOffset {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Unambiguous { offset: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Unambiguous offset", &__self_0),
            Self::Gap { before: __self_0, after: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Gap before after", __self_0, &__self_1),
            Self::Fold { before: __self_0, after: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Fold before after", __self_0, &__self_1),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for AmbiguousOffset {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Offset>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    AmbiguousOffset {
}
#[automatically_derived]impl ::core::cmp::PartialEq for AmbiguousOffset {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Unambiguous { offset: __self_0 }, Self::Unambiguous {
                    offset: __arg1_0 }) => __self_0 == __arg1_0,
                (Self::Gap { before: __self_0, after: __self_1 }, Self::Gap {
                    before: __arg1_0, after: __arg1_1 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (Self::Fold { before: __self_0, after: __self_1 },
                    Self::Fold { before: __arg1_0, after: __arg1_1 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq)]
158#[cfg_attr(feature = "defmt", derive(defmt::Format))]
159pub enum AmbiguousOffset {
160    /// The offset for a particular civil datetime and time zone is
161    /// unambiguous.
162    ///
163    /// This is the overwhelmingly common case. In general, the only time this
164    /// case does not occur is when there is a transition to a different time
165    /// zone (rare) or to/from daylight saving time (occurs for 1 hour twice
166    /// in year in many geographic locations).
167    Unambiguous {
168        /// The offset from UTC for the corresponding civil datetime given. The
169        /// offset is determined via the relevant time zone data, and in this
170        /// case, there is only one possible offset that could be applied to
171        /// the given civil datetime.
172        offset: Offset,
173    },
174    /// The offset for a particular civil datetime and time zone is ambiguous
175    /// because there is a gap.
176    ///
177    /// This most commonly occurs when a civil datetime corresponds to an hour
178    /// that was "skipped" in a jump to DST (daylight saving time).
179    Gap {
180        /// The offset corresponding to the time before a gap.
181        ///
182        /// For example, given a time zone of `America/Los_Angeles`, the offset
183        /// for time immediately preceding `2020-03-08T02:00:00` is `-08`.
184        before: Offset,
185        /// The offset corresponding to the later time in a gap.
186        ///
187        /// For example, given a time zone of `America/Los_Angeles`, the offset
188        /// for time immediately following `2020-03-08T02:59:59` is `-07`.
189        after: Offset,
190    },
191    /// The offset for a particular civil datetime and time zone is ambiguous
192    /// because there is a fold.
193    ///
194    /// This most commonly occurs when a civil datetime corresponds to an hour
195    /// that was "repeated" in a jump to standard time from DST (daylight
196    /// saving time).
197    Fold {
198        /// The offset corresponding to the earlier time in a fold.
199        ///
200        /// For example, given a time zone of `America/Los_Angeles`, the offset
201        /// for time on the first `2020-11-01T01:00:00` is `-07`.
202        before: Offset,
203        /// The offset corresponding to the earlier time in a fold.
204        ///
205        /// For example, given a time zone of `America/Los_Angeles`, the offset
206        /// for time on the second `2020-11-01T01:00:00` is `-08`.
207        after: Offset,
208    },
209}
210
211impl AmbiguousOffset {
212    #[inline]
213    pub(crate) const fn from_jcore(
214        offset: JAmbiguousOffset,
215    ) -> AmbiguousOffset {
216        match offset {
217            JAmbiguousOffset::Unambiguous { offset } => {
218                let offset = Offset::from_jcore(offset);
219                AmbiguousOffset::Unambiguous { offset }
220            }
221            JAmbiguousOffset::Gap { before, after } => {
222                let before = Offset::from_jcore(before);
223                let after = Offset::from_jcore(after);
224                AmbiguousOffset::Gap { before, after }
225            }
226            JAmbiguousOffset::Fold { before, after } => {
227                let before = Offset::from_jcore(before);
228                let after = Offset::from_jcore(after);
229                AmbiguousOffset::Fold { before, after }
230            }
231        }
232    }
233}
234
235/// A possibly ambiguous [`Timestamp`], created by
236/// [`TimeZone::to_ambiguous_timestamp`].
237///
238/// While this is called an ambiguous _timestamp_, the thing that is
239/// actually ambiguous is the offset. That is, an ambiguous timestamp is
240/// actually a pair of a [`civil::DateTime`](crate::civil::DateTime) and an
241/// [`AmbiguousOffset`].
242///
243/// When the offset is ambiguous, it either represents a gap (civil time is
244/// skipped) or a fold (civil time is repeated). In both cases, there are, by
245/// construction, two different offsets to choose from: the offset from before
246/// the transition and the offset from after the transition.
247///
248/// The purpose of this type is to represent that ambiguity (when it occurs)
249/// and enable callers to make a choice about how to resolve that ambiguity.
250/// In some cases, you might want to reject ambiguity altogether, which is
251/// supported by the [`AmbiguousTimestamp::unambiguous`] routine.
252///
253/// This type provides four different out-of-the-box disambiguation strategies:
254///
255/// * [`AmbiguousTimestamp::compatible`] implements the
256/// [`Disambiguation::Compatible`] strategy. In the case of a gap, the offset
257/// after the gap is selected. In the case of a fold, the offset before the
258/// fold occurs is selected.
259/// * [`AmbiguousTimestamp::earlier`] implements the
260/// [`Disambiguation::Earlier`] strategy. This always selects the "earlier"
261/// offset.
262/// * [`AmbiguousTimestamp::later`] implements the
263/// [`Disambiguation::Later`] strategy. This always selects the "later"
264/// offset.
265/// * [`AmbiguousTimestamp::unambiguous`] implements the
266/// [`Disambiguation::Reject`] strategy. It acts as an assertion that the
267/// offset is unambiguous. If it is ambiguous, then an appropriate error is
268/// returned.
269///
270/// The [`AmbiguousTimestamp::disambiguate`] method can be used with the
271/// [`Disambiguation`] enum when the disambiguation strategy isn't known until
272/// runtime.
273///
274/// Note also that these aren't the only disambiguation strategies. The
275/// [`AmbiguousOffset`] type, accessible via [`AmbiguousTimestamp::offset`],
276/// exposes the full details of the ambiguity. So any strategy can be
277/// implemented.
278///
279/// # Example
280///
281/// This example shows how the "compatible" disambiguation strategy is
282/// implemented. Recall that the "compatible" strategy chooses the offset
283/// corresponding to the civil datetime after a gap, and the offset
284/// corresponding to the civil datetime before a gap.
285///
286/// ```
287/// use jiff::{civil::date, tz::{self, AmbiguousOffset}};
288///
289/// let tz = tz::db().get("America/New_York")?;
290/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
291/// let offset = match tz.to_ambiguous_timestamp(dt).offset() {
292///     AmbiguousOffset::Unambiguous { offset } => offset,
293///     // This is counter-intuitive, but in order to get the civil datetime
294///     // *after* the gap, we need to select the offset from *before* the
295///     // gap.
296///     AmbiguousOffset::Gap { before, .. } => before,
297///     AmbiguousOffset::Fold { before, .. } => before,
298/// };
299/// assert_eq!(offset.to_timestamp(dt)?.to_string(), "2024-03-10T07:30:00Z");
300///
301/// # Ok::<(), Box<dyn std::error::Error>>(())
302/// ```
303#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for AmbiguousTimestamp {
}
#[automatically_derived]impl ::core::clone::Clone for AmbiguousTimestamp {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<DateTime>;
        let _: ::core::clone::AssertParamIsClone<AmbiguousOffset>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for AmbiguousTimestamp { }Copy, #[automatically_derived]impl ::core::fmt::Debug for AmbiguousTimestamp {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "AmbiguousTimestamp dt offset", &self.dt, &&self.offset)
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for AmbiguousTimestamp {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DateTime>;
        let _: ::core::cmp::AssertParamIsEq<AmbiguousOffset>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    AmbiguousTimestamp {
}
#[automatically_derived]impl ::core::cmp::PartialEq for AmbiguousTimestamp {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.dt == other.dt && self.offset == other.offset
    }
}PartialEq)]
304#[cfg_attr(feature = "defmt", derive(defmt::Format))]
305pub struct AmbiguousTimestamp {
306    dt: DateTime,
307    offset: AmbiguousOffset,
308}
309
310impl AmbiguousTimestamp {
311    #[inline]
312    pub(crate) fn new(
313        dt: DateTime,
314        kind: AmbiguousOffset,
315    ) -> AmbiguousTimestamp {
316        AmbiguousTimestamp { dt, offset: kind }
317    }
318
319    /// Returns the civil datetime that was used to create this ambiguous
320    /// timestamp.
321    ///
322    /// # Example
323    ///
324    /// ```
325    /// use jiff::{civil::date, tz};
326    ///
327    /// let tz = tz::db().get("America/New_York")?;
328    /// let dt = date(2024, 7, 10).at(17, 15, 0, 0);
329    /// let ts = tz.to_ambiguous_timestamp(dt);
330    /// assert_eq!(ts.datetime(), dt);
331    ///
332    /// # Ok::<(), Box<dyn std::error::Error>>(())
333    /// ```
334    #[inline]
335    pub fn datetime(&self) -> DateTime {
336        self.dt
337    }
338
339    /// Returns the possibly ambiguous offset that is the ultimate source of
340    /// ambiguity.
341    ///
342    /// Most civil datetimes are not ambiguous, and thus, the offset will not
343    /// be ambiguous either. In this case, the offset returned will be the
344    /// [`AmbiguousOffset::Unambiguous`] variant.
345    ///
346    /// But, not all civil datetimes are unambiguous. There are exactly two
347    /// cases where a civil datetime can be ambiguous: when a civil datetime
348    /// does not exist (a gap) or when a civil datetime is repeated (a fold).
349    /// In both such cases, the _offset_ is the thing that is ambiguous as
350    /// there are two possible choices for the offset in both cases: the offset
351    /// before the transition (whether it's a gap or a fold) or the offset
352    /// after the transition.
353    ///
354    /// This type captures the fact that computing an offset from a civil
355    /// datetime in a particular time zone is in one of three possible states:
356    ///
357    /// 1. It is unambiguous.
358    /// 2. It is ambiguous because there is a gap in time.
359    /// 3. It is ambiguous because there is a fold in time.
360    ///
361    /// # Example
362    ///
363    /// ```
364    /// use jiff::{civil::date, tz::{self, AmbiguousOffset}};
365    ///
366    /// let tz = tz::db().get("America/New_York")?;
367    ///
368    /// // Not ambiguous.
369    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
370    /// let ts = tz.to_ambiguous_timestamp(dt);
371    /// assert_eq!(ts.offset(), AmbiguousOffset::Unambiguous {
372    ///     offset: tz::offset(-4),
373    /// });
374    ///
375    /// // Ambiguous because of a gap.
376    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
377    /// let ts = tz.to_ambiguous_timestamp(dt);
378    /// assert_eq!(ts.offset(), AmbiguousOffset::Gap {
379    ///     before: tz::offset(-5),
380    ///     after: tz::offset(-4),
381    /// });
382    ///
383    /// // Ambiguous because of a fold.
384    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
385    /// let ts = tz.to_ambiguous_timestamp(dt);
386    /// assert_eq!(ts.offset(), AmbiguousOffset::Fold {
387    ///     before: tz::offset(-4),
388    ///     after: tz::offset(-5),
389    /// });
390    ///
391    /// # Ok::<(), Box<dyn std::error::Error>>(())
392    /// ```
393    #[inline]
394    pub fn offset(&self) -> AmbiguousOffset {
395        self.offset
396    }
397
398    /// Returns true if and only if this possibly ambiguous timestamp is
399    /// actually ambiguous.
400    ///
401    /// This occurs precisely in cases when the offset is _not_
402    /// [`AmbiguousOffset::Unambiguous`].
403    ///
404    /// # Example
405    ///
406    /// ```
407    /// use jiff::{civil::date, tz};
408    ///
409    /// let tz = tz::db().get("America/New_York")?;
410    ///
411    /// // Not ambiguous.
412    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
413    /// let ts = tz.to_ambiguous_timestamp(dt);
414    /// assert!(!ts.is_ambiguous());
415    ///
416    /// // Ambiguous because of a gap.
417    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
418    /// let ts = tz.to_ambiguous_timestamp(dt);
419    /// assert!(ts.is_ambiguous());
420    ///
421    /// // Ambiguous because of a fold.
422    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
423    /// let ts = tz.to_ambiguous_timestamp(dt);
424    /// assert!(ts.is_ambiguous());
425    ///
426    /// # Ok::<(), Box<dyn std::error::Error>>(())
427    /// ```
428    #[inline]
429    pub fn is_ambiguous(&self) -> bool {
430        !#[allow(non_exhaustive_omitted_patterns)] match self.offset() {
    AmbiguousOffset::Unambiguous { .. } => true,
    _ => false,
}matches!(self.offset(), AmbiguousOffset::Unambiguous { .. })
431    }
432
433    /// Disambiguates this timestamp according to the
434    /// [`Disambiguation::Compatible`] strategy.
435    ///
436    /// If this timestamp is unambiguous, then this is a no-op.
437    ///
438    /// The "compatible" strategy selects the offset corresponding to the civil
439    /// time after a gap, and the offset corresponding to the civil time before
440    /// a fold. This is what is specified in [RFC 5545].
441    ///
442    /// [RFC 5545]: https://datatracker.ietf.org/doc/html/rfc5545
443    ///
444    /// # Errors
445    ///
446    /// This returns an error when the combination of the civil datetime
447    /// and offset would lead to a `Timestamp` outside of the
448    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
449    /// when the civil datetime is "close" to its own [`DateTime::MIN`]
450    /// and [`DateTime::MAX`] limits.
451    ///
452    /// # Example
453    ///
454    /// ```
455    /// use jiff::{civil::date, tz};
456    ///
457    /// let tz = tz::db().get("America/New_York")?;
458    ///
459    /// // Not ambiguous.
460    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
461    /// let ts = tz.to_ambiguous_timestamp(dt);
462    /// assert_eq!(
463    ///     ts.compatible()?.to_string(),
464    ///     "2024-07-15T21:30:00Z",
465    /// );
466    ///
467    /// // Ambiguous because of a gap.
468    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
469    /// let ts = tz.to_ambiguous_timestamp(dt);
470    /// assert_eq!(
471    ///     ts.compatible()?.to_string(),
472    ///     "2024-03-10T07:30:00Z",
473    /// );
474    ///
475    /// // Ambiguous because of a fold.
476    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
477    /// let ts = tz.to_ambiguous_timestamp(dt);
478    /// assert_eq!(
479    ///     ts.compatible()?.to_string(),
480    ///     "2024-11-03T05:30:00Z",
481    /// );
482    ///
483    /// # Ok::<(), Box<dyn std::error::Error>>(())
484    /// ```
485    #[inline]
486    pub fn compatible(self) -> Result<Timestamp, Error> {
487        let offset = match self.offset() {
488            AmbiguousOffset::Unambiguous { offset } => offset,
489            AmbiguousOffset::Gap { before, .. } => before,
490            AmbiguousOffset::Fold { before, .. } => before,
491        };
492        offset.to_timestamp(self.dt)
493    }
494
495    /// Disambiguates this timestamp according to the
496    /// [`Disambiguation::Earlier`] strategy.
497    ///
498    /// If this timestamp is unambiguous, then this is a no-op.
499    ///
500    /// The "earlier" strategy selects the offset corresponding to the civil
501    /// time before a gap, and the offset corresponding to the civil time
502    /// before a fold.
503    ///
504    /// # Errors
505    ///
506    /// This returns an error when the combination of the civil datetime
507    /// and offset would lead to a `Timestamp` outside of the
508    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
509    /// when the civil datetime is "close" to its own [`DateTime::MIN`]
510    /// and [`DateTime::MAX`] limits.
511    ///
512    /// # Example
513    ///
514    /// ```
515    /// use jiff::{civil::date, tz};
516    ///
517    /// let tz = tz::db().get("America/New_York")?;
518    ///
519    /// // Not ambiguous.
520    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
521    /// let ts = tz.to_ambiguous_timestamp(dt);
522    /// assert_eq!(
523    ///     ts.earlier()?.to_string(),
524    ///     "2024-07-15T21:30:00Z",
525    /// );
526    ///
527    /// // Ambiguous because of a gap.
528    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
529    /// let ts = tz.to_ambiguous_timestamp(dt);
530    /// assert_eq!(
531    ///     ts.earlier()?.to_string(),
532    ///     "2024-03-10T06:30:00Z",
533    /// );
534    ///
535    /// // Ambiguous because of a fold.
536    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
537    /// let ts = tz.to_ambiguous_timestamp(dt);
538    /// assert_eq!(
539    ///     ts.earlier()?.to_string(),
540    ///     "2024-11-03T05:30:00Z",
541    /// );
542    ///
543    /// # Ok::<(), Box<dyn std::error::Error>>(())
544    /// ```
545    #[inline]
546    pub fn earlier(self) -> Result<Timestamp, Error> {
547        let offset = match self.offset() {
548            AmbiguousOffset::Unambiguous { offset } => offset,
549            AmbiguousOffset::Gap { after, .. } => after,
550            AmbiguousOffset::Fold { before, .. } => before,
551        };
552        offset.to_timestamp(self.dt)
553    }
554
555    /// Disambiguates this timestamp according to the
556    /// [`Disambiguation::Later`] strategy.
557    ///
558    /// If this timestamp is unambiguous, then this is a no-op.
559    ///
560    /// The "later" strategy selects the offset corresponding to the civil
561    /// time after a gap, and the offset corresponding to the civil time
562    /// after a fold.
563    ///
564    /// # Errors
565    ///
566    /// This returns an error when the combination of the civil datetime
567    /// and offset would lead to a `Timestamp` outside of the
568    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
569    /// when the civil datetime is "close" to its own [`DateTime::MIN`]
570    /// and [`DateTime::MAX`] limits.
571    ///
572    /// # Example
573    ///
574    /// ```
575    /// use jiff::{civil::date, tz};
576    ///
577    /// let tz = tz::db().get("America/New_York")?;
578    ///
579    /// // Not ambiguous.
580    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
581    /// let ts = tz.to_ambiguous_timestamp(dt);
582    /// assert_eq!(
583    ///     ts.later()?.to_string(),
584    ///     "2024-07-15T21:30:00Z",
585    /// );
586    ///
587    /// // Ambiguous because of a gap.
588    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
589    /// let ts = tz.to_ambiguous_timestamp(dt);
590    /// assert_eq!(
591    ///     ts.later()?.to_string(),
592    ///     "2024-03-10T07:30:00Z",
593    /// );
594    ///
595    /// // Ambiguous because of a fold.
596    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
597    /// let ts = tz.to_ambiguous_timestamp(dt);
598    /// assert_eq!(
599    ///     ts.later()?.to_string(),
600    ///     "2024-11-03T06:30:00Z",
601    /// );
602    ///
603    /// # Ok::<(), Box<dyn std::error::Error>>(())
604    /// ```
605    #[inline]
606    pub fn later(self) -> Result<Timestamp, Error> {
607        let offset = match self.offset() {
608            AmbiguousOffset::Unambiguous { offset } => offset,
609            AmbiguousOffset::Gap { before, .. } => before,
610            AmbiguousOffset::Fold { after, .. } => after,
611        };
612        offset.to_timestamp(self.dt)
613    }
614
615    /// Disambiguates this timestamp according to the
616    /// [`Disambiguation::Reject`] strategy.
617    ///
618    /// If this timestamp is unambiguous, then this is a no-op.
619    ///
620    /// The "reject" strategy always returns an error when the timestamp
621    /// is ambiguous.
622    ///
623    /// # Errors
624    ///
625    /// This returns an error when the combination of the civil datetime
626    /// and offset would lead to a `Timestamp` outside of the
627    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
628    /// when the civil datetime is "close" to its own [`DateTime::MIN`]
629    /// and [`DateTime::MAX`] limits.
630    ///
631    /// This also returns an error when the timestamp is ambiguous.
632    ///
633    /// # Example
634    ///
635    /// ```
636    /// use jiff::{civil::date, tz};
637    ///
638    /// let tz = tz::db().get("America/New_York")?;
639    ///
640    /// // Not ambiguous.
641    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
642    /// let ts = tz.to_ambiguous_timestamp(dt);
643    /// assert_eq!(
644    ///     ts.later()?.to_string(),
645    ///     "2024-07-15T21:30:00Z",
646    /// );
647    ///
648    /// // Ambiguous because of a gap.
649    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
650    /// let ts = tz.to_ambiguous_timestamp(dt);
651    /// assert!(ts.unambiguous().is_err());
652    ///
653    /// // Ambiguous because of a fold.
654    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
655    /// let ts = tz.to_ambiguous_timestamp(dt);
656    /// assert!(ts.unambiguous().is_err());
657    ///
658    /// # Ok::<(), Box<dyn std::error::Error>>(())
659    /// ```
660    #[inline]
661    pub fn unambiguous(self) -> Result<Timestamp, Error> {
662        let offset = match self.offset() {
663            AmbiguousOffset::Unambiguous { offset } => offset,
664            AmbiguousOffset::Gap { before, after } => {
665                return Err(Error::from(E::BecauseGap { before, after }));
666            }
667            AmbiguousOffset::Fold { before, after } => {
668                return Err(Error::from(E::BecauseFold { before, after }));
669            }
670        };
671        offset.to_timestamp(self.dt)
672    }
673
674    /// Disambiguates this (possibly ambiguous) timestamp into a specific
675    /// timestamp.
676    ///
677    /// This is the same as calling one of the disambiguation methods, but
678    /// the method chosen is indicated by the option given. This is useful
679    /// when the disambiguation option needs to be chosen at runtime.
680    ///
681    /// # Errors
682    ///
683    /// This returns an error if this would have returned a timestamp
684    /// outside of its minimum and maximum values.
685    ///
686    /// This can also return an error when using the [`Disambiguation::Reject`]
687    /// strategy. Namely, when using the `Reject` strategy, any ambiguous
688    /// timestamp always results in an error.
689    ///
690    /// # Example
691    ///
692    /// This example shows the various disambiguation modes when given a
693    /// datetime that falls in a "fold" (i.e., a backwards DST transition).
694    ///
695    /// ```
696    /// use jiff::{civil::date, tz::{self, Disambiguation}};
697    ///
698    /// let newyork = tz::db().get("America/New_York")?;
699    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
700    /// let ambiguous = newyork.to_ambiguous_timestamp(dt);
701    ///
702    /// // In compatible mode, backward transitions select the earlier
703    /// // time. In the EDT->EST transition, that's the -04 (EDT) offset.
704    /// let ts = ambiguous.clone().disambiguate(Disambiguation::Compatible)?;
705    /// assert_eq!(ts.to_string(), "2024-11-03T05:30:00Z");
706    ///
707    /// // The earlier time in the EDT->EST transition is the -04 (EDT) offset.
708    /// let ts = ambiguous.clone().disambiguate(Disambiguation::Earlier)?;
709    /// assert_eq!(ts.to_string(), "2024-11-03T05:30:00Z");
710    ///
711    /// // The later time in the EDT->EST transition is the -05 (EST) offset.
712    /// let ts = ambiguous.clone().disambiguate(Disambiguation::Later)?;
713    /// assert_eq!(ts.to_string(), "2024-11-03T06:30:00Z");
714    ///
715    /// // Since our datetime is ambiguous, the 'reject' strategy errors.
716    /// assert!(ambiguous.disambiguate(Disambiguation::Reject).is_err());
717    ///
718    /// # Ok::<(), Box<dyn std::error::Error>>(())
719    /// ```
720    #[inline]
721    pub fn disambiguate(
722        self,
723        option: Disambiguation,
724    ) -> Result<Timestamp, Error> {
725        match option {
726            Disambiguation::Compatible => self.compatible(),
727            Disambiguation::Earlier => self.earlier(),
728            Disambiguation::Later => self.later(),
729            Disambiguation::Reject => self.unambiguous(),
730        }
731    }
732
733    /// Convert this ambiguous timestamp into an ambiguous zoned date time by
734    /// attaching a time zone.
735    ///
736    /// This is useful when you have a [`civil::DateTime`], [`TimeZone`] and
737    /// want to convert it to an instant while applying a particular
738    /// disambiguation strategy without an extra clone of the `TimeZone`.
739    ///
740    /// This isn't currently exposed because I believe use cases for crate
741    /// users can be satisfied via [`TimeZone::into_ambiguous_zoned_datetime`]
742    /// (which is implemented via this routine).
743    #[inline]
744    pub(crate) fn into_ambiguous_zoned_datetime(
745        self,
746        tz: TimeZone,
747    ) -> AmbiguousZonedDateTime {
748        AmbiguousZonedDateTime::new(self, tz)
749    }
750}
751
752/// A possibly ambiguous [`ZonedDateTime`], created by
753/// [`TimeZone::to_ambiguous_zoned_datetime`].
754///
755/// While this is called an ambiguous zoned datetime, the thing that is
756/// actually ambiguous is the offset. That is, an ambiguous zoned datetime
757/// is actually a triple of a [`civil::DateTime`](crate::civil::DateTime), a
758/// [`TimeZone`] and an [`AmbiguousOffset`].
759///
760/// When the offset is ambiguous, it either represents a gap (civil time is
761/// skipped) or a fold (civil time is repeated). In both cases, there are, by
762/// construction, two different offsets to choose from: the offset from before
763/// the transition and the offset from after the transition.
764///
765/// The purpose of this type is to represent that ambiguity (when it occurs)
766/// and enable callers to make a choice about how to resolve that ambiguity.
767/// In some cases, you might want to reject ambiguity altogether, which is
768/// supported by the [`AmbiguousZonedDateTime::unambiguous`] routine.
769///
770/// This type provides four different out-of-the-box disambiguation strategies:
771///
772/// * [`AmbiguousZonedDateTime::compatible`] implements the
773/// [`Disambiguation::Compatible`] strategy. In the case of a gap, the offset
774/// after the gap is selected. In the case of a fold, the offset before the
775/// fold occurs is selected.
776/// * [`AmbiguousZonedDateTime::earlier`] implements the
777/// [`Disambiguation::Earlier`] strategy. This always selects the "earlier"
778/// offset.
779/// * [`AmbiguousZonedDateTime::later`] implements the
780/// [`Disambiguation::Later`] strategy. This always selects the "later"
781/// offset.
782/// * [`AmbiguousZonedDateTime::unambiguous`] implements the
783/// [`Disambiguation::Reject`] strategy. It acts as an assertion that the
784/// offset is unambiguous. If it is ambiguous, then an appropriate error is
785/// returned.
786///
787/// The [`AmbiguousZonedDateTime::disambiguate`] method can be used with the
788/// [`Disambiguation`] enum when the disambiguation strategy isn't known until
789/// runtime.
790///
791/// Note also that these aren't the only disambiguation strategies. The
792/// [`AmbiguousOffset`] type, accessible via
793/// [`AmbiguousZonedDateTime::offset`], exposes the full details of the
794/// ambiguity. So any strategy can be implemented.
795///
796/// # Example
797///
798/// This example shows how the "compatible" disambiguation strategy is
799/// implemented. Recall that the "compatible" strategy chooses the offset
800/// corresponding to the civil datetime after a gap, and the offset
801/// corresponding to the civil datetime before a gap.
802///
803/// ```
804/// use jiff::{civil::date, tz::{self, AmbiguousOffset}};
805///
806/// let tz = tz::db().get("America/New_York")?;
807/// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
808/// let ambiguous = tz.to_ambiguous_zoned_datetime(dt);
809/// let offset = match ambiguous.offset() {
810///     AmbiguousOffset::Unambiguous { offset } => offset,
811///     // This is counter-intuitive, but in order to get the civil datetime
812///     // *after* the gap, we need to select the offset from *before* the
813///     // gap.
814///     AmbiguousOffset::Gap { before, .. } => before,
815///     AmbiguousOffset::Fold { before, .. } => before,
816/// };
817/// let zdt = offset
818///     .to_timestamp(dt)?
819///     .to_zoned_datetime(ambiguous.into_time_zone());
820/// assert_eq!(zdt.to_string(), "2024-03-10T03:30:00-04:00[America/New_York]");
821///
822/// # Ok::<(), Box<dyn std::error::Error>>(())
823/// ```
824#[derive(#[automatically_derived]impl ::core::clone::Clone for AmbiguousZonedDateTime {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        AmbiguousZonedDateTime {
            ts: ::core::clone::Clone::clone(&self.ts),
            tz: ::core::clone::Clone::clone(&self.tz),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for AmbiguousZonedDateTime {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "AmbiguousZonedDateTime ts tz", &self.ts, &&self.tz)
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for AmbiguousZonedDateTime {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<AmbiguousTimestamp>;
        let _: ::core::cmp::AssertParamIsEq<TimeZone>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    AmbiguousZonedDateTime {
}
#[automatically_derived]impl ::core::cmp::PartialEq for AmbiguousZonedDateTime
    {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.ts == other.ts && self.tz == other.tz
    }
}PartialEq)]
825#[cfg_attr(feature = "defmt", derive(defmt::Format))]
826pub struct AmbiguousZonedDateTime {
827    ts: AmbiguousTimestamp,
828    tz: TimeZone,
829}
830
831impl AmbiguousZonedDateTime {
832    #[inline]
833    fn new(ts: AmbiguousTimestamp, tz: TimeZone) -> AmbiguousZonedDateTime {
834        AmbiguousZonedDateTime { ts, tz }
835    }
836
837    /// Returns a reference to the time zone that was used to create this
838    /// ambiguous zoned datetime.
839    ///
840    /// # Example
841    ///
842    /// ```
843    /// use jiff::{civil::date, tz};
844    ///
845    /// let tz = tz::db().get("America/New_York")?;
846    /// let dt = date(2024, 7, 10).at(17, 15, 0, 0);
847    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
848    /// assert_eq!(&tz, zdt.time_zone());
849    ///
850    /// # Ok::<(), Box<dyn std::error::Error>>(())
851    /// ```
852    #[inline]
853    pub fn time_zone(&self) -> &TimeZone {
854        &self.tz
855    }
856
857    /// Consumes this ambiguous zoned datetime and returns the underlying
858    /// `TimeZone`. This is useful if you no longer need the ambiguous zoned
859    /// datetime and want its `TimeZone` without cloning it. (Cloning a
860    /// `TimeZone` is cheap but not free.)
861    ///
862    /// # Example
863    ///
864    /// ```
865    /// use jiff::{civil::date, tz};
866    ///
867    /// let tz = tz::db().get("America/New_York")?;
868    /// let dt = date(2024, 7, 10).at(17, 15, 0, 0);
869    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
870    /// assert_eq!(tz, zdt.into_time_zone());
871    ///
872    /// # Ok::<(), Box<dyn std::error::Error>>(())
873    /// ```
874    #[inline]
875    pub fn into_time_zone(self) -> TimeZone {
876        self.tz
877    }
878
879    /// Returns the civil datetime that was used to create this ambiguous
880    /// zoned datetime.
881    ///
882    /// # Example
883    ///
884    /// ```
885    /// use jiff::{civil::date, tz};
886    ///
887    /// let tz = tz::db().get("America/New_York")?;
888    /// let dt = date(2024, 7, 10).at(17, 15, 0, 0);
889    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
890    /// assert_eq!(zdt.datetime(), dt);
891    ///
892    /// # Ok::<(), Box<dyn std::error::Error>>(())
893    /// ```
894    #[inline]
895    pub fn datetime(&self) -> DateTime {
896        self.ts.datetime()
897    }
898
899    /// Returns the possibly ambiguous offset that is the ultimate source of
900    /// ambiguity.
901    ///
902    /// Most civil datetimes are not ambiguous, and thus, the offset will not
903    /// be ambiguous either. In this case, the offset returned will be the
904    /// [`AmbiguousOffset::Unambiguous`] variant.
905    ///
906    /// But, not all civil datetimes are unambiguous. There are exactly two
907    /// cases where a civil datetime can be ambiguous: when a civil datetime
908    /// does not exist (a gap) or when a civil datetime is repeated (a fold).
909    /// In both such cases, the _offset_ is the thing that is ambiguous as
910    /// there are two possible choices for the offset in both cases: the offset
911    /// before the transition (whether it's a gap or a fold) or the offset
912    /// after the transition.
913    ///
914    /// This type captures the fact that computing an offset from a civil
915    /// datetime in a particular time zone is in one of three possible states:
916    ///
917    /// 1. It is unambiguous.
918    /// 2. It is ambiguous because there is a gap in time.
919    /// 3. It is ambiguous because there is a fold in time.
920    ///
921    /// # Example
922    ///
923    /// ```
924    /// use jiff::{civil::date, tz::{self, AmbiguousOffset}};
925    ///
926    /// let tz = tz::db().get("America/New_York")?;
927    ///
928    /// // Not ambiguous.
929    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
930    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
931    /// assert_eq!(zdt.offset(), AmbiguousOffset::Unambiguous {
932    ///     offset: tz::offset(-4),
933    /// });
934    ///
935    /// // Ambiguous because of a gap.
936    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
937    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
938    /// assert_eq!(zdt.offset(), AmbiguousOffset::Gap {
939    ///     before: tz::offset(-5),
940    ///     after: tz::offset(-4),
941    /// });
942    ///
943    /// // Ambiguous because of a fold.
944    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
945    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
946    /// assert_eq!(zdt.offset(), AmbiguousOffset::Fold {
947    ///     before: tz::offset(-4),
948    ///     after: tz::offset(-5),
949    /// });
950    ///
951    /// # Ok::<(), Box<dyn std::error::Error>>(())
952    /// ```
953    #[inline]
954    pub fn offset(&self) -> AmbiguousOffset {
955        self.ts.offset
956    }
957
958    /// Returns true if and only if this possibly ambiguous zoned datetime is
959    /// actually ambiguous.
960    ///
961    /// This occurs precisely in cases when the offset is _not_
962    /// [`AmbiguousOffset::Unambiguous`].
963    ///
964    /// # Example
965    ///
966    /// ```
967    /// use jiff::{civil::date, tz};
968    ///
969    /// let tz = tz::db().get("America/New_York")?;
970    ///
971    /// // Not ambiguous.
972    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
973    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
974    /// assert!(!zdt.is_ambiguous());
975    ///
976    /// // Ambiguous because of a gap.
977    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
978    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
979    /// assert!(zdt.is_ambiguous());
980    ///
981    /// // Ambiguous because of a fold.
982    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
983    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
984    /// assert!(zdt.is_ambiguous());
985    ///
986    /// # Ok::<(), Box<dyn std::error::Error>>(())
987    /// ```
988    #[inline]
989    pub fn is_ambiguous(&self) -> bool {
990        !#[allow(non_exhaustive_omitted_patterns)] match self.offset() {
    AmbiguousOffset::Unambiguous { .. } => true,
    _ => false,
}matches!(self.offset(), AmbiguousOffset::Unambiguous { .. })
991    }
992
993    /// Disambiguates this zoned datetime according to the
994    /// [`Disambiguation::Compatible`] strategy.
995    ///
996    /// If this zoned datetime is unambiguous, then this is a no-op.
997    ///
998    /// The "compatible" strategy selects the offset corresponding to the civil
999    /// time after a gap, and the offset corresponding to the civil time before
1000    /// a fold. This is what is specified in [RFC 5545].
1001    ///
1002    /// [RFC 5545]: https://datatracker.ietf.org/doc/html/rfc5545
1003    ///
1004    /// # Errors
1005    ///
1006    /// This returns an error when the combination of the civil datetime and
1007    /// offset would lead to a `ZonedDateTime` with a timestamp outside of the
1008    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs when
1009    /// the civil datetime is "close" to its own [`DateTime::MIN`] and
1010    /// [`DateTime::MAX`] limits.
1011    ///
1012    /// # Example
1013    ///
1014    /// ```
1015    /// use jiff::{civil::date, tz};
1016    ///
1017    /// let tz = tz::db().get("America/New_York")?;
1018    ///
1019    /// // Not ambiguous.
1020    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
1021    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
1022    /// assert_eq!(
1023    ///     zdt.compatible()?.to_string(),
1024    ///     "2024-07-15T17:30:00-04:00[America/New_York]",
1025    /// );
1026    ///
1027    /// // Ambiguous because of a gap.
1028    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
1029    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
1030    /// assert_eq!(
1031    ///     zdt.compatible()?.to_string(),
1032    ///     "2024-03-10T03:30:00-04:00[America/New_York]",
1033    /// );
1034    ///
1035    /// // Ambiguous because of a fold.
1036    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
1037    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
1038    /// assert_eq!(
1039    ///     zdt.compatible()?.to_string(),
1040    ///     "2024-11-03T01:30:00-04:00[America/New_York]",
1041    /// );
1042    ///
1043    /// # Ok::<(), Box<dyn std::error::Error>>(())
1044    /// ```
1045    #[inline]
1046    pub fn compatible(self) -> Result<ZonedDateTime, Error> {
1047        let ts = self
1048            .ts
1049            .compatible()
1050            .with_context(|| E::InTimeZone { tz: self.time_zone().clone() })?;
1051        Ok(ts.to_zoned_datetime(self.tz))
1052    }
1053
1054    /// Disambiguates this zoned datetime according to the
1055    /// [`Disambiguation::Earlier`] strategy.
1056    ///
1057    /// If this zoned datetime is unambiguous, then this is a no-op.
1058    ///
1059    /// The "earlier" strategy selects the offset corresponding to the civil
1060    /// time before a gap, and the offset corresponding to the civil time
1061    /// before a fold.
1062    ///
1063    /// # Errors
1064    ///
1065    /// This returns an error when the combination of the civil datetime and
1066    /// offset would lead to a `ZonedDateTime` with a timestamp outside of the
1067    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs when
1068    /// the civil datetime is "close" to its own [`DateTime::MIN`] and
1069    /// [`DateTime::MAX`] limits.
1070    ///
1071    /// # Example
1072    ///
1073    /// ```
1074    /// use jiff::{civil::date, tz};
1075    ///
1076    /// let tz = tz::db().get("America/New_York")?;
1077    ///
1078    /// // Not ambiguous.
1079    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
1080    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
1081    /// assert_eq!(
1082    ///     zdt.earlier()?.to_string(),
1083    ///     "2024-07-15T17:30:00-04:00[America/New_York]",
1084    /// );
1085    ///
1086    /// // Ambiguous because of a gap.
1087    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
1088    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
1089    /// assert_eq!(
1090    ///     zdt.earlier()?.to_string(),
1091    ///     "2024-03-10T01:30:00-05:00[America/New_York]",
1092    /// );
1093    ///
1094    /// // Ambiguous because of a fold.
1095    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
1096    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
1097    /// assert_eq!(
1098    ///     zdt.earlier()?.to_string(),
1099    ///     "2024-11-03T01:30:00-04:00[America/New_York]",
1100    /// );
1101    ///
1102    /// # Ok::<(), Box<dyn std::error::Error>>(())
1103    /// ```
1104    #[inline]
1105    pub fn earlier(self) -> Result<ZonedDateTime, Error> {
1106        let ts = self
1107            .ts
1108            .earlier()
1109            .with_context(|| E::InTimeZone { tz: self.time_zone().clone() })?;
1110        Ok(ts.to_zoned_datetime(self.tz))
1111    }
1112
1113    /// Disambiguates this zoned datetime according to the
1114    /// [`Disambiguation::Later`] strategy.
1115    ///
1116    /// If this zoned datetime is unambiguous, then this is a no-op.
1117    ///
1118    /// The "later" strategy selects the offset corresponding to the civil
1119    /// time after a gap, and the offset corresponding to the civil time
1120    /// after a fold.
1121    ///
1122    /// # Errors
1123    ///
1124    /// This returns an error when the combination of the civil datetime and
1125    /// offset would lead to a `ZonedDateTime` with a timestamp outside of the
1126    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs when
1127    /// the civil datetime is "close" to its own [`DateTime::MIN`] and
1128    /// [`DateTime::MAX`] limits.
1129    ///
1130    /// # Example
1131    ///
1132    /// ```
1133    /// use jiff::{civil::date, tz};
1134    ///
1135    /// let tz = tz::db().get("America/New_York")?;
1136    ///
1137    /// // Not ambiguous.
1138    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
1139    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
1140    /// assert_eq!(
1141    ///     zdt.later()?.to_string(),
1142    ///     "2024-07-15T17:30:00-04:00[America/New_York]",
1143    /// );
1144    ///
1145    /// // Ambiguous because of a gap.
1146    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
1147    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
1148    /// assert_eq!(
1149    ///     zdt.later()?.to_string(),
1150    ///     "2024-03-10T03:30:00-04:00[America/New_York]",
1151    /// );
1152    ///
1153    /// // Ambiguous because of a fold.
1154    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
1155    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
1156    /// assert_eq!(
1157    ///     zdt.later()?.to_string(),
1158    ///     "2024-11-03T01:30:00-05:00[America/New_York]",
1159    /// );
1160    ///
1161    /// # Ok::<(), Box<dyn std::error::Error>>(())
1162    /// ```
1163    #[inline]
1164    pub fn later(self) -> Result<ZonedDateTime, Error> {
1165        let ts = self
1166            .ts
1167            .later()
1168            .with_context(|| E::InTimeZone { tz: self.time_zone().clone() })?;
1169        Ok(ts.to_zoned_datetime(self.tz))
1170    }
1171
1172    /// Disambiguates this zoned datetime according to the
1173    /// [`Disambiguation::Reject`] strategy.
1174    ///
1175    /// If this zoned datetime is unambiguous, then this is a no-op.
1176    ///
1177    /// The "reject" strategy always returns an error when the zoned datetime
1178    /// is ambiguous.
1179    ///
1180    /// # Errors
1181    ///
1182    /// This returns an error when the combination of the civil datetime and
1183    /// offset would lead to a `ZonedDateTime` with a timestamp outside of the
1184    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs when
1185    /// the civil datetime is "close" to its own [`DateTime::MIN`] and
1186    /// [`DateTime::MAX`] limits.
1187    ///
1188    /// This also returns an error when the timestamp is ambiguous.
1189    ///
1190    /// # Example
1191    ///
1192    /// ```
1193    /// use jiff::{civil::date, tz};
1194    ///
1195    /// let tz = tz::db().get("America/New_York")?;
1196    ///
1197    /// // Not ambiguous.
1198    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
1199    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
1200    /// assert_eq!(
1201    ///     zdt.later()?.to_string(),
1202    ///     "2024-07-15T17:30:00-04:00[America/New_York]",
1203    /// );
1204    ///
1205    /// // Ambiguous because of a gap.
1206    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
1207    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
1208    /// assert!(zdt.unambiguous().is_err());
1209    ///
1210    /// // Ambiguous because of a fold.
1211    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
1212    /// let zdt = tz.to_ambiguous_zoned_datetime(dt);
1213    /// assert!(zdt.unambiguous().is_err());
1214    ///
1215    /// # Ok::<(), Box<dyn std::error::Error>>(())
1216    /// ```
1217    #[inline]
1218    pub fn unambiguous(self) -> Result<ZonedDateTime, Error> {
1219        let ts = self
1220            .ts
1221            .unambiguous()
1222            .with_context(|| E::InTimeZone { tz: self.time_zone().clone() })?;
1223        Ok(ts.to_zoned_datetime(self.tz))
1224    }
1225
1226    /// Disambiguates this (possibly ambiguous) timestamp into a concrete
1227    /// time zone aware timestamp.
1228    ///
1229    /// This is the same as calling one of the disambiguation methods, but
1230    /// the method chosen is indicated by the option given. This is useful
1231    /// when the disambiguation option needs to be chosen at runtime.
1232    ///
1233    /// # Errors
1234    ///
1235    /// This returns an error if this would have returned a zoned datetime
1236    /// outside of its minimum and maximum values.
1237    ///
1238    /// This can also return an error when using the [`Disambiguation::Reject`]
1239    /// strategy. Namely, when using the `Reject` strategy, any ambiguous
1240    /// timestamp always results in an error.
1241    ///
1242    /// # Example
1243    ///
1244    /// This example shows the various disambiguation modes when given a
1245    /// datetime that falls in a "fold" (i.e., a backwards DST transition).
1246    ///
1247    /// ```
1248    /// use jiff::{civil::date, tz::{self, Disambiguation}};
1249    ///
1250    /// let newyork = tz::db().get("America/New_York")?;
1251    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
1252    /// let ambiguous = newyork.to_ambiguous_zoned_datetime(dt);
1253    ///
1254    /// // In compatible mode, backward transitions select the earlier
1255    /// // time. In the EDT->EST transition, that's the -04 (EDT) offset.
1256    /// let zdt = ambiguous.clone().disambiguate(Disambiguation::Compatible)?;
1257    /// assert_eq!(
1258    ///     zdt.to_string(),
1259    ///     "2024-11-03T01:30:00-04:00[America/New_York]",
1260    /// );
1261    ///
1262    /// // The earlier time in the EDT->EST transition is the -04 (EDT) offset.
1263    /// let zdt = ambiguous.clone().disambiguate(Disambiguation::Earlier)?;
1264    /// assert_eq!(
1265    ///     zdt.to_string(),
1266    ///     "2024-11-03T01:30:00-04:00[America/New_York]",
1267    /// );
1268    ///
1269    /// // The later time in the EDT->EST transition is the -05 (EST) offset.
1270    /// let zdt = ambiguous.clone().disambiguate(Disambiguation::Later)?;
1271    /// assert_eq!(
1272    ///     zdt.to_string(),
1273    ///     "2024-11-03T01:30:00-05:00[America/New_York]",
1274    /// );
1275    ///
1276    /// // Since our datetime is ambiguous, the 'reject' strategy errors.
1277    /// assert!(ambiguous.disambiguate(Disambiguation::Reject).is_err());
1278    ///
1279    /// # Ok::<(), Box<dyn std::error::Error>>(())
1280    /// ```
1281    #[inline]
1282    pub fn disambiguate(
1283        self,
1284        option: Disambiguation,
1285    ) -> Result<ZonedDateTime, Error> {
1286        match option {
1287            Disambiguation::Compatible => self.compatible(),
1288            Disambiguation::Earlier => self.earlier(),
1289            Disambiguation::Later => self.later(),
1290            Disambiguation::Reject => self.unambiguous(),
1291        }
1292    }
1293}