jiff-core 0.1.0

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

/// A fixed offset, in seconds, from UTC.
#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct Offset {
    seconds: i32,
}

impl Offset {
    /// The minimum possible offset from UTC.
    pub const MIN: Offset = Offset { seconds: b::OffsetTotalSeconds::MIN };

    /// The maximum possible offset from UTC.
    pub const MAX: Offset = Offset { seconds: b::OffsetTotalSeconds::MAX };

    /// The UTC offset.
    pub const UTC: Offset = Offset { seconds: 0 };

    /// The zero offset.
    pub const ZERO: Offset = Offset { seconds: 0 };

    /// Creates a new time zone offset in a `const` context from a given number
    /// of hours.
    #[inline]
    pub const fn constant(hours: i8) -> Offset {
        unwrapr!(Offset::from_hours(hours), "invalid time zone offset hours")
    }

    /// Creates a new time zone offset in a `const` context from a given number
    /// of seconds.
    #[inline]
    pub const fn constant_seconds(seconds: i32) -> Offset {
        unwrapr!(
            Offset::from_seconds(seconds),
            "invalid time zone offset seconds",
        )
    }

    /// Creates a new time zone offset from a given number of hours.
    ///
    /// Negative offsets correspond to time zones west of the prime meridian,
    /// while positive offsets correspond to time zones east of the prime
    /// meridian. Equivalently, in all cases, `civil-time - offset = UTC`.
    #[inline]
    pub const fn from_hours(hours: i8) -> Result<Offset, RangeError> {
        Offset::from_seconds(hours as i32 * c::SECS_PER_HOUR_32)
    }

    /// Returns a new time zone offset from UTC given its representation in
    /// seconds.
    ///
    /// An error is also returned when `seconds` is not in the range specified
    /// by [`OffsetTotalSeconds`](b::OffsetTotalSeconds).
    #[inline]
    pub const fn from_seconds(seconds: i32) -> Result<Offset, RangeError> {
        let seconds = rtry!(b::OffsetTotalSeconds::checkc(seconds as i64));
        Ok(Offset { seconds })
    }

    /// Returns the seconds value corresponding to this time zone offset.
    #[inline]
    pub const fn seconds(self) -> i32 {
        self.seconds
    }

    /// Returns the negation of this offset.
    ///
    /// A negative offset will become positive and vice versa. This is a no-op
    /// if the offset is zero.
    ///
    /// This never panics.
    #[inline]
    pub const fn negate(self) -> Offset {
        // OK because of the boundaries we enforce. `seconds` can never be
        // `i32::MIN`.
        Offset { seconds: -self.seconds() }
    }

    /// Returns the "sign number" or "signum" of this offset.
    ///
    /// The number returned is `-1` when this offset is negative,
    /// `0` when this offset is zero and `1` when this span is positive.
    #[inline]
    pub const fn signum(self) -> i8 {
        self.seconds().signum() as i8
    }

    /// Returns true if and only if this offset is positive.
    ///
    /// This returns false when the offset is zero or negative.
    #[inline]
    pub const fn is_positive(self) -> bool {
        self.seconds() > 0
    }

    /// Returns true if and only if this offset is less than zero.
    ///
    /// This returns false when the offset is zero or positive.
    #[inline]
    pub const fn is_negative(self) -> bool {
        self.seconds() < 0
    }

    /// Returns true if and only if this offset is zero.
    ///
    /// Or equivalently, when this offset corresponds to [`Offset::UTC`].
    #[inline]
    pub const fn is_zero(self) -> bool {
        self.seconds() == 0
    }

    /// Adds the given number of seconds to this offset.
    ///
    /// If the resulting offset would be outside the an offset's boundaries,
    /// an error is returned.
    #[inline]
    pub const fn checked_add(
        self,
        seconds: i32,
    ) -> Result<Offset, RangeError> {
        let seconds =
            rtry!(b::OffsetTotalSeconds::checked_add(self.seconds(), seconds));
        Ok(Offset { seconds })
    }

    /// Subtracts the given number of seconds from this offset.
    ///
    /// If the resulting offset would be outside the an offset's boundaries,
    /// an error is returned.
    #[inline]
    pub const fn checked_sub(
        self,
        seconds: i32,
    ) -> Result<Offset, RangeError> {
        let seconds =
            rtry!(b::OffsetTotalSeconds::checked_add(self.seconds(), seconds));
        Ok(Offset { seconds })
    }

