1use crate::{
2Timestamp,
3 bounds::{selfas b, RangeError},
4 civil::{self, DateTime},
5constantsas c,
6 macros::{rtry, unwrapr},
7};
89/// 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}
1415impl Offset {
16/// The minimum possible offset from UTC.
17pub const MIN: Offset = Offset { seconds: b::OffsetTotalSeconds::MIN };
1819/// The maximum possible offset from UTC.
20pub const MAX: Offset = Offset { seconds: b::OffsetTotalSeconds::MAX };
2122/// The UTC offset.
23pub const UTC: Offset = Offset { seconds: 0 };
2425/// The zero offset.
26pub const ZERO: Offset = Offset { seconds: 0 };
2728/// Creates a new time zone offset in a `const` context from a given number
29 /// of hours.
30#[inline]
31pub const fn constant(hours: i8) -> Offset {
32match 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 }
3435/// Creates a new time zone offset in a `const` context from a given number
36 /// of seconds.
37#[inline]
38pub const fn constant_seconds(seconds: i32) -> Offset {
39match 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 }
4445/// 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]
51pub const fn from_hours(hours: i8) -> Result<Offset, RangeError> {
52Offset::from_seconds(hoursas i32 * c::SECS_PER_HOUR_32)
53 }
5455/// 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]
61pub const fn from_seconds(seconds: i32) -> Result<Offset, RangeError> {
62let 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));
63Ok(Offset { seconds })
64 }
6566/// Returns the seconds value corresponding to this time zone offset.
67#[inline]
68pub const fn seconds(self) -> i32 {
69self.seconds
70 }
7172/// 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]
79pub const fn negate(self) -> Offset {
80// OK because of the boundaries we enforce. `seconds` can never be
81 // `i32::MIN`.
82Offset { seconds: -self.seconds() }
83 }
8485/// 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]
90pub const fn signum(self) -> i8 {
91self.seconds().signum() as i892 }
9394/// Returns true if and only if this offset is positive.
95 ///
96 /// This returns false when the offset is zero or negative.
97#[inline]
98pub const fn is_positive(self) -> bool {
99self.seconds() > 0
100}
101102/// 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]
106pub const fn is_negative(self) -> bool {
107self.seconds() < 0
108}
109110/// Returns true if and only if this offset is zero.
111 ///
112 /// Or equivalently, when this offset corresponds to [`Offset::UTC`].
113#[inline]
114pub const fn is_zero(self) -> bool {
115self.seconds() == 0
116}
117118/// 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]
123pub const fn checked_add(
124self,
125 seconds: i32,
126 ) -> Result<Offset, RangeError> {
127let seconds =
128match 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));
129Ok(Offset { seconds })
130 }
131132/// 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]
137pub const fn checked_sub(
138self,
139 seconds: i32,
140 ) -> Result<Offset, RangeError> {
141let 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(
142self.seconds() as i64 - seconds as i64,
143 ));
144Ok(Offset { seconds })
145 }
146147/// Returns the number of seconds from this offset to `other`.
148#[inline]
149pub const fn until(self, other: Offset) -> i32 {
150other.seconds() - self.seconds()
151 }
152153/// Returns the number of seconds since this offset from `other`.
154#[inline]
155pub const fn since(self, other: Offset) -> i32 {
156self.seconds() - other.seconds()
157 }
158159/// 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]
164pub const fn to_datetime(self, timestamp: Timestamp) -> civil::DateTime {
165let offset = self;
166let second = timestamp.as_second();
167let mut nanosecond = timestamp.subsec_nanosecond();
168169// 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).
174const DAY_SHIFT: i32 = 30 * 146097;
175const SEC_SHIFT: i64 = (DAY_SHIFTas i64) * 86_400;
176177let mut pos_sec =
178 (second + (offset.seconds() as i64) + SEC_SHIFT) as u64;
179180let is_neg_nano: bool = nanosecond < 0;
181pos_sec -= is_neg_nanoas u64;
182nanosecond += if is_neg_nano { 1_000_000_000 } else { 0 };
183184let mut epoch_day = (pos_sec / 86_400) as i32;
185let second = (pos_sec % 86_400) as i32;
186187epoch_day -= DAY_SHIFT;
188189// 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.
195let 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();
200let 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!(
201unwrapr!(
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 }
211212/// 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]
219pub const fn to_timestamp(
220self,
221 dt: civil::DateTime,
222 ) -> Result<Timestamp, RangeError> {
223let offset = self;
224let epoch_day = dt.date().to_unix_epoch_day().day();
225let mut second = (epoch_dayas i64) * c::SECS_PER_CIVIL_DAY226 + (dt.time().to_second().second() as i64);
227let mut nanosecond = dt.time().subsec_nanosecond();
228second -= offset.seconds() as i64;
229// Check before normalizing so a fraction below `Timestamp::MIN`
230 // cannot bring the seconds component back into range.
231second = match b::UnixEpochSeconds::checkc(second) {
Ok(val) => val,
Err(err) => return Err(err.into_range_error()),
}rtry!(b::UnixEpochSeconds::checkc(second));
232if second < 0 && nanosecond != 0 {
233second += 1;
234nanosecond -= c::NANOS_PER_SEC_32;
235 }
236Ok(Timestamp::new_unchecked(second, nanosecond))
237 }
238}
239240impl Offset {
241#[inline]
242fn part_hours(self) -> i8 {
243 (self.seconds() / c::SECS_PER_HOUR_32) as i8244 }
245246#[inline]
247fn part_minutes(self) -> i8 {
248 ((self.seconds() / c::SECS_PER_MIN_32) % c::MINS_PER_HOUR_32) as i8249 }
250251#[inline]
252fn part_seconds(self) -> i8 {
253 (self.seconds() % c::SECS_PER_MIN_32) as i8254 }
255}
256257/// 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::Negfor Offset {
264type Output = Offset;
265266#[inline]
267fn neg(self) -> Offset {
268self.negate()
269 }
270}
271272/// 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 {
279type Output = Offset;
280281fn add(self, seconds: i32) -> Offset {
282self.checked_add(seconds).unwrap()
283 }
284}
285286/// 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]
294fn add_assign(&mut self, rhs: i32) {
295*self = *self + rhs;
296 }
297}
298299/// 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 {
306type Output = Offset;
307308fn sub(self, seconds: i32) -> Offset {
309self.checked_sub(seconds).unwrap()
310 }
311}
312313/// 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]
321fn sub_assign(&mut self, rhs: i32) {
322*self = *self - rhs;
323 }
324}
325326impl core::fmt::Debugfor Offset {
327fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
328let sign = if self.is_negative() { "-" } else { "" };
329f.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!(
330f,
331"{sign}{:02}:{:02}:{:02}",
332self.part_hours().unsigned_abs(),
333self.part_minutes().unsigned_abs(),
334self.part_seconds().unsigned_abs(),
335 )336 }
337}
338339impl core::fmt::Displayfor Offset {
340fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
341let sign = if self.is_negative() { "-" } else { "+" };
342let hours = self.part_hours().unsigned_abs();
343let minutes = self.part_minutes().unsigned_abs();
344let seconds = self.part_seconds().unsigned_abs();
345if hours == 0 && minutes == 0 && seconds == 0 {
346f.write_str("+00")
347 } else if hours != 0 && minutes == 0 && seconds == 0 {
348f.write_fmt(format_args!("{0}{1:02}", sign, hours))write!(f, "{sign}{hours:02}")349 } else if minutes != 0 && seconds == 0 {
350f.write_fmt(format_args!("{0}{1:02}:{2:02}", sign, hours, minutes))write!(f, "{sign}{hours:02}:{minutes:02}")351 } else {
352f.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}
356357#[cfg(feature = "defmt")]
358impl defmt::Format for Offset {
359fn format(&self, f: defmt::Formatter) {
360let sign = if self.is_negative() { "-" } else { "" };
361defmt::write!(
362 f,
363"{=str}{=u8:02}:{=u8:02}:{=u8:02}",
364 sign,
365self.part_hours().unsigned_abs(),
366self.part_minutes().unsigned_abs(),
367self.part_seconds().unsigned_abs(),
368 )
369 }
370}
371372#[cfg(feature = "arbitrary")]
373impl<'a> arbitrary::Arbitrary<'a> for Offset {
374fn arbitrary(
375 u: &mut arbitrary::Unstructured<'a>,
376 ) -> arbitrary::Result<Offset> {
377let secs = u.int_in_range(
378 b::OffsetTotalSeconds::MIN..=b::OffsetTotalSeconds::MAX,
379 )?;
380Ok(Offset::from_seconds(secs).unwrap_or(Offset::UTC))
381 }
382383fn size_hint(depth: usize) -> (usize, Option<usize>) {
384 <i32 as arbitrary::Arbitrary>::size_hint(depth)
385 }
386}
387388#[cfg(test)]
389impl quickcheck::Arbitrary for Offset {
390fn arbitrary(g: &mut quickcheck::Gen) -> Offset {
391let secs = b::OffsetTotalSeconds::arbitrary(g);
392 Offset::from_seconds(secs).unwrap_or(Offset::UTC)
393 }
394395fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Self>> {
396let secs = self.seconds();
397 alloc::boxed::Box::new(secs.shrink().filter_map(|secs| {
398let secs = b::OffsetTotalSeconds::check(secs).ok()?;
399 Offset::from_seconds(secs).ok()
400 }))
401 }
402}
403404/// 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).
421Unambiguous {
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.
426offset: 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).
433Gap {
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`.
438before: 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`.
443after: 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).
451Fold {
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`.
456before: 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`.
461after: Offset,
462 },
463}
464465impl AmbiguousOffset {
466#[inline]
467pub(crate) const fn into_ambiguous_timestamp(
468self,
469 dt: DateTime,
470 ) -> AmbiguousTimestamp {
471AmbiguousTimestamp { dt, offset: self }
472 }
473}
474475/// 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}
487488impl 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]
505pub const fn datetime(&self) -> DateTime {
506self.dt
507 }
508509/// 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]
564pub const fn offset(&self) -> AmbiguousOffset {
565self.offset
566 }
567568/// 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]
599pub 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 }
602603/// 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]
621pub const fn compatible(self) -> Result<Timestamp, RangeError> {
622let offset = match self.offset() {
623 AmbiguousOffset::Unambiguous { offset } => offset,
624 AmbiguousOffset::Gap { before, .. } => before,
625 AmbiguousOffset::Fold { before, .. } => before,
626 };
627offset.to_timestamp(self.dt)
628 }
629630/// 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]
646pub const fn earlier(self) -> Result<Timestamp, RangeError> {
647let offset = match self.offset() {
648 AmbiguousOffset::Unambiguous { offset } => offset,
649 AmbiguousOffset::Gap { after, .. } => after,
650 AmbiguousOffset::Fold { before, .. } => before,
651 };
652offset.to_timestamp(self.dt)
653 }
654655/// 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]
671pub const fn later(self) -> Result<Timestamp, RangeError> {
672let offset = match self.offset() {
673 AmbiguousOffset::Unambiguous { offset } => offset,
674 AmbiguousOffset::Gap { before, .. } => before,
675 AmbiguousOffset::Fold { after, .. } => after,
676 };
677offset.to_timestamp(self.dt)
678 }
679680/// 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]
723pub const fn unambiguous(self) -> Result<Timestamp, AmbiguousError> {
724let offset = match self.offset() {
725 AmbiguousOffset::Unambiguous { offset } => offset,
726 AmbiguousOffset::Gap { before, after } => {
727return Err(AmbiguousError {
728 kind: AmbiguousErrorKind::BecauseGap { before, after },
729 });
730 }
731 AmbiguousOffset::Fold { before, after } => {
732return Err(AmbiguousError {
733 kind: AmbiguousErrorKind::BecauseFold { before, after },
734 });
735 }
736 };
737match offset.to_timestamp(self.dt) {
738Ok(timestamp) => Ok(timestamp),
739Err(range_error) => Err(AmbiguousError {
740 kind: AmbiguousErrorKind::Range(range_error),
741 }),
742 }
743 }
744}
745746/// 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}
754755#[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}
762763impl core::fmt::Displayfor AmbiguousError {
764fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
765use self::AmbiguousErrorKind::*;
766767match self.kind {
768Range(ref err) => core::fmt::Display::fmt(err, f),
769BecauseFold { before, after } => f.write_fmt(format_args!("datetime is ambiguous since it falls into a fold between offsets {0} and {1}",
before, after))write!(
770f,
771"datetime is ambiguous since it falls into a \
772 fold between offsets {before} and {after}",
773 ),
774BecauseGap { before, after } => f.write_fmt(format_args!("datetime is ambiguous since it falls into a gap between offsets {0} and {1}",
before, after))write!(
775f,
776"datetime is ambiguous since it falls into a \
777 gap between offsets {before} and {after}",
778 ),
779 }
780 }
781}
782783impl core::error::Errorfor AmbiguousError {}
784785#[cfg(test)]
786mod tests {
787use super::Offset;
788789#[test]
790fn checked_subtracts_positive_and_negative_seconds() {
791assert_eq!(
792 Offset::UTC.checked_sub(1).unwrap(),
793 Offset::constant_seconds(-1),
794 );
795assert_eq!(
796 Offset::UTC.checked_sub(-1).unwrap(),
797 Offset::constant_seconds(1),
798 );
799 }
800801#[test]
802fn checked_sub_rejects_overflow() {
803assert!(Offset::MIN.checked_sub(1).is_err());
804assert!(Offset::MAX.checked_sub(-1).is_err());
805assert!(Offset::UTC.checked_sub(i32::MIN).is_err());
806 }
807808#[test]
809fn subtraction_operators_subtract_seconds() {
810assert_eq!(Offset::UTC - 1, Offset::constant_seconds(-1));
811812let mut offset = Offset::UTC;
813 offset -= 1;
814assert_eq!(offset, Offset::constant_seconds(-1));
815 }
816}