Skip to main content

jiff_core/tz/
offset.rs

1use crate::{
2    Timestamp,
3    bounds::{self as b, RangeError},
4    civil::{self, DateTime},
5    constants as c,
6    macros::{rtry, unwrapr},
7};
8
9/// A fixed offset, in seconds, from UTC.
10#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Offset {
}
#[automatically_derived]impl ::core::clone::Clone for Offset {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<i32>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Offset { }Copy, #[automatically_derived]impl ::core::cmp::Eq for Offset {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<i32>;
    }
}Eq, #[automatically_derived]impl ::core::hash::Hash for Offset {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.seconds, state)
    }
}Hash, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Offset {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Offset {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.seconds == other.seconds }
}PartialEq, #[automatically_derived]impl ::core::cmp::PartialOrd for Offset {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]impl ::core::cmp::Ord for Offset {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&self.seconds, &other.seconds)
    }
}Ord)]
11pub struct Offset {
12    seconds: i32,
13}
14
15impl Offset {
16    /// The minimum possible offset from UTC.
17    pub const MIN: Offset = Offset { seconds: b::OffsetTotalSeconds::MIN };
18
19    /// The maximum possible offset from UTC.
20    pub const MAX: Offset = Offset { seconds: b::OffsetTotalSeconds::MAX };
21
22    /// The UTC offset.
23    pub const UTC: Offset = Offset { seconds: 0 };
24
25    /// The zero offset.
26    pub const ZERO: Offset = Offset { seconds: 0 };
27
28    /// Creates a new time zone offset in a `const` context from a given number
29    /// of hours.
30    #[inline]
31    pub const fn constant(hours: i8) -> Offset {
32        match Offset::from_hours(hours) {
    Ok(val) => val,
    Err(_) => {
        ::core::panicking::panic_fmt(format_args!("invalid time zone offset hours"));
    }
}unwrapr!(Offset::from_hours(hours), "invalid time zone offset hours")
33    }
34
35    /// Creates a new time zone offset in a `const` context from a given number
36    /// of seconds.
37    #[inline]
38    pub const fn constant_seconds(seconds: i32) -> Offset {
39        match Offset::from_seconds(seconds) {
    Ok(val) => val,
    Err(_) => {
        ::core::panicking::panic_fmt(format_args!("invalid time zone offset seconds"));
    }
}unwrapr!(
40            Offset::from_seconds(seconds),
41            "invalid time zone offset seconds",
42        )
43    }
44
45    /// Creates a new time zone offset from a given number of hours.
46    ///
47    /// Negative offsets correspond to time zones west of the prime meridian,
48    /// while positive offsets correspond to time zones east of the prime
49    /// meridian. Equivalently, in all cases, `civil-time - offset = UTC`.
50    #[inline]
51    pub const fn from_hours(hours: i8) -> Result<Offset, RangeError> {
52        Offset::from_seconds(hours as i32 * c::SECS_PER_HOUR_32)
53    }
54
55    /// Returns a new time zone offset from UTC given its representation in
56    /// seconds.
57    ///
58    /// An error is also returned when `seconds` is not in the range specified
59    /// by [`OffsetTotalSeconds`](b::OffsetTotalSeconds).
60    #[inline]
61    pub const fn from_seconds(seconds: i32) -> Result<Offset, RangeError> {
62        let seconds = match b::OffsetTotalSeconds::checkc(seconds as i64) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::OffsetTotalSeconds::checkc(seconds as i64));
63        Ok(Offset { seconds })
64    }
65
66    /// Returns the seconds value corresponding to this time zone offset.
67    #[inline]
68    pub const fn seconds(self) -> i32 {
69        self.seconds
70    }
71
72    /// Returns the negation of this offset.
73    ///
74    /// A negative offset will become positive and vice versa. This is a no-op
75    /// if the offset is zero.
76    ///
77    /// This never panics.
78    #[inline]
79    pub const fn negate(self) -> Offset {
80        // OK because of the boundaries we enforce. `seconds` can never be
81        // `i32::MIN`.
82        Offset { seconds: -self.seconds() }
83    }
84
85    /// Returns the "sign number" or "signum" of this offset.
86    ///
87    /// The number returned is `-1` when this offset is negative,
88    /// `0` when this offset is zero and `1` when this span is positive.
89    #[inline]
90    pub const fn signum(self) -> i8 {
91        self.seconds().signum() as i8
92    }
93
94    /// Returns true if and only if this offset is positive.
95    ///
96    /// This returns false when the offset is zero or negative.
97    #[inline]
98    pub const fn is_positive(self) -> bool {
99        self.seconds() > 0
100    }
101
102    /// Returns true if and only if this offset is less than zero.
103    ///
104    /// This returns false when the offset is zero or positive.
105    #[inline]
106    pub const fn is_negative(self) -> bool {
107        self.seconds() < 0
108    }
109
110    /// Returns true if and only if this offset is zero.
111    ///
112    /// Or equivalently, when this offset corresponds to [`Offset::UTC`].
113    #[inline]
114    pub const fn is_zero(self) -> bool {
115        self.seconds() == 0
116    }
117
118    /// Adds the given number of seconds to this offset.
119    ///
120    /// If the resulting offset would be outside the an offset's boundaries,
121    /// an error is returned.
122    #[inline]
123    pub const fn checked_add(
124        self,
125        seconds: i32,
126    ) -> Result<Offset, RangeError> {
127        let seconds =
128            match b::OffsetTotalSeconds::checked_add(self.seconds(), seconds) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::OffsetTotalSeconds::checked_add(self.seconds(), seconds));
129        Ok(Offset { seconds })
130    }
131
132    /// Subtracts the given number of seconds from this offset.
133    ///
134    /// If the resulting offset would be outside the an offset's boundaries,
135    /// an error is returned.
136    #[inline]
137    pub const fn checked_sub(
138        self,
139        seconds: i32,
140    ) -> Result<Offset, RangeError> {
141        let seconds = match b::OffsetTotalSeconds::checkc(self.seconds() as i64 - seconds as i64) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::OffsetTotalSeconds::checkc(
142            self.seconds() as i64 - seconds as i64,
143        ));
144        Ok(Offset { seconds })
145    }
146
147    /// Returns the number of seconds from this offset to `other`.
148    #[inline]
149    pub const fn until(self, other: Offset) -> i32 {
150        other.seconds() - self.seconds()
151    }
152
153    /// Returns the number of seconds since this offset from `other`.
154    #[inline]
155    pub const fn since(self, other: Offset) -> i32 {
156        self.seconds() - other.seconds()
157    }
158
159    /// Converts a Unix timestamp with an offset to a Gregorian datetime.
160    ///
161    /// The offset should correspond to the number of seconds required to
162    /// add to this timestamp to get the local time.
163    #[inline]
164    pub const fn to_datetime(self, timestamp: Timestamp) -> civil::DateTime {
165        let offset = self;
166        let second = timestamp.as_second();
167        let mut nanosecond = timestamp.subsec_nanosecond();
168
169        // Shift second comfortably into the postive domain
170        // so that division and remainder can use unsigned math
171        // which is much faster.
172        // 30 * 400 years: 12,000 yr range > [-9,999..1970]
173        // (146097 being the number of days per 400 years).
174        const DAY_SHIFT: i32 = 30 * 146097;
175        const SEC_SHIFT: i64 = (DAY_SHIFT as i64) * 86_400;
176
177        let mut pos_sec =
178            (second + (offset.seconds() as i64) + SEC_SHIFT) as u64;
179
180        let is_neg_nano: bool = nanosecond < 0;
181        pos_sec -= is_neg_nano as u64;
182        nanosecond += if is_neg_nano { 1_000_000_000 } else { 0 };
183
184        let mut epoch_day = (pos_sec / 86_400) as i32;
185        let second = (pos_sec % 86_400) as i32;
186
187        epoch_day -= DAY_SHIFT;
188
189        // We should check whether having unchecked APIs
190        // would be beneficial here. In particular, the
191        // math above, coupled with the ranges allowed on
192        // `Timestamp` and `Offset` (by design) guarantee
193        // that our resulting datetime will always be in
194        // range.
195        let date = match civil::UnixEpochDay::new(epoch_day) {
    Ok(val) => val,
    Err(_) => {
        ::core::panicking::panic_fmt(format_args!("always valid Unix epoch day"));
    }
}unwrapr!(
196            civil::UnixEpochDay::new(epoch_day),
197            "always valid Unix epoch day",
198        )
199        .to_date();
200        let time = match match civil::TimeSecond::new(second) {
                Ok(val) => val,
                Err(_) => {
                    ::core::panicking::panic_fmt(format_args!("always valid civil second time"));
                }
            }.to_time().with_subsec_nanosecond(nanosecond) {
    Ok(val) => val,
    Err(_) => {
        ::core::panicking::panic_fmt(format_args!("always valid civil subsecond"));
    }
}unwrapr!(
201            unwrapr!(
202                civil::TimeSecond::new(second),
203                "always valid civil second time"
204            )
205            .to_time()
206            .with_subsec_nanosecond(nanosecond),
207            "always valid civil subsecond"
208        );
209        civil::DateTime::from_parts(date, time)
210    }
211
212    /// Converts the given civil datetime to a timestamp using this offset.
213    ///
214    /// # Errors
215    ///
216    /// This returns an error if this would have returned a timestamp outside
217    /// of its minimum and maximum values.
218    #[inline]
219    pub const fn to_timestamp(
220        self,
221        dt: civil::DateTime,
222    ) -> Result<Timestamp, RangeError> {
223        let offset = self;
224        let epoch_day = dt.date().to_unix_epoch_day().day();
225        let mut second = (epoch_day as i64) * c::SECS_PER_CIVIL_DAY
226            + (dt.time().to_second().second() as i64);
227        let mut nanosecond = dt.time().subsec_nanosecond();
228        second -= offset.seconds() as i64;
229        // Check before normalizing so a fraction below `Timestamp::MIN`
230        // cannot bring the seconds component back into range.
231        second = match b::UnixEpochSeconds::checkc(second) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::UnixEpochSeconds::checkc(second));
232        if second < 0 && nanosecond != 0 {
233            second += 1;
234            nanosecond -= c::NANOS_PER_SEC_32;
235        }
236        Ok(Timestamp::new_unchecked(second, nanosecond))
237    }
238}
239
240impl Offset {
241    #[inline]
242    fn part_hours(self) -> i8 {
243        (self.seconds() / c::SECS_PER_HOUR_32) as i8
244    }
245
246    #[inline]
247    fn part_minutes(self) -> i8 {
248        ((self.seconds() / c::SECS_PER_MIN_32) % c::MINS_PER_HOUR_32) as i8
249    }
250
251    #[inline]
252    fn part_seconds(self) -> i8 {
253        (self.seconds() % c::SECS_PER_MIN_32) as i8
254    }
255}
256
257/// Negate this offset.
258///
259/// A positive offset becomes negative and vice versa. This is a no-op for the
260/// zero offset.
261///
262/// This never panics.
263impl core::ops::Neg for Offset {
264    type Output = Offset;
265
266    #[inline]
267    fn neg(self) -> Offset {
268        self.negate()
269    }
270}
271
272/// Adds a number of seconds to an `Offset`.
273///
274/// # Panics
275///
276/// When adding would result in a value outside the boundaries of a
277/// `Offset`.
278impl core::ops::Add<i32> for Offset {
279    type Output = Offset;
280
281    fn add(self, seconds: i32) -> Offset {
282        self.checked_add(seconds).unwrap()
283    }
284}
285
286/// Adds a number of seconds into an `Offset`.
287///
288/// # Panics
289///
290/// When adding would result in a value outside the boundaries of a
291/// `Offset`.
292impl core::ops::AddAssign<i32> for Offset {
293    #[inline]
294    fn add_assign(&mut self, rhs: i32) {
295        *self = *self + rhs;
296    }
297}
298
299/// Subtracts a number of seconds from an `Offset`.
300///
301/// # Panics
302///
303/// When adding would result in a value outside the boundaries of a
304/// `Offset`.
305impl core::ops::Sub<i32> for Offset {
306    type Output = Offset;
307
308    fn sub(self, seconds: i32) -> Offset {
309        self.checked_sub(seconds).unwrap()
310    }
311}
312
313/// Subtracts a number of seconds from an `Offset` in place.
314///
315/// # Panics
316///
317/// When adding would result in a value outside the boundaries of a
318/// `Offset`.
319impl core::ops::SubAssign<i32> for Offset {
320    #[inline]
321    fn sub_assign(&mut self, rhs: i32) {
322        *self = *self - rhs;
323    }
324}
325
326impl core::fmt::Debug for Offset {
327    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
328        let sign = if self.is_negative() { "-" } else { "" };
329        f.write_fmt(format_args!("{3}{0:02}:{1:02}:{2:02}",
        self.part_hours().unsigned_abs(), self.part_minutes().unsigned_abs(),
        self.part_seconds().unsigned_abs(), sign))write!(
330            f,
331            "{sign}{:02}:{:02}:{:02}",
332            self.part_hours().unsigned_abs(),
333            self.part_minutes().unsigned_abs(),
334            self.part_seconds().unsigned_abs(),
335        )
336    }
337}
338
339impl core::fmt::Display for Offset {
340    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
341        let sign = if self.is_negative() { "-" } else { "+" };
342        let hours = self.part_hours().unsigned_abs();
343        let minutes = self.part_minutes().unsigned_abs();
344        let seconds = self.part_seconds().unsigned_abs();
345        if hours == 0 && minutes == 0 && seconds == 0 {
346            f.write_str("+00")
347        } else if hours != 0 && minutes == 0 && seconds == 0 {
348            f.write_fmt(format_args!("{0}{1:02}", sign, hours))write!(f, "{sign}{hours:02}")
349        } else if minutes != 0 && seconds == 0 {
350            f.write_fmt(format_args!("{0}{1:02}:{2:02}", sign, hours, minutes))write!(f, "{sign}{hours:02}:{minutes:02}")
351        } else {
352            f.write_fmt(format_args!("{0}{1:02}:{2:02}:{3:02}", sign, hours, minutes,
        seconds))write!(f, "{sign}{hours:02}:{minutes:02}:{seconds:02}")
353        }
354    }
355}
356
357#[cfg(feature = "defmt")]
358impl defmt::Format for Offset {
359    fn format(&self, f: defmt::Formatter) {
360        let sign = if self.is_negative() { "-" } else { "" };
361        defmt::write!(
362            f,
363            "{=str}{=u8:02}:{=u8:02}:{=u8:02}",
364            sign,
365            self.part_hours().unsigned_abs(),
366            self.part_minutes().unsigned_abs(),
367            self.part_seconds().unsigned_abs(),
368        )
369    }
370}
371
372#[cfg(feature = "arbitrary")]
373impl<'a> arbitrary::Arbitrary<'a> for Offset {
374    fn arbitrary(
375        u: &mut arbitrary::Unstructured<'a>,
376    ) -> arbitrary::Result<Offset> {
377        let secs = u.int_in_range(
378            b::OffsetTotalSeconds::MIN..=b::OffsetTotalSeconds::MAX,
379        )?;
380        Ok(Offset::from_seconds(secs).unwrap_or(Offset::UTC))
381    }
382
383    fn size_hint(depth: usize) -> (usize, Option<usize>) {
384        <i32 as arbitrary::Arbitrary>::size_hint(depth)
385    }
386}
387
388#[cfg(test)]
389impl quickcheck::Arbitrary for Offset {
390    fn arbitrary(g: &mut quickcheck::Gen) -> Offset {
391        let secs = b::OffsetTotalSeconds::arbitrary(g);
392        Offset::from_seconds(secs).unwrap_or(Offset::UTC)
393    }
394
395    fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Self>> {
396        let secs = self.seconds();
397        alloc::boxed::Box::new(secs.shrink().filter_map(|secs| {
398            let secs = b::OffsetTotalSeconds::check(secs).ok()?;
399            Offset::from_seconds(secs).ok()
400        }))
401    }
402}
403
404/// A possibly ambiguous [`Offset`].
405///
406/// One of three possibilities encoded by this type occurs when converting a
407/// civil datetime into a specific instant in time. In rare cases, the civil
408/// datetime can fall into a gap or a fold, in which case, one of two offsets
409/// could be applicable. Or, perhaps, neither. Callers must decide how best to
410/// handle these cases.
411#[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)]
412#[cfg_attr(feature = "defmt", derive(defmt::Format))]
413pub enum AmbiguousOffset {
414    /// The offset for a particular civil datetime and time zone is
415    /// unambiguous.
416    ///
417    /// This is the overwhelmingly common case. In general, the only time this
418    /// case does not occur is when there is a transition to a different time
419    /// zone (rare) or to/from daylight saving time (occurs for 1 hour twice
420    /// in year in many geographic locations).
421    Unambiguous {
422        /// The offset from UTC for the corresponding civil datetime given. The
423        /// offset is determined via the relevant time zone data, and in this
424        /// case, there is only one possible offset that could be applied to
425        /// the given civil datetime.
426        offset: Offset,
427    },
428    /// The offset for a particular civil datetime and time zone is ambiguous
429    /// because there is a gap.
430    ///
431    /// This most commonly occurs when a civil datetime corresponds to an hour
432    /// that was "skipped" in a jump to DST (daylight saving time).
433    Gap {
434        /// The offset corresponding to the time before a gap.
435        ///
436        /// For example, given a time zone of `America/Los_Angeles`, the offset
437        /// for time immediately preceding `2020-03-08T02:00:00` is `-08`.
438        before: Offset,
439        /// The offset corresponding to the later time in a gap.
440        ///
441        /// For example, given a time zone of `America/Los_Angeles`, the offset
442        /// for time immediately following `2020-03-08T02:59:59` is `-07`.
443        after: Offset,
444    },
445    /// The offset for a particular civil datetime and time zone is ambiguous
446    /// because there is a fold.
447    ///
448    /// This most commonly occurs when a civil datetime corresponds to an hour
449    /// that was "repeated" in a jump to standard time from DST (daylight
450    /// saving time).
451    Fold {
452        /// The offset corresponding to the earlier time in a fold.
453        ///
454        /// For example, given a time zone of `America/Los_Angeles`, the offset
455        /// for time on the first `2020-11-01T01:00:00` is `-07`.
456        before: Offset,
457        /// The offset corresponding to the earlier time in a fold.
458        ///
459        /// For example, given a time zone of `America/Los_Angeles`, the offset
460        /// for time on the second `2020-11-01T01:00:00` is `-08`.
461        after: Offset,
462    },
463}
464
465impl AmbiguousOffset {
466    #[inline]
467    pub(crate) const fn into_ambiguous_timestamp(
468        self,
469        dt: DateTime,
470    ) -> AmbiguousTimestamp {
471        AmbiguousTimestamp { dt, offset: self }
472    }
473}
474
475/// A possibly ambiguous [`Timestamp`].
476///
477/// While this is called an ambiguous _timestamp_, the thing that is
478/// actually ambiguous is the offset. That is, an ambiguous timestamp is
479/// actually a pair of a [`civil::DateTime`](crate::civil::DateTime) and an
480/// [`AmbiguousOffset`].
481#[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)]
482#[cfg_attr(feature = "defmt", derive(defmt::Format))]
483pub struct AmbiguousTimestamp {
484    dt: DateTime,
485    offset: AmbiguousOffset,
486}
487
488impl AmbiguousTimestamp {
489    /// Returns the civil datetime that was used to create this ambiguous
490    /// timestamp.
491    ///
492    /// # Example
493    ///
494    /// ```
495    /// use jiff_core::{civil::date, tz::posix};
496    ///
497    /// let tz = posix::TimeZone::parse("EST5EDT,M3.2.0,M11.1.0").unwrap();
498    /// let dt = date(2024, 7, 10).at(17, 15, 0, 0);
499    /// let ts = tz.to_ambiguous_timestamp(dt);
500    /// assert_eq!(ts.datetime(), dt);
501    ///
502    /// # Ok::<(), Box<dyn std::error::Error>>(())
503    /// ```
504    #[inline]
505    pub const fn datetime(&self) -> DateTime {
506        self.dt
507    }
508
509    /// Returns the possibly ambiguous offset that is the ultimate source of
510    /// ambiguity.
511    ///
512    /// Most civil datetimes are not ambiguous, and thus, the offset will not
513    /// be ambiguous either. In this case, the offset returned will be the
514    /// [`AmbiguousOffset::Unambiguous`] variant.
515    ///
516    /// But, not all civil datetimes are unambiguous. There are exactly two
517    /// cases where a civil datetime can be ambiguous: when a civil datetime
518    /// does not exist (a gap) or when a civil datetime is repeated (a fold).
519    /// In both such cases, the _offset_ is the thing that is ambiguous as
520    /// there are two possible choices for the offset in both cases: the offset
521    /// before the transition (whether it's a gap or a fold) or the offset
522    /// after the transition.
523    ///
524    /// This type captures the fact that computing an offset from a civil
525    /// datetime in a particular time zone is in one of three possible states:
526    ///
527    /// 1. It is unambiguous.
528    /// 2. It is ambiguous because there is a gap in time.
529    /// 3. It is ambiguous because there is a fold in time.
530    ///
531    /// # Example
532    ///
533    /// ```
534    /// use jiff_core::{civil::date, tz::{self, posix, AmbiguousOffset}};
535    ///
536    /// let tz = posix::TimeZone::parse("EST5EDT,M3.2.0,M11.1.0").unwrap();
537    ///
538    /// // Not ambiguous.
539    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
540    /// let ts = tz.to_ambiguous_timestamp(dt);
541    /// assert_eq!(ts.offset(), AmbiguousOffset::Unambiguous {
542    ///     offset: tz::offset(-4),
543    /// });
544    ///
545    /// // Ambiguous because of a gap.
546    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
547    /// let ts = tz.to_ambiguous_timestamp(dt);
548    /// assert_eq!(ts.offset(), AmbiguousOffset::Gap {
549    ///     before: tz::offset(-5),
550    ///     after: tz::offset(-4),
551    /// });
552    ///
553    /// // Ambiguous because of a fold.
554    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
555    /// let ts = tz.to_ambiguous_timestamp(dt);
556    /// assert_eq!(ts.offset(), AmbiguousOffset::Fold {
557    ///     before: tz::offset(-4),
558    ///     after: tz::offset(-5),
559    /// });
560    ///
561    /// # Ok::<(), Box<dyn std::error::Error>>(())
562    /// ```
563    #[inline]
564    pub const fn offset(&self) -> AmbiguousOffset {
565        self.offset
566    }
567
568    /// Returns true if and only if this possibly ambiguous timestamp is
569    /// actually ambiguous.
570    ///
571    /// This occurs precisely in cases when the offset is _not_
572    /// [`AmbiguousOffset::Unambiguous`].
573    ///
574    /// # Example
575    ///
576    /// ```
577    /// use jiff_core::{civil::date, tz::posix};
578    ///
579    /// let tz = posix::TimeZone::parse("EST5EDT,M3.2.0,M11.1.0").unwrap();
580    ///
581    /// // Not ambiguous.
582    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
583    /// let ts = tz.to_ambiguous_timestamp(dt);
584    /// assert!(!ts.is_ambiguous());
585    ///
586    /// // Ambiguous because of a gap.
587    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
588    /// let ts = tz.to_ambiguous_timestamp(dt);
589    /// assert!(ts.is_ambiguous());
590    ///
591    /// // Ambiguous because of a fold.
592    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
593    /// let ts = tz.to_ambiguous_timestamp(dt);
594    /// assert!(ts.is_ambiguous());
595    ///
596    /// # Ok::<(), Box<dyn std::error::Error>>(())
597    /// ```
598    #[inline]
599    pub const fn is_ambiguous(&self) -> bool {
600        !#[allow(non_exhaustive_omitted_patterns)] match self.offset() {
    AmbiguousOffset::Unambiguous { .. } => true,
    _ => false,
}matches!(self.offset(), AmbiguousOffset::Unambiguous { .. })
601    }
602
603    /// Disambiguates this timestamp according to the "compatible" strategy.
604    ///
605    /// If this timestamp is unambiguous, then this is a no-op.
606    ///
607    /// The "compatible" strategy selects the offset corresponding to the civil
608    /// time after a gap, and the offset corresponding to the civil time before
609    /// a fold. This is what is specified in [RFC 5545].
610    ///
611    /// [RFC 5545]: https://datatracker.ietf.org/doc/html/rfc5545
612    ///
613    /// # Errors
614    ///
615    /// This returns an error when the combination of the civil datetime
616    /// and offset would lead to a `Timestamp` outside of the
617    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
618    /// when the civil datetime is "close" to its own [`DateTime::MIN`]
619    /// and [`DateTime::MAX`] limits.
620    #[inline]
621    pub const fn compatible(self) -> Result<Timestamp, RangeError> {
622        let offset = match self.offset() {
623            AmbiguousOffset::Unambiguous { offset } => offset,
624            AmbiguousOffset::Gap { before, .. } => before,
625            AmbiguousOffset::Fold { before, .. } => before,
626        };
627        offset.to_timestamp(self.dt)
628    }
629
630    /// Disambiguates this timestamp according to the "earlier" strategy.
631    ///
632    /// If this timestamp is unambiguous, then this is a no-op.
633    ///
634    /// The "earlier" strategy selects the offset corresponding to the civil
635    /// time before a gap, and the offset corresponding to the civil time
636    /// before a fold.
637    ///
638    /// # Errors
639    ///
640    /// This returns an error when the combination of the civil datetime
641    /// and offset would lead to a `Timestamp` outside of the
642    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
643    /// when the civil datetime is "close" to its own [`DateTime::MIN`]
644    /// and [`DateTime::MAX`] limits.
645    #[inline]
646    pub const fn earlier(self) -> Result<Timestamp, RangeError> {
647        let offset = match self.offset() {
648            AmbiguousOffset::Unambiguous { offset } => offset,
649            AmbiguousOffset::Gap { after, .. } => after,
650            AmbiguousOffset::Fold { before, .. } => before,
651        };
652        offset.to_timestamp(self.dt)
653    }
654
655    /// Disambiguates this timestamp according to the "later" strategy.
656    ///
657    /// If this timestamp is unambiguous, then this is a no-op.
658    ///
659    /// The "later" strategy selects the offset corresponding to the civil
660    /// time after a gap, and the offset corresponding to the civil time
661    /// after a fold.
662    ///
663    /// # Errors
664    ///
665    /// This returns an error when the combination of the civil datetime
666    /// and offset would lead to a `Timestamp` outside of the
667    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
668    /// when the civil datetime is "close" to its own [`DateTime::MIN`]
669    /// and [`DateTime::MAX`] limits.
670    #[inline]
671    pub const fn later(self) -> Result<Timestamp, RangeError> {
672        let offset = match self.offset() {
673            AmbiguousOffset::Unambiguous { offset } => offset,
674            AmbiguousOffset::Gap { before, .. } => before,
675            AmbiguousOffset::Fold { after, .. } => after,
676        };
677        offset.to_timestamp(self.dt)
678    }
679
680    /// Disambiguates this timestamp according to the "reject" strategy.
681    ///
682    /// If this timestamp is unambiguous, then this is a no-op.
683    ///
684    /// The "reject" strategy always returns an error when the timestamp
685    /// is ambiguous.
686    ///
687    /// # Errors
688    ///
689    /// This returns an error when the combination of the civil datetime
690    /// and offset would lead to a `Timestamp` outside of the
691    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
692    /// when the civil datetime is "close" to its own [`DateTime::MIN`]
693    /// and [`DateTime::MAX`] limits.
694    ///
695    /// This also returns an error when the timestamp is ambiguous.
696    ///
697    /// # Example
698    ///
699    /// ```
700    /// use jiff_core::{civil::date, tz::{posix, Offset}};
701    ///
702    /// let tz = posix::TimeZone::parse("EST5EDT,M3.2.0,M11.1.0").unwrap();
703    ///
704    /// // Not ambiguous.
705    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
706    /// let ts = tz.to_ambiguous_timestamp(dt);
707    /// assert_eq!(
708    ///     ts.later().unwrap().to_datetime(Offset::UTC),
709    ///     date(2024, 7, 15).at(21, 30, 0, 0),
710    /// );
711    ///
712    /// // Ambiguous because of a gap.
713    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
714    /// let ts = tz.to_ambiguous_timestamp(dt);
715    /// assert!(ts.unambiguous().is_err());
716    ///
717    /// // Ambiguous because of a fold.
718    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
719    /// let ts = tz.to_ambiguous_timestamp(dt);
720    /// assert!(ts.unambiguous().is_err());
721    /// ```
722    #[inline]
723    pub const fn unambiguous(self) -> Result<Timestamp, AmbiguousError> {
724        let offset = match self.offset() {
725            AmbiguousOffset::Unambiguous { offset } => offset,
726            AmbiguousOffset::Gap { before, after } => {
727                return Err(AmbiguousError {
728                    kind: AmbiguousErrorKind::BecauseGap { before, after },
729                });
730            }
731            AmbiguousOffset::Fold { before, after } => {
732                return Err(AmbiguousError {
733                    kind: AmbiguousErrorKind::BecauseFold { before, after },
734                });
735            }
736        };
737        match offset.to_timestamp(self.dt) {
738            Ok(timestamp) => Ok(timestamp),
739            Err(range_error) => Err(AmbiguousError {
740                kind: AmbiguousErrorKind::Range(range_error),
741            }),
742        }
743    }
744}
745
746/// An error that occurs when an unmabiguous civil datetime is demanded.
747///
748/// This surfaces via the [`AmbiguousTimestamp::unambiguous`] API.
749#[derive(#[automatically_derived]impl ::core::clone::Clone for AmbiguousError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        AmbiguousError { kind: ::core::clone::Clone::clone(&self.kind) }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for AmbiguousError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "AmbiguousError kind", &&self.kind)
    }
}Debug)]
750#[cfg_attr(feature = "defmt", derive(defmt::Format))]
751pub struct AmbiguousError {
752    kind: AmbiguousErrorKind,
753}
754
755#[derive(#[automatically_derived]impl ::core::clone::Clone for AmbiguousErrorKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Range(__self_0) =>
                AmbiguousErrorKind::Range(::core::clone::Clone::clone(__self_0)),
            Self::BecauseFold { before: __self_0, after: __self_1 } =>
                AmbiguousErrorKind::BecauseFold {
                    before: ::core::clone::Clone::clone(__self_0),
                    after: ::core::clone::Clone::clone(__self_1),
                },
            Self::BecauseGap { before: __self_0, after: __self_1 } =>
                AmbiguousErrorKind::BecauseGap {
                    before: ::core::clone::Clone::clone(__self_0),
                    after: ::core::clone::Clone::clone(__self_1),
                },
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for AmbiguousErrorKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Range(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Range",
                    &__self_0),
            Self::BecauseFold { before: __self_0, after: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "BecauseFold before after", __self_0, &__self_1),
            Self::BecauseGap { before: __self_0, after: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "BecauseGap before after", __self_0, &__self_1),
        }
    }
}Debug)]
756#[cfg_attr(feature = "defmt", derive(defmt::Format))]
757enum AmbiguousErrorKind {
758    Range(RangeError),
759    BecauseFold { before: Offset, after: Offset },
760    BecauseGap { before: Offset, after: Offset },
761}
762
763impl core::fmt::Display for AmbiguousError {
764    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
765        use self::AmbiguousErrorKind::*;
766
767        match self.kind {
768            Range(ref err) => core::fmt::Display::fmt(err, f),
769            BecauseFold { before, after } => f.write_fmt(format_args!("datetime is ambiguous since it falls into a fold between offsets {0} and {1}",
        before, after))write!(
770                f,
771                "datetime is ambiguous since it falls into a \
772                 fold between offsets {before} and {after}",
773            ),
774            BecauseGap { before, after } => f.write_fmt(format_args!("datetime is ambiguous since it falls into a gap between offsets {0} and {1}",
        before, after))write!(
775                f,
776                "datetime is ambiguous since it falls into a \
777                 gap between offsets {before} and {after}",
778            ),
779        }
780    }
781}
782
783impl core::error::Error for AmbiguousError {}
784
785#[cfg(test)]
786mod tests {
787    use super::Offset;
788
789    #[test]
790    fn checked_subtracts_positive_and_negative_seconds() {
791        assert_eq!(
792            Offset::UTC.checked_sub(1).unwrap(),
793            Offset::constant_seconds(-1),
794        );
795        assert_eq!(
796            Offset::UTC.checked_sub(-1).unwrap(),
797            Offset::constant_seconds(1),
798        );
799    }
800
801    #[test]
802    fn checked_sub_rejects_overflow() {
803        assert!(Offset::MIN.checked_sub(1).is_err());
804        assert!(Offset::MAX.checked_sub(-1).is_err());
805        assert!(Offset::UTC.checked_sub(i32::MIN).is_err());
806    }
807
808    #[test]
809    fn subtraction_operators_subtract_seconds() {
810        assert_eq!(Offset::UTC - 1, Offset::constant_seconds(-1));
811
812        let mut offset = Offset::UTC;
813        offset -= 1;
814        assert_eq!(offset, Offset::constant_seconds(-1));
815    }
816}