    /// Returns the number of seconds from this offset to `other`.
    #[inline]
    pub const fn until(self, other: Offset) -> i32 {
        other.seconds() - self.seconds()
    }

    /// Returns the number of seconds since this offset from `other`.
    #[inline]
    pub const fn since(self, other: Offset) -> i32 {
        self.seconds() - other.seconds()
    }

    /// Converts a Unix timestamp with an offset to a Gregorian datetime.
    ///
    /// The offset should correspond to the number of seconds required to
    /// add to this timestamp to get the local time.
    #[inline]
    pub const fn to_datetime(self, timestamp: Timestamp) -> civil::DateTime {
        let offset = self;
        let second = timestamp.as_second();
        let mut nanosecond = timestamp.subsec_nanosecond();

        // Shift second comfortably into the postive domain
        // so that division and remainder can use unsigned math
        // which is much faster.
        // 30 * 400 years: 12,000 yr range > [-9,999..1970]
        // (146097 being the number of days per 400 years).
        const DAY_SHIFT: i32 = 30 * 146097;
        const SEC_SHIFT: i64 = (DAY_SHIFT as i64) * 86_400;

        let pos_sec = (second + (offset.seconds() as i64) + SEC_SHIFT) as u64;
        let mut epoch_day = (pos_sec / 86_400) as i32;
        let mut second = (pos_sec % 86_400) as i32;

        if nanosecond < 0 {
            if second > 0 {
                second -= 1;
                nanosecond += 1_000_000_000;
            } else {
                epoch_day -= 1;
                second += 86_399;
                nanosecond += 1_000_000_000;
            }
        }

        epoch_day -= DAY_SHIFT;

        // We should check whether having unchecked APIs
        // would be beneficial here. In particular, the
        // math above, coupled with the ranges allowed on
        // `Timestamp` and `Offset` (by design) guarantee
        // that our resulting datetime will always be in
        // range.
        let date = unwrapr!(
            civil::UnixEpochDay::new(epoch_day),
            "always valid Unix epoch day",
        )
        .to_date();
        let time = unwrapr!(
            unwrapr!(
                civil::TimeSecond::new(second),
                "always valid civil second time"
            )
            .to_time()
            .with_subsec_nanosecond(nanosecond),
            "always valid civil subsecond"
        );
        civil::DateTime::from_parts(date, time)
    }

    /// Converts the given civil datetime to a timestamp using this offset.
    ///
    /// # Errors
    ///
    /// This returns an error if this would have returned a timestamp outside
    /// of its minimum and maximum values.
    #[inline]
    pub const fn to_timestamp(
        self,
        dt: civil::DateTime,
    ) -> Result<Timestamp, RangeError> {
        let offset = self;
        let epoch_day = dt.date().to_unix_epoch_day().day();
        let mut second = (epoch_day as i64) * c::SECS_PER_CIVIL_DAY
            + (dt.time().to_second().second() as i64);
        let mut nanosecond = dt.time().subsec_nanosecond();
        second -= offset.seconds() as i64;
        if second < 0 && nanosecond != 0 {
            second += 1;
            nanosecond -= c::NANOS_PER_SEC_32;
        }
        let second = rtry!(b::UnixEpochSeconds::checkc(second));
        Ok(Timestamp::new_unchecked(second, nanosecond))
    }
}

impl Offset {
    #[inline]
    fn part_hours(self) -> i8 {
        (self.seconds() / c::SECS_PER_HOUR_32) as i8
    }

    #[inline]
    fn part_minutes(self) -> i8 {
        ((self.seconds() / c::SECS_PER_MIN_32) % c::MINS_PER_HOUR_32) as i8
    }

    #[inline]
    fn part_seconds(self) -> i8 {
        (self.seconds() % c::SECS_PER_MIN_32) as i8
    }
}

/// Negate this offset.
///
/// A positive offset becomes negative and vice versa. This is a no-op for the
/// zero offset.
///
/// This never panics.
impl core::ops::Neg for Offset {
    type Output = Offset;

    #[inline]
    fn neg(self) -> Offset {
        self.negate()
    }
}

/// Adds a number of seconds to an `Offset`.
///
/// # Panics
///
/// When adding would result in a value outside the boundaries of a
/// `Offset`.
impl core::ops::Add<i32> for Offset {
    type Output = Offset;

    fn add(self, seconds: i32) -> Offset {
        self.checked_add(seconds).unwrap()
    }
}

/// Adds a number of seconds into an `Offset`.
///
/// # Panics
///
/// When adding would result in a value outside the boundaries of a
/// `Offset`.
impl core::ops::AddAssign<i32> for Offset {
    #[inline]
    fn add_assign(&mut self, rhs: i32) {
        *self = *self + rhs;
    }
}

/// Subtracts a number of seconds from an `Offset`.
///
/// # Panics
///
/// When adding would result in a value outside the boundaries of a
/// `Offset`.
impl core::ops::Sub<i32> for Offset {
    type Output = Offset;

    fn sub(self, seconds: i32) -> Offset {
        self.checked_sub(seconds).unwrap()
    }
}

/// Subtracts a number of seconds from an `Offset` in place.
///
/// # Panics
///
/// When adding would result in a value outside the boundaries of a
/// `Offset`.
impl core::ops::SubAssign<i32> for Offset {
    #[inline]
    fn sub_assign(&mut self, rhs: i32) {
        *self = *self - rhs;
    }
}

impl core::fmt::Debug for Offset {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        let sign = if self.is_negative() { "-" } else { "" };
        write!(
            f,
            "{sign}{:02}:{:02}:{:02}",
            self.part_hours().unsigned_abs(),
            self.part_minutes().unsigned_abs(),
            self.part_seconds().unsigned_abs(),
        )
    }
}

impl core::fmt::Display for Offset {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        let sign = if self.is_negative() { "-" } else { "+" };
        let hours = self.part_hours().unsigned_abs();
        let minutes = self.part_minutes().unsigned_abs();
        let seconds = self.part_seconds().unsigned_abs();
        if hours == 0 && minutes == 0 && seconds == 0 {
            f.write_str("+00")
        } else if hours != 0 && minutes == 0 && seconds == 0 {
            write!(f, "{sign}{hours:02}")
        } else if minutes != 0 && seconds == 0 {
            write!(f, "{sign}{hours:02}:{minutes:02}")
        } else {
            write!(f, "{sign}{hours:02}:{minutes:02}:{seconds:02}")
        }
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for Offset {
    fn format(&self, f: defmt::Formatter) {
        let sign = if self.is_negative() { "-" } else { "" };
        defmt::write!(
            f,
            "{=str}{=u8:02}:{=u8:02}:{=u8:02}",
            sign,
            self.part_hours().unsigned_abs(),
            self.part_minutes().unsigned_abs(),
            self.part_seconds().unsigned_abs(),
        )
    }
}

#[cfg(test)]
impl quickcheck::Arbitrary for Offset {
    fn arbitrary(g: &mut quickcheck::Gen) -> Offset {
        let secs = b::OffsetTotalSeconds::arbitrary(g);
        Offset::from_seconds(secs).unwrap_or(Offset::UTC)
    }

    fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Self>> {
        let secs = self.seconds();
        alloc::boxed::Box::new(secs.shrink().filter_map(|secs| {
            let secs = b::OffsetTotalSeconds::check(secs).ok()?;
            Offset::from_seconds(secs).ok()
        }))
    }
}

/// A possibly ambiguous [`Offset`].
///
/// One of three possibilities encoded by this type occurs when converting a
/// civil datetime into a specific instant in time. In rare cases, the civil
/// datetime can fall into a gap or a fold, in which case, one of two offsets
/// could be applicable. Or, perhaps, neither. Callers must decide how best to
/// handle these cases.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum AmbiguousOffset {
    /// The offset for a particular civil datetime and time zone is
    /// unambiguous.
    ///
    /// This is the overwhelmingly common case. In general, the only time this
    /// case does not occur is when there is a transition to a different time
    /// zone (rare) or to/from daylight saving time (occurs for 1 hour twice
    /// in year in many geographic locations).
    Unambiguous {
        /// The offset from UTC for the corresponding civil datetime given. The
        /// offset is determined via the relevant time zone data, and in this
        /// case, there is only one possible offset that could be applied to
        /// the given civil datetime.
        offset: Offset,
    },
    /// The offset for a particular civil datetime and time zone is ambiguous
    /// because there is a gap.
    ///
    /// This most commonly occurs when a civil datetime corresponds to an hour
    /// that was "skipped" in a jump to DST (daylight saving time).
    Gap {
        /// The offset corresponding to the time before a gap.
        ///
        /// For example, given a time zone of `America/Los_Angeles`, the offset
        /// for time immediately preceding `2020-03-08T02:00:00` is `-08`.
        before: Offset,
        /// The offset corresponding to the later time in a gap.
        ///
        /// For example, given a time zone of `America/Los_Angeles`, the offset
        /// for time immediately following `2020-03-08T02:59:59` is `-07`.
        after: Offset,
    },
    /// The offset for a particular civil datetime and time zone is ambiguous
    /// because there is a fold.
    ///
    /// This most commonly occurs when a civil datetime corresponds to an hour
    /// that was "repeated" in a jump to standard time from DST (daylight
    /// saving time).
    Fold {
        /// The offset corresponding to the earlier time in a fold.
        ///
        /// For example, given a time zone of `America/Los_Angeles`, the offset
        /// for time on the first `2020-11-01T01:00:00` is `-07`.
        before: Offset,
        /// The offset corresponding to the earlier time in a fold.
        ///
        /// For example, given a time zone of `America/Los_Angeles`, the offset
        /// for time on the second `2020-11-01T01:00:00` is `-08`.
        after: Offset,
    },
}

impl AmbiguousOffset {
    #[inline]
    pub(crate) const fn into_ambiguous_timestamp(
        self,
        dt: DateTime,
    ) -> AmbiguousTimestamp {
        AmbiguousTimestamp { dt, offset: self }
    }
}

/// A possibly ambiguous [`Timestamp`].
///
/// While this is called an ambiguous _timestamp_, the thing that is
/// actually ambiguous is the offset. That is, an ambiguous timestamp is
/// actually a pair of a [`civil::DateTime`](crate::civil::DateTime) and an
/// [`AmbiguousOffset`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AmbiguousTimestamp {
    dt: DateTime,
    offset: AmbiguousOffset,
}

impl AmbiguousTimestamp {
    /// Returns the civil datetime that was used to create this ambiguous
    /// timestamp.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff_core::{civil::date, tz::posix};
    ///
    /// let tz = posix::TimeZone::parse("EST5EDT,M3.2.0,M11.1.0").unwrap();
    /// let dt = date(2024, 7, 10).at(17, 15, 0, 0);
    /// let ts = tz.to_ambiguous_timestamp(dt);
    /// assert_eq!(ts.datetime(), dt);
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[inline]
    pub const fn datetime(&self) -> DateTime {
        self.dt
    }

    /// Returns the possibly ambiguous offset that is the ultimate source of
    /// ambiguity.
    ///
    /// Most civil datetimes are not ambiguous, and thus, the offset will not
    /// be ambiguous either. In this case, the offset returned will be the
    /// [`AmbiguousOffset::Unambiguous`] variant.
    ///
    /// But, not all civil datetimes are unambiguous. There are exactly two
    /// cases where a civil datetime can be ambiguous: when a civil datetime
    /// does not exist (a gap) or when a civil datetime is repeated (a fold).
    /// In both such cases, the _offset_ is the thing that is ambiguous as
    /// there are two possible choices for the offset in both cases: the offset
    /// before the transition (whether it's a gap or a fold) or the offset
    /// after the transition.
    ///
    /// This type captures the fact that computing an offset from a civil
    /// datetime in a particular time zone is in one of three possible states:
    ///
    /// 1. It is unambiguous.
    /// 2. It is ambiguous because there is a gap in time.
    /// 3. It is ambiguous because there is a fold in time.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff_core::{civil::date, tz::{self, posix, AmbiguousOffset}};
    ///
    /// let tz = posix::TimeZone::parse("EST5EDT,M3.2.0,M11.1.0").unwrap();
    ///
    /// // Not ambiguous.
    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
    /// let ts = tz.to_ambiguous_timestamp(dt);
    /// assert_eq!(ts.offset(), AmbiguousOffset::Unambiguous {
    ///     offset: tz::offset(-4),
    /// });
    ///
    /// // Ambiguous because of a gap.
    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
    /// let ts = tz.to_ambiguous_timestamp(dt);
    /// assert_eq!(ts.offset(), AmbiguousOffset::Gap {
    ///     before: tz::offset(-5),
    ///     after: tz::offset(-4),
    /// });
    ///
    /// // Ambiguous because of a fold.
    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
    /// let ts = tz.to_ambiguous_timestamp(dt);
    /// assert_eq!(ts.offset(), AmbiguousOffset::Fold {
    ///     before: tz::offset(-4),
    ///     after: tz::offset(-5),
    /// });
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[inline]
    pub const fn offset(&self) -> AmbiguousOffset {
        self.offset
    }

    /// Returns true if and only if this possibly ambiguous timestamp is
    /// actually ambiguous.
    ///
    /// This occurs precisely in cases when the offset is _not_
    /// [`AmbiguousOffset::Unambiguous`].
    ///
    /// # Example
    ///
    /// ```
    /// use jiff_core::{civil::date, tz::posix};
    ///
    /// let tz = posix::TimeZone::parse("EST5EDT,M3.2.0,M11.1.0").unwrap();
    ///
    /// // Not ambiguous.
    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
    /// let ts = tz.to_ambiguous_timestamp(dt);
    /// assert!(!ts.is_ambiguous());
    ///
    /// // Ambiguous because of a gap.
    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
    /// let ts = tz.to_ambiguous_timestamp(dt);
    /// assert!(ts.is_ambiguous());
    ///
    /// // Ambiguous because of a fold.
    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
    /// let ts = tz.to_ambiguous_timestamp(dt);
    /// assert!(ts.is_ambiguous());
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[inline]
    pub const fn is_ambiguous(&self) -> bool {
        !matches!(self.offset(), AmbiguousOffset::Unambiguous { .. })
    }

    /// Disambiguates this timestamp according to the "compatible" strategy.
    ///
    /// If this timestamp is unambiguous, then this is a no-op.
    ///
    /// The "compatible" strategy selects the offset corresponding to the civil
    /// time after a gap, and the offset corresponding to the civil time before
    /// a fold. This is what is specified in [RFC 5545].
    ///
    /// [RFC 5545]: https://datatracker.ietf.org/doc/html/rfc5545
    ///
    /// # Errors
    ///
    /// This returns an error when the combination of the civil datetime
    /// and offset would lead to a `Timestamp` outside of the
    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
    /// when the civil datetime is "close" to its own [`DateTime::MIN`]
    /// and [`DateTime::MAX`] limits.
    #[inline]
    pub const fn compatible(self) -> Result<Timestamp, RangeError> {
        let offset = match self.offset() {
            AmbiguousOffset::Unambiguous { offset } => offset,
            AmbiguousOffset::Gap { before, .. } => before,
            AmbiguousOffset::Fold { before, .. } => before,
        };
        offset.to_timestamp(self.dt)
    }

    /// Disambiguates this timestamp according to the "earlier" strategy.
    ///
    /// If this timestamp is unambiguous, then this is a no-op.
    ///
    /// The "earlier" strategy selects the offset corresponding to the civil
    /// time before a gap, and the offset corresponding to the civil time
    /// before a fold.
    ///
    /// # Errors
    ///
    /// This returns an error when the combination of the civil datetime
    /// and offset would lead to a `Timestamp` outside of the
    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
    /// when the civil datetime is "close" to its own [`DateTime::MIN`]
    /// and [`DateTime::MAX`] limits.
    #[inline]
    pub const fn earlier(self) -> Result<Timestamp, RangeError> {
        let offset = match self.offset() {
            AmbiguousOffset::Unambiguous { offset } => offset,
            AmbiguousOffset::Gap { after, .. } => after,
            AmbiguousOffset::Fold { before, .. } => before,
        };
        offset.to_timestamp(self.dt)
    }

    /// Disambiguates this timestamp according to the "later" strategy.
    ///
    /// If this timestamp is unambiguous, then this is a no-op.
    ///
    /// The "later" strategy selects the offset corresponding to the civil
    /// time after a gap, and the offset corresponding to the civil time
    /// after a fold.
    ///
    /// # Errors
    ///
    /// This returns an error when the combination of the civil datetime
    /// and offset would lead to a `Timestamp` outside of the
    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
    /// when the civil datetime is "close" to its own [`DateTime::MIN`]
    /// and [`DateTime::MAX`] limits.
    #[inline]
    pub const fn later(self) -> Result<Timestamp, RangeError> {
        let offset = match self.offset() {
            AmbiguousOffset::Unambiguous { offset } => offset,
            AmbiguousOffset::Gap { before, .. } => before,
            AmbiguousOffset::Fold { after, .. } => after,
        };
        offset.to_timestamp(self.dt)
    }

    /// Disambiguates this timestamp according to the "reject" strategy.
    ///
    /// If this timestamp is unambiguous, then this is a no-op.
    ///
    /// The "reject" strategy always returns an error when the timestamp
    /// is ambiguous.
    ///
    /// # Errors
    ///
    /// This returns an error when the combination of the civil datetime
    /// and offset would lead to a `Timestamp` outside of the
    /// [`Timestamp::MIN`] and [`Timestamp::MAX`] limits. This only occurs
    /// when the civil datetime is "close" to its own [`DateTime::MIN`]
    /// and [`DateTime::MAX`] limits.
    ///
    /// This also returns an error when the timestamp is ambiguous.
    ///
    /// # Example
    ///
    /// ```
    /// use jiff_core::{civil::date, tz::{posix, Offset}};
    ///
    /// let tz = posix::TimeZone::parse("EST5EDT,M3.2.0,M11.1.0").unwrap();
    ///
    /// // Not ambiguous.
    /// let dt = date(2024, 7, 15).at(17, 30, 0, 0);
    /// let ts = tz.to_ambiguous_timestamp(dt);
    /// assert_eq!(
    ///     ts.later().unwrap().to_datetime(Offset::UTC),
    ///     date(2024, 7, 15).at(21, 30, 0, 0),
    /// );
    ///
    /// // Ambiguous because of a gap.
    /// let dt = date(2024, 3, 10).at(2, 30, 0, 0);
    /// let ts = tz.to_ambiguous_timestamp(dt);
    /// assert!(ts.unambiguous().is_err());
    ///
    /// // Ambiguous because of a fold.
    /// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
    /// let ts = tz.to_ambiguous_timestamp(dt);
    /// assert!(ts.unambiguous().is_err());
    /// ```
    #[inline]
    pub const fn unambiguous(self) -> Result<Timestamp, AmbiguousError> {
        let offset = match self.offset() {
            AmbiguousOffset::Unambiguous { offset } => offset,
            AmbiguousOffset::Gap { before, after } => {
                return Err(AmbiguousError {
                    kind: AmbiguousErrorKind::BecauseGap { before, after },
                });
            }
            AmbiguousOffset::Fold { before, after } => {
                return Err(AmbiguousError {
                    kind: AmbiguousErrorKind::BecauseFold { before, after },
                });
            }
        };
        match offset.to_timestamp(self.dt) {
            Ok(timestamp) => Ok(timestamp),
            Err(range_error) => Err(AmbiguousError {
                kind: AmbiguousErrorKind::Range(range_error),
            }),
        }
    }
}

/// An error that occurs when an unmabiguous civil datetime is demanded.
///
/// This surfaces via the [`AmbiguousTimestamp::unambiguous`] API.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AmbiguousError {
    kind: AmbiguousErrorKind,
}

#[derive(Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
enum AmbiguousErrorKind {
    Range(RangeError),
    BecauseFold { before: Offset, after: Offset },
    BecauseGap { before: Offset, after: Offset },
}

impl core::fmt::Display for AmbiguousError {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        use self::AmbiguousErrorKind::*;

        match self.kind {
            Range(ref err) => core::fmt::Display::fmt(err, f),
            BecauseFold { before, after } => write!(
                f,
                "datetime is ambiguous since it falls into a \
                 fold between offsets {before} and {after}",
            ),
            BecauseGap { before, after } => write!(
                f,
                "datetime is ambiguous since it falls into a \
                 gap between offsets {before} and {after}",
            ),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for AmbiguousError {}