jiff/tz/offset.rs
1use core::{
2 ops::{Add, AddAssign, Neg, Sub, SubAssign},
3 time::Duration as UnsignedDuration,
4};
5
6use jcore::{constants as c, tz::Offset as JOffset};
7
8use crate::{
9 RoundMode, SignedDuration, Unit, civil,
10 duration::{Duration, SDuration},
11 error::{Error, ErrorContext, tz::offset::Error as E},
12 span::Span,
13 timestamp::Timestamp,
14 tz::{
15 AmbiguousOffset, AmbiguousTimestamp, AmbiguousZonedDateTime, TimeZone,
16 },
17 util::{b, constant, round::Increment},
18};
19
20/// An enum indicating whether a particular datetime is in DST or not.
21///
22/// DST stands for "daylight saving time." It is a label used to apply to
23/// points in time as a way to contrast it with "standard time." DST is
24/// usually, but not always, one hour ahead of standard time. When DST takes
25/// effect is usually determined by governments, and the rules can vary
26/// depending on the location. DST is typically used as a means to maximize
27/// "sunlight" time during typical working hours, and as a cost cutting measure
28/// by reducing energy consumption. (The effectiveness of DST and whether it
29/// is overall worth it is a separate question entirely.)
30///
31/// In general, most users should never need to deal with this type. But it can
32/// be occasionally useful in circumstances where callers need to know whether
33/// DST is active or not for a particular point in time.
34///
35/// This type has a `From<bool>` trait implementation, where the bool is
36/// interpreted as being `true` when DST is active.
37#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
38#[cfg_attr(feature = "defmt", derive(defmt::Format))]
39pub enum Dst {
40 /// DST is not in effect. In other words, standard time is in effect.
41 No,
42 /// DST is in effect.
43 Yes,
44}
45
46impl Dst {
47 /// Returns true when this value is equal to `Dst::Yes`.
48 pub fn is_dst(self) -> bool {
49 matches!(self, Dst::Yes)
50 }
51
52 /// Returns true when this value is equal to `Dst::No`.
53 ///
54 /// `std` in this context refers to "standard time." That is, it is the
55 /// offset from UTC used when DST is not in effect.
56 pub fn is_std(self) -> bool {
57 matches!(self, Dst::No)
58 }
59
60 pub(crate) fn from_jcore(dst: jcore::tz::Dst) -> Dst {
61 match dst {
62 jcore::tz::Dst::Yes => Dst::Yes,
63 jcore::tz::Dst::No => Dst::No,
64 }
65 }
66}
67
68impl From<bool> for Dst {
69 fn from(is_dst: bool) -> Dst {
70 if is_dst { Dst::Yes } else { Dst::No }
71 }
72}
73
74/// Represents a fixed time zone offset.
75///
76/// Negative offsets correspond to time zones west of the prime meridian, while
77/// positive offsets correspond to time zones east of the prime meridian.
78/// Equivalently, in all cases, `civil-time - offset = UTC`.
79///
80/// # Display format
81///
82/// This type implements the `std::fmt::Display` trait. It
83/// will convert the offset to a string format in the form
84/// `{sign}{hours}[:{minutes}[:{seconds}]]`, where `minutes` and `seconds` are
85/// only present when non-zero. For example:
86///
87/// ```
88/// use jiff::tz;
89///
90/// let o = tz::offset(-5);
91/// assert_eq!(o.to_string(), "-05");
92/// let o = tz::Offset::from_seconds(-18_000).unwrap();
93/// assert_eq!(o.to_string(), "-05");
94/// let o = tz::Offset::from_seconds(-18_060).unwrap();
95/// assert_eq!(o.to_string(), "-05:01");
96/// let o = tz::Offset::from_seconds(-18_062).unwrap();
97/// assert_eq!(o.to_string(), "-05:01:02");
98///
99/// // The min value.
100/// let o = tz::Offset::from_seconds(-93_599).unwrap();
101/// assert_eq!(o.to_string(), "-25:59:59");
102/// // The max value.
103/// let o = tz::Offset::from_seconds(93_599).unwrap();
104/// assert_eq!(o.to_string(), "+25:59:59");
105/// // No offset.
106/// let o = tz::offset(0);
107/// assert_eq!(o.to_string(), "+00");
108/// ```
109///
110/// # Example
111///
112/// This shows how to create a zoned datetime with a time zone using a fixed
113/// offset:
114///
115/// ```
116/// use jiff::{civil::date, tz, ZonedDateTime};
117///
118/// let offset = tz::offset(-4).to_time_zone();
119/// let zdt = date(2024, 7, 8).at(15, 20, 0, 0).to_zoned_datetime(offset)?;
120/// assert_eq!(zdt.to_string(), "2024-07-08T15:20:00-04:00[-04:00]");
121///
122/// # Ok::<(), Box<dyn std::error::Error>>(())
123/// ```
124///
125/// Notice that the zoned datetime still includes a time zone annotation. But
126/// since there is no time zone identifier, the offset instead is repeated as
127/// an additional assertion that a fixed offset datetime was intended.
128#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
129#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
130pub struct Offset {
131 inner: JOffset,
132}
133
134impl Offset {
135 /// The minimum possible time zone offset.
136 ///
137 /// This corresponds to the offset `-25:59:59`.
138 pub const MIN: Offset = Offset { inner: JOffset::MIN };
139
140 /// The maximum possible time zone offset.
141 ///
142 /// This corresponds to the offset `25:59:59`.
143 pub const MAX: Offset = Offset { inner: JOffset::MAX };
144
145 /// The offset corresponding to UTC. That is, no offset at all.
146 ///
147 /// This is defined to always be equivalent to `Offset::ZERO`, but it is
148 /// semantically distinct. This ought to be used when UTC is desired
149 /// specifically, while `Offset::ZERO` ought to be used when one wants to
150 /// express "no offset." For example, when adding offsets, `Offset::ZERO`
151 /// corresponds to the identity.
152 pub const UTC: Offset = Offset { inner: JOffset::UTC };
153
154 /// The offset corresponding to no offset at all.
155 ///
156 /// This is defined to always be equivalent to `Offset::UTC`, but it is
157 /// semantically distinct. This ought to be used when a zero offset is
158 /// desired specifically, while `Offset::UTC` ought to be used when one
159 /// wants to express UTC. For example, when adding offsets, `Offset::ZERO`
160 /// corresponds to the identity.
161 pub const ZERO: Offset = Offset { inner: JOffset::UTC };
162
163 /// Creates a new time zone offset in a `const` context from a given number
164 /// of hours.
165 ///
166 /// Negative offsets correspond to time zones west of the prime meridian,
167 /// while positive offsets correspond to time zones east of the prime
168 /// meridian. Equivalently, in all cases, `civil-time - offset = UTC`.
169 ///
170 /// The fallible non-const version of this constructor is
171 /// [`Offset::from_hours`].
172 ///
173 /// # Panics
174 ///
175 /// This routine panics when the given number of hours is out of range.
176 /// Namely, `hours` must be in the range `-25..=25`.
177 ///
178 /// # Example
179 ///
180 /// ```
181 /// use jiff::tz::Offset;
182 ///
183 /// let o = Offset::constant(-5);
184 /// assert_eq!(o.seconds(), -18_000);
185 /// let o = Offset::constant(5);
186 /// assert_eq!(o.seconds(), 18_000);
187 /// ```
188 ///
189 /// Alternatively, one can use the terser `jiff::tz::offset` free function:
190 ///
191 /// ```
192 /// use jiff::tz;
193 ///
194 /// let o = tz::offset(-5);
195 /// assert_eq!(o.seconds(), -18_000);
196 /// let o = tz::offset(5);
197 /// assert_eq!(o.seconds(), 18_000);
198 /// ```
199 #[inline]
200 pub const fn constant(hours: i8) -> Offset {
201 let hours = constant::unwrapr!(
202 b::OffsetHours::checkc(hours as i64),
203 "invalid time zone offset hours",
204 );
205 Offset::constant_seconds((hours as i32) * 60 * 60)
206 }
207
208 /// Creates a new time zone offset in a `const` context from a given number
209 /// of seconds.
210 ///
211 /// Negative offsets correspond to time zones west of the prime meridian,
212 /// while positive offsets correspond to time zones east of the prime
213 /// meridian. Equivalently, in all cases, `civil-time - offset = UTC`.
214 ///
215 /// The fallible non-const version of this constructor is
216 /// [`Offset::from_seconds`].
217 ///
218 /// # Panics
219 ///
220 /// This routine panics when the given number of seconds is out of range.
221 /// The range corresponds to the offsets `-25:59:59..=25:59:59`. In units
222 /// of seconds, that corresponds to `-93,599..=93,599`.
223 ///
224 /// # Example
225 ///
226 /// ```ignore
227 /// use jiff::tz::Offset;
228 ///
229 /// let o = Offset::constant_seconds(-18_000);
230 /// assert_eq!(o.seconds(), -18_000);
231 /// let o = Offset::constant_seconds(18_000);
232 /// assert_eq!(o.seconds(), 18_000);
233 /// ```
234 // This is currently unexported because I find the name too long and
235 // very off-putting. I don't think non-hour offsets are used enough to
236 // warrant its existence. And I think I'd rather `Offset::hms` be const and
237 // exported instead of this monstrosity.
238 #[inline]
239 pub(crate) const fn constant_seconds(seconds: i32) -> Offset {
240 let inner = constant::unwrapr!(
241 JOffset::from_seconds(seconds),
242 "invalid time zone offset seconds",
243 );
244 Offset { inner }
245 }
246
247 /// Creates a new time zone offset from a given number of hours.
248 ///
249 /// Negative offsets correspond to time zones west of the prime meridian,
250 /// while positive offsets correspond to time zones east of the prime
251 /// meridian. Equivalently, in all cases, `civil-time - offset = UTC`.
252 ///
253 /// # Errors
254 ///
255 /// This routine returns an error when the given number of hours is out of
256 /// range. Namely, `hours` must be in the range `-25..=25`.
257 ///
258 /// # Example
259 ///
260 /// ```
261 /// use jiff::tz::Offset;
262 ///
263 /// let o = Offset::from_hours(-5)?;
264 /// assert_eq!(o.seconds(), -18_000);
265 /// let o = Offset::from_hours(5)?;
266 /// assert_eq!(o.seconds(), 18_000);
267 ///
268 /// # Ok::<(), Box<dyn std::error::Error>>(())
269 /// ```
270 #[inline]
271 pub fn from_hours(hours: i8) -> Result<Offset, Error> {
272 let inner = JOffset::from_hours(hours).map_err(Error::jcore_range)?;
273 Ok(Offset { inner })
274 }
275
276 /// Creates a new time zone offset in a `const` context from a given number
277 /// of seconds.
278 ///
279 /// Negative offsets correspond to time zones west of the prime meridian,
280 /// while positive offsets correspond to time zones east of the prime
281 /// meridian. Equivalently, in all cases, `civil-time - offset = UTC`.
282 ///
283 /// # Errors
284 ///
285 /// This routine returns an error when the given number of seconds is out
286 /// of range. The range corresponds to the offsets `-25:59:59..=25:59:59`.
287 /// In units of seconds, that corresponds to `-93,599..=93,599`.
288 ///
289 /// # Example
290 ///
291 /// ```
292 /// use jiff::tz::Offset;
293 ///
294 /// let o = Offset::from_seconds(-18_000)?;
295 /// assert_eq!(o.seconds(), -18_000);
296 /// let o = Offset::from_seconds(18_000)?;
297 /// assert_eq!(o.seconds(), 18_000);
298 ///
299 /// # Ok::<(), Box<dyn std::error::Error>>(())
300 /// ```
301 #[inline]
302 pub fn from_seconds(seconds: i32) -> Result<Offset, Error> {
303 let inner =
304 JOffset::from_seconds(seconds).map_err(Error::jcore_range)?;
305 Ok(Offset { inner })
306 }
307
308 /// Returns the total number of seconds in this offset.
309 ///
310 /// The value returned is guaranteed to represent an offset in the range
311 /// `-25:59:59..=25:59:59`. Or more precisely, the value will be in units
312 /// of seconds in the range `-93,599..=93,599`.
313 ///
314 /// Negative offsets correspond to time zones west of the prime meridian,
315 /// while positive offsets correspond to time zones east of the prime
316 /// meridian. Equivalently, in all cases, `civil-time - offset = UTC`.
317 ///
318 /// # Example
319 ///
320 /// ```
321 /// use jiff::tz;
322 ///
323 /// let o = tz::offset(-5);
324 /// assert_eq!(o.seconds(), -18_000);
325 /// let o = tz::offset(5);
326 /// assert_eq!(o.seconds(), 18_000);
327 /// ```
328 #[inline]
329 pub const fn seconds(self) -> i32 {
330 self.inner.seconds()
331 }
332
333 /// Returns the negation of this offset.
334 ///
335 /// A negative offset will become positive and vice versa. This is a no-op
336 /// if the offset is zero.
337 ///
338 /// This never panics.
339 ///
340 /// # Example
341 ///
342 /// ```
343 /// use jiff::tz;
344 ///
345 /// assert_eq!(tz::offset(-5).negate(), tz::offset(5));
346 /// // It's also available via the `-` operator:
347 /// assert_eq!(-tz::offset(-5), tz::offset(5));
348 /// ```
349 pub fn negate(self) -> Offset {
350 let inner = self.inner.negate();
351 Offset { inner }
352 }
353
354 /// Returns the "sign number" or "signum" of this offset.
355 ///
356 /// The number returned is `-1` when this offset is negative,
357 /// `0` when this offset is zero and `1` when this span is positive.
358 ///
359 /// # Example
360 ///
361 /// ```
362 /// use jiff::tz;
363 ///
364 /// assert_eq!(tz::offset(5).signum(), 1);
365 /// assert_eq!(tz::offset(0).signum(), 0);
366 /// assert_eq!(tz::offset(-5).signum(), -1);
367 /// ```
368 #[inline]
369 pub fn signum(self) -> i8 {
370 self.inner.signum()
371 }
372
373 /// Returns true if and only if this offset is positive.
374 ///
375 /// This returns false when the offset is zero or negative.
376 ///
377 /// # Example
378 ///
379 /// ```
380 /// use jiff::tz;
381 ///
382 /// assert!(tz::offset(5).is_positive());
383 /// assert!(!tz::offset(0).is_positive());
384 /// assert!(!tz::offset(-5).is_positive());
385 /// ```
386 pub fn is_positive(self) -> bool {
387 self.inner.is_positive()
388 }
389
390 /// Returns true if and only if this offset is less than zero.
391 ///
392 /// # Example
393 ///
394 /// ```
395 /// use jiff::tz;
396 ///
397 /// assert!(!tz::offset(5).is_negative());
398 /// assert!(!tz::offset(0).is_negative());
399 /// assert!(tz::offset(-5).is_negative());
400 /// ```
401 pub fn is_negative(self) -> bool {
402 self.inner.is_negative()
403 }
404
405 /// Returns true if and only if this offset is zero.
406 ///
407 /// Or equivalently, when this offset corresponds to [`Offset::UTC`].
408 ///
409 /// # Example
410 ///
411 /// ```
412 /// use jiff::tz;
413 ///
414 /// assert!(!tz::offset(5).is_zero());
415 /// assert!(tz::offset(0).is_zero());
416 /// assert!(!tz::offset(-5).is_zero());
417 /// ```
418 pub fn is_zero(self) -> bool {
419 self.inner.is_zero()
420 }
421
422 /// Converts this offset into a [`TimeZone`].
423 ///
424 /// This is a convenience function for calling [`TimeZone::fixed`] with
425 /// this offset.
426 ///
427 /// # Example
428 ///
429 /// ```
430 /// use jiff::tz::offset;
431 ///
432 /// let tz = offset(-4).to_time_zone();
433 /// assert_eq!(
434 /// tz.to_datetime(jiff::Timestamp::UNIX_EPOCH).to_string(),
435 /// "1969-12-31T20:00:00",
436 /// );
437 /// ```
438 pub fn to_time_zone(self) -> TimeZone {
439 TimeZone::fixed(self)
440 }
441
442 /// Converts the given timestamp to a civil datetime using this offset.
443 ///
444 /// # Example
445 ///
446 /// ```
447 /// use jiff::{civil::date, tz, Timestamp};
448 ///
449 /// assert_eq!(
450 /// tz::offset(-8).to_datetime(Timestamp::UNIX_EPOCH),
451 /// date(1969, 12, 31).at(16, 0, 0, 0),
452 /// );
453 /// ```
454 #[inline]
455 pub fn to_datetime(self, timestamp: Timestamp) -> civil::DateTime {
456 civil::DateTime::from_jcore(
457 self.inner.to_datetime(timestamp.to_jcore()),
458 )
459 }
460
461 /// Converts the given civil datetime to a timestamp using this offset.
462 ///
463 /// # Errors
464 ///
465 /// This returns an error if this would have returned a timestamp outside
466 /// of its minimum and maximum values.
467 ///
468 /// # Example
469 ///
470 /// This example shows how to find the timestamp corresponding to
471 /// `1969-12-31T16:00:00-08`.
472 ///
473 /// ```
474 /// use jiff::{civil::date, tz, Timestamp};
475 ///
476 /// assert_eq!(
477 /// tz::offset(-8).to_timestamp(date(1969, 12, 31).at(16, 0, 0, 0))?,
478 /// Timestamp::UNIX_EPOCH,
479 /// );
480 /// # Ok::<(), Box<dyn std::error::Error>>(())
481 /// ```
482 ///
483 /// This example shows some maximum boundary conditions where this routine
484 /// will fail:
485 ///
486 /// ```
487 /// use jiff::{civil::date, tz, Timestamp, ToSpan};
488 ///
489 /// let dt = date(9999, 12, 31).at(23, 0, 0, 0);
490 /// assert!(tz::offset(-8).to_timestamp(dt).is_err());
491 ///
492 /// // If the offset is big enough, then converting it to a UTC
493 /// // timestamp will fit, even when using the maximum civil datetime.
494 /// let dt = date(9999, 12, 31).at(23, 59, 59, 999_999_999);
495 /// assert_eq!(tz::Offset::MAX.to_timestamp(dt).unwrap(), Timestamp::MAX);
496 /// // But adjust the offset down 1 second is enough to go out-of-bounds.
497 /// assert!((tz::Offset::MAX - 1.seconds()).to_timestamp(dt).is_err());
498 /// ```
499 ///
500 /// Same as above, but for minimum values:
501 ///
502 /// ```
503 /// use jiff::{civil::date, tz, Timestamp, ToSpan};
504 ///
505 /// let dt = date(-9999, 1, 1).at(1, 0, 0, 0);
506 /// assert!(tz::offset(8).to_timestamp(dt).is_err());
507 ///
508 /// // If the offset is small enough, then converting it to a UTC
509 /// // timestamp will fit, even when using the minimum civil datetime.
510 /// let dt = date(-9999, 1, 1).at(0, 0, 0, 0);
511 /// assert_eq!(tz::Offset::MIN.to_timestamp(dt).unwrap(), Timestamp::MIN);
512 /// // But adjust the offset up 1 second is enough to go out-of-bounds.
513 /// assert!((tz::Offset::MIN + 1.seconds()).to_timestamp(dt).is_err());
514 /// ```
515 #[inline]
516 pub fn to_timestamp(
517 self,
518 dt: civil::DateTime,
519 ) -> Result<Timestamp, Error> {
520 Ok(Timestamp::from_jcore(
521 self.inner
522 .to_timestamp(dt.to_jcore())
523 .context(E::ConvertDateTimeToTimestamp { offset: self })?,
524 ))
525 }
526
527 /// Adds the given span of time to this offset.
528 ///
529 /// Since time zone offsets have second resolution, any fractional seconds
530 /// in the duration given are ignored.
531 ///
532 /// This operation accepts three different duration types: [`Span`],
533 /// [`SignedDuration`] or [`std::time::Duration`]. This is achieved via
534 /// `From` trait implementations for the [`OffsetArithmetic`] type.
535 ///
536 /// # Errors
537 ///
538 /// This returns an error if the result of adding the given span would
539 /// exceed the minimum or maximum allowed `Offset` value.
540 ///
541 /// This also returns an error if the span given contains any non-zero
542 /// units bigger than hours.
543 ///
544 /// # Example
545 ///
546 /// This example shows how to add one hour to an offset (if the offset
547 /// corresponds to standard time, then adding an hour will usually give
548 /// you DST time):
549 ///
550 /// ```
551 /// use jiff::{tz, ToSpan};
552 ///
553 /// let off = tz::offset(-5);
554 /// assert_eq!(off.checked_add(1.hours()).unwrap(), tz::offset(-4));
555 /// ```
556 ///
557 /// And note that while fractional seconds are ignored, units less than
558 /// seconds aren't ignored if they sum up to a duration at least as big
559 /// as one second:
560 ///
561 /// ```
562 /// use jiff::{tz, ToSpan};
563 ///
564 /// let off = tz::offset(5);
565 /// let span = 900.milliseconds()
566 /// .microseconds(50_000)
567 /// .nanoseconds(50_000_000);
568 /// assert_eq!(
569 /// off.checked_add(span).unwrap(),
570 /// tz::Offset::from_seconds((5 * 60 * 60) + 1).unwrap(),
571 /// );
572 /// // Any leftover fractional part is ignored.
573 /// let span = 901.milliseconds()
574 /// .microseconds(50_001)
575 /// .nanoseconds(50_000_001);
576 /// assert_eq!(
577 /// off.checked_add(span).unwrap(),
578 /// tz::Offset::from_seconds((5 * 60 * 60) + 1).unwrap(),
579 /// );
580 /// ```
581 ///
582 /// This example shows some cases where checked addition will fail.
583 ///
584 /// ```
585 /// use jiff::{tz::Offset, ToSpan};
586 ///
587 /// // Adding units above 'hour' always results in an error.
588 /// assert!(Offset::UTC.checked_add(1.day()).is_err());
589 /// assert!(Offset::UTC.checked_add(1.week()).is_err());
590 /// assert!(Offset::UTC.checked_add(1.month()).is_err());
591 /// assert!(Offset::UTC.checked_add(1.year()).is_err());
592 ///
593 /// // Adding even 1 second to the max, or subtracting 1 from the min,
594 /// // will result in overflow and thus an error will be returned.
595 /// assert!(Offset::MIN.checked_add(-1.seconds()).is_err());
596 /// assert!(Offset::MAX.checked_add(1.seconds()).is_err());
597 /// ```
598 ///
599 /// # Example: adding absolute durations
600 ///
601 /// This shows how to add signed and unsigned absolute durations to an
602 /// `Offset`. Like with `Span`s, any fractional seconds are ignored.
603 ///
604 /// ```
605 /// use std::time::Duration;
606 ///
607 /// use jiff::{tz::offset, SignedDuration};
608 ///
609 /// let off = offset(-10);
610 ///
611 /// let dur = SignedDuration::from_hours(11);
612 /// assert_eq!(off.checked_add(dur)?, offset(1));
613 /// assert_eq!(off.checked_add(-dur)?, offset(-21));
614 ///
615 /// // Any leftover time is truncated. That is, only
616 /// // whole seconds from the duration are considered.
617 /// let dur = Duration::new(3 * 60 * 60, 999_999_999);
618 /// assert_eq!(off.checked_add(dur)?, offset(-7));
619 ///
620 /// # Ok::<(), Box<dyn std::error::Error>>(())
621 /// ```
622 #[inline]
623 pub fn checked_add<A: Into<OffsetArithmetic>>(
624 self,
625 duration: A,
626 ) -> Result<Offset, Error> {
627 let duration: OffsetArithmetic = duration.into();
628 duration.checked_add(self)
629 }
630
631 #[inline]
632 fn checked_add_span(self, span: &Span) -> Result<Offset, Error> {
633 if let Some(err) = span.smallest_non_time_non_zero_unit_error() {
634 return Err(err);
635 }
636
637 let span = b::OffsetTotalSeconds::check(
638 span.to_invariant_duration().as_secs(),
639 )?;
640 // No overflow is possible here because even `Offset::MIN +
641 // Offset::MIN` fits into an `i32`. And note that the number of seconds
642 // in the span is limited to the range supported by `Offset`.
643 Offset::from_seconds(span + self.seconds())
644 }
645
646 #[inline]
647 fn checked_add_duration(
648 self,
649 duration: SignedDuration,
650 ) -> Result<Offset, Error> {
651 let duration = b::OffsetTotalSeconds::check(duration.as_secs())
652 .context(E::OverflowAddSignedDuration)?;
653 Offset::from_seconds(duration + self.seconds())
654 }
655
656 /// This routine is identical to [`Offset::checked_add`] with the duration
657 /// negated.
658 ///
659 /// # Errors
660 ///
661 /// This has the same error conditions as [`Offset::checked_add`].
662 ///
663 /// # Example
664 ///
665 /// ```
666 /// use std::time::Duration;
667 ///
668 /// use jiff::{tz, SignedDuration, ToSpan};
669 ///
670 /// let off = tz::offset(-4);
671 /// assert_eq!(
672 /// off.checked_sub(1.hours())?,
673 /// tz::offset(-5),
674 /// );
675 /// assert_eq!(
676 /// off.checked_sub(SignedDuration::from_hours(1))?,
677 /// tz::offset(-5),
678 /// );
679 /// assert_eq!(
680 /// off.checked_sub(Duration::from_secs(60 * 60))?,
681 /// tz::offset(-5),
682 /// );
683 ///
684 /// # Ok::<(), Box<dyn std::error::Error>>(())
685 /// ```
686 #[inline]
687 pub fn checked_sub<A: Into<OffsetArithmetic>>(
688 self,
689 duration: A,
690 ) -> Result<Offset, Error> {
691 let duration: OffsetArithmetic = duration.into();
692 duration.checked_neg().and_then(|oa| oa.checked_add(self))
693 }
694
695 /// This routine is identical to [`Offset::checked_add`], except the
696 /// result saturates on overflow. That is, instead of overflow, either
697 /// [`Offset::MIN`] or [`Offset::MAX`] is returned.
698 ///
699 /// # Errors
700 ///
701 /// This returns an error if the given `Span` contains any non-zero units
702 /// greater than hours.
703 ///
704 /// # Example
705 ///
706 /// This example shows some cases where saturation will occur.
707 ///
708 /// ```
709 /// use jiff::{tz::Offset, SignedDuration, ToSpan};
710 ///
711 /// // Spans with non-zero calendar units return an error.
712 /// assert!(Offset::UTC.saturating_add(1.weeks()).is_err());
713 /// assert!(Offset::UTC.saturating_add(1.months()).is_err());
714 /// assert!(Offset::UTC.saturating_add(1.years()).is_err());
715 ///
716 /// // Adding even 1 second to the max, or subtracting 1 from the min,
717 /// // will result in saturation.
718 /// assert_eq!(Offset::MIN.saturating_add(-1.seconds())?, Offset::MIN);
719 /// assert_eq!(Offset::MAX.saturating_add(1.seconds())?, Offset::MAX);
720 ///
721 /// // Adding absolute durations also saturates as expected.
722 /// assert_eq!(Offset::UTC.saturating_add(SignedDuration::MAX)?, Offset::MAX);
723 /// assert_eq!(Offset::UTC.saturating_add(SignedDuration::MIN)?, Offset::MIN);
724 /// assert_eq!(Offset::UTC.saturating_add(std::time::Duration::MAX)?, Offset::MAX);
725 ///
726 /// # Ok::<(), Box<dyn std::error::Error>>(())
727 /// ```
728 #[inline]
729 pub fn saturating_add<A: Into<OffsetArithmetic>>(
730 self,
731 duration: A,
732 ) -> Result<Offset, Error> {
733 let duration: OffsetArithmetic = duration.into();
734 duration.saturating_add(self)
735 }
736
737 /// This routine is identical to [`Offset::saturating_add`] with the
738 /// duration parameter negated.
739 ///
740 /// # Errors
741 ///
742 /// This returns an error if the given `Span` contains any non-zero units
743 /// greater than hours.
744 ///
745 /// # Example
746 ///
747 /// This example shows some cases where saturation will occur.
748 ///
749 /// ```
750 /// use jiff::{tz::Offset, SignedDuration, ToSpan};
751 ///
752 /// // Spans with non-zero calendar units return an error.
753 /// assert!(Offset::UTC.saturating_sub(1.weeks()).is_err());
754 /// assert!(Offset::UTC.saturating_sub(1.months()).is_err());
755 /// assert!(Offset::UTC.saturating_sub(1.years()).is_err());
756 ///
757 /// // Subtracting even 1 second from the min, or adding 1 to the max,
758 /// // will result in saturation.
759 /// assert_eq!(Offset::MIN.saturating_sub(1.seconds())?, Offset::MIN);
760 /// assert_eq!(Offset::MAX.saturating_sub(-1.seconds())?, Offset::MAX);
761 ///
762 /// // Adding absolute durations also saturates as expected.
763 /// assert_eq!(Offset::UTC.saturating_sub(SignedDuration::MAX)?, Offset::MIN);
764 /// assert_eq!(Offset::UTC.saturating_sub(SignedDuration::MIN)?, Offset::MAX);
765 /// assert_eq!(Offset::UTC.saturating_sub(std::time::Duration::MAX)?, Offset::MIN);
766 ///
767 /// # Ok::<(), Box<dyn std::error::Error>>(())
768 /// ```
769 #[inline]
770 pub fn saturating_sub<A: Into<OffsetArithmetic>>(
771 self,
772 duration: A,
773 ) -> Result<Offset, Error> {
774 let duration: OffsetArithmetic = duration.into();
775 let Ok(duration) = duration.checked_neg() else {
776 return Ok(Offset::MIN);
777 };
778 self.saturating_add(duration)
779 }
780
781 /// Returns the span of time from this offset until the other given.
782 ///
783 /// When the `other` offset is more west (i.e., more negative) of the prime
784 /// meridian than this offset, then the span returned will be negative.
785 ///
786 /// # Properties
787 ///
788 /// Adding the span returned to this offset will always equal the `other`
789 /// offset given.
790 ///
791 /// # Examples
792 ///
793 /// ```
794 /// use jiff::{tz, ToSpan};
795 ///
796 /// assert_eq!(
797 /// tz::offset(-5).until(tz::Offset::UTC),
798 /// (5 * 60 * 60).seconds().fieldwise(),
799 /// );
800 /// // Flipping the operands in this case results in a negative span.
801 /// assert_eq!(
802 /// tz::Offset::UTC.until(tz::offset(-5)),
803 /// -(5 * 60 * 60).seconds().fieldwise(),
804 /// );
805 /// // The maximum span you can get:
806 /// assert_eq!(
807 /// tz::Offset::MIN.until(tz::Offset::MAX),
808 /// 187_198.seconds().fieldwise(),
809 /// );
810 /// ```
811 #[inline]
812 pub fn until(self, other: Offset) -> Span {
813 // OK because `Offset::MIN - Offset::MAX` will
814 // never overflow `i32`.
815 let diff = other.seconds() - self.seconds();
816 Span::new().seconds(diff)
817 }
818
819 /// Returns the span of time since the other offset given from this offset.
820 ///
821 /// When the `other` is more east (i.e., more positive) of the prime
822 /// meridian than this offset, then the span returned will be negative.
823 ///
824 /// # Properties
825 ///
826 /// Adding the span returned to the `other` offset will always equal this
827 /// offset.
828 ///
829 /// # Examples
830 ///
831 /// ```
832 /// use jiff::{tz, ToSpan};
833 ///
834 /// assert_eq!(
835 /// tz::Offset::UTC.since(tz::offset(-5)),
836 /// (5 * 60 * 60).seconds().fieldwise(),
837 /// );
838 /// // Flipping the operands in this case results in a negative span.
839 /// assert_eq!(
840 /// tz::offset(-5).since(tz::Offset::UTC),
841 /// -(5 * 60 * 60).seconds().fieldwise(),
842 /// );
843 /// ```
844 #[inline]
845 pub fn since(self, other: Offset) -> Span {
846 self.until(other).negate()
847 }
848
849 /// Returns an absolute duration representing the difference in time from
850 /// this offset until the given `other` offset.
851 ///
852 /// When the `other` offset is more west (i.e., more negative) of the prime
853 /// meridian than this offset, then the duration returned will be negative.
854 ///
855 /// Unlike [`Offset::until`], this returns a duration corresponding to a
856 /// 96-bit integer of nanoseconds between two offsets.
857 ///
858 /// # When should I use this versus [`Offset::until`]?
859 ///
860 /// See the type documentation for [`SignedDuration`] for the section on
861 /// when one should use [`Span`] and when one should use `SignedDuration`.
862 /// In short, use `Span` (and therefore `Offset::until`) unless you have a
863 /// specific reason to do otherwise.
864 ///
865 /// # Examples
866 ///
867 /// ```
868 /// use jiff::{tz, SignedDuration};
869 ///
870 /// assert_eq!(
871 /// tz::offset(-5).duration_until(tz::Offset::UTC),
872 /// SignedDuration::from_hours(5),
873 /// );
874 /// // Flipping the operands in this case results in a negative span.
875 /// assert_eq!(
876 /// tz::Offset::UTC.duration_until(tz::offset(-5)),
877 /// SignedDuration::from_hours(-5),
878 /// );
879 /// ```
880 #[inline]
881 pub fn duration_until(self, other: Offset) -> SignedDuration {
882 SignedDuration::offset_until(self, other)
883 }
884
885 /// This routine is identical to [`Offset::duration_until`], but the order
886 /// of the parameters is flipped.
887 ///
888 /// # Examples
889 ///
890 /// ```
891 /// use jiff::{tz, SignedDuration};
892 ///
893 /// assert_eq!(
894 /// tz::Offset::UTC.duration_since(tz::offset(-5)),
895 /// SignedDuration::from_hours(5),
896 /// );
897 /// assert_eq!(
898 /// tz::offset(-5).duration_since(tz::Offset::UTC),
899 /// SignedDuration::from_hours(-5),
900 /// );
901 /// ```
902 #[inline]
903 pub fn duration_since(self, other: Offset) -> SignedDuration {
904 SignedDuration::offset_until(other, self)
905 }
906
907 /// Returns a new offset that is rounded according to the given
908 /// configuration.
909 ///
910 /// Rounding an offset has a number of parameters, all of which are
911 /// optional. When no parameters are given, then no rounding is done, and
912 /// the offset as given is returned. That is, it's a no-op.
913 ///
914 /// As is consistent with `Offset` itself, rounding only supports units of
915 /// hours, minutes or seconds. If any other unit is provided, then an error
916 /// is returned.
917 ///
918 /// The parameters are, in brief:
919 ///
920 /// * [`OffsetRound::smallest`] sets the smallest [`Unit`] that is allowed
921 /// to be non-zero in the offset returned. By default, it is set to
922 /// [`Unit::Second`], i.e., no rounding occurs. When the smallest unit is
923 /// set to something bigger than seconds, then the non-zero units in the
924 /// offset smaller than the smallest unit are used to determine how the
925 /// offset should be rounded. For example, rounding `+01:59` to the nearest
926 /// hour using the default rounding mode would produce `+02:00`.
927 /// * [`OffsetRound::mode`] determines how to handle the remainder
928 /// when rounding. The default is [`RoundMode::HalfExpand`], which
929 /// corresponds to how you were likely taught to round in school.
930 /// Alternative modes, like [`RoundMode::Trunc`], exist too. For example,
931 /// a truncating rounding of `+01:59` to the nearest hour would
932 /// produce `+01:00`.
933 /// * [`OffsetRound::increment`] sets the rounding granularity to
934 /// use for the configured smallest unit. For example, if the smallest unit
935 /// is minutes and the increment is `15`, then the offset returned will
936 /// always have its minute component set to a multiple of `15`.
937 ///
938 /// # Errors
939 ///
940 /// In general, there are two main ways for rounding to fail: an improper
941 /// configuration like trying to round an offset to the nearest unit other
942 /// than hours/minutes/seconds, or when overflow occurs. Overflow can occur
943 /// when the offset would exceed the minimum or maximum `Offset` values.
944 /// Typically, this can only realistically happen if the offset before
945 /// rounding is already close to its minimum or maximum value.
946 ///
947 /// # Example: rounding to the nearest multiple of 15 minutes
948 ///
949 /// Most time zone offsets fall on an hour boundary, but some fall on the
950 /// half-hour or even 15 minute boundary:
951 ///
952 /// ```
953 /// use jiff::{tz::Offset, Unit};
954 ///
955 /// let offset = Offset::from_seconds(-(44 * 60 + 30)).unwrap();
956 /// let rounded = offset.round((Unit::Minute, 15))?;
957 /// assert_eq!(rounded, Offset::from_seconds(-45 * 60).unwrap());
958 ///
959 /// # Ok::<(), Box<dyn std::error::Error>>(())
960 /// ```
961 ///
962 /// # Example: rounding can fail via overflow
963 ///
964 /// ```
965 /// use jiff::{tz::Offset, Unit};
966 ///
967 /// assert_eq!(Offset::MAX.to_string(), "+25:59:59");
968 /// assert_eq!(
969 /// Offset::MAX.round(Unit::Minute).unwrap_err().to_string(),
970 /// "rounding time zone offset resulted in a duration that overflows: \
971 /// parameter 'time zone offset total seconds' is not \
972 /// in the required range of -93599..=93599",
973 /// );
974 /// ```
975 #[inline]
976 pub fn round<R: Into<OffsetRound>>(
977 self,
978 options: R,
979 ) -> Result<Offset, Error> {
980 let options: OffsetRound = options.into();
981 options.round(self)
982 }
983}
984
985impl Offset {
986 /// This creates an `Offset` via hours/minutes/seconds components.
987 ///
988 /// Currently, it exists because it's convenient for use in tests.
989 ///
990 /// I originally wanted to expose this in the public API, but I couldn't
991 /// decide on how I wanted to treat signedness. There are a variety of
992 /// choices:
993 ///
994 /// * Require all values to be positive, and ask the caller to use
995 /// `-offset` to negate it.
996 /// * Require all values to have the same sign. If any differs, either
997 /// panic or return an error.
998 /// * If any have a negative sign, then behave as if all have a negative
999 /// sign.
1000 /// * Permit any combination of sign and combine them correctly.
1001 /// Similar to how `std::time::Duration::new(-1s, 1ns)` is turned into
1002 /// `-999,999,999ns`.
1003 ///
1004 /// I think the last option is probably the right behavior, but also the
1005 /// most annoying to implement. But if someone wants to take a crack at it,
1006 /// a PR is welcome.
1007 #[cfg(test)]
1008 #[inline]
1009 pub(crate) const fn hms(hours: i8, minutes: i8, seconds: i8) -> Offset {
1010 let hours = constant::unwrapr!(
1011 b::OffsetHours::checkc(hours as i64),
1012 "invalid time zone offset hours",
1013 );
1014 let minutes = constant::unwrapr!(
1015 b::OffsetMinutes::checkc(minutes as i64),
1016 "invalid time zone offset minutes",
1017 );
1018 let seconds = constant::unwrapr!(
1019 b::OffsetSeconds::checkc(seconds as i64),
1020 "invalid time zone offset seconds",
1021 );
1022 let seconds = (hours as i32 * c::SECS_PER_HOUR_32)
1023 + (minutes as i32 * c::SECS_PER_MIN_32)
1024 + (seconds as i32);
1025 let inner =
1026 constant::unwrapr!(JOffset::from_seconds(seconds), "valid offset");
1027 Offset { inner }
1028 }
1029
1030 #[inline]
1031 pub(crate) fn part_hours(self) -> i8 {
1032 (self.seconds() / c::SECS_PER_HOUR_32) as i8
1033 }
1034
1035 #[inline]
1036 pub(crate) fn part_minutes(self) -> i8 {
1037 ((self.seconds() / c::SECS_PER_MIN_32) % c::MINS_PER_HOUR_32) as i8
1038 }
1039
1040 #[inline]
1041 pub(crate) fn part_seconds(self) -> i8 {
1042 (self.seconds() % c::SECS_PER_MIN_32) as i8
1043 }
1044
1045 #[inline]
1046 pub(crate) const fn from_jcore(offset: JOffset) -> Offset {
1047 Offset { inner: offset }
1048 }
1049
1050 #[inline]
1051 pub(crate) const fn from_seconds_unchecked(seconds: i32) -> Offset {
1052 // TODO: Benchmark whether the check here is hurting us. If it is,
1053 // then we'll need a safety boundary in jiff-core to support this
1054 // operation.
1055 let inner =
1056 constant::unwrapr!(JOffset::from_seconds(seconds), "valid offset");
1057 Offset { inner }
1058 }
1059
1060 #[inline]
1061 pub(crate) fn to_abbreviation(&self) -> jcore::tz::Abbreviation {
1062 use core::fmt::Write;
1063
1064 let mut dst = jcore::util::ArrayStr::<9>::new("").unwrap();
1065 // OK because the string representation of an offset
1066 // can never exceed 9 bytes. The longest possible, e.g.,
1067 // is `-25:59:59`.
1068 write!(&mut dst, "{}", self).unwrap();
1069 // The correctness argument here is unfortunately convuleted. In
1070 // environments with `alloc`, this will always succeed because the
1071 // heap is used as a fallback. But in core-only environments, the
1072 // abbreviation capacity is specifically set to `9` in jiff-core to
1073 // accommodate this use case. Thus, this can never fail.
1074 jcore::tz::Abbreviation::new(dst.as_str())
1075 .expect("`Abbreviation` capacity is big enough")
1076 }
1077
1078 /// Round this offset to the nearest minute and returns the hour/minute
1079 /// components as unsigned integers.
1080 ///
1081 /// Generally speaking, the second component on an offset is always zero.
1082 /// There are _some_ cases in the tzdb where this isn't true (like
1083 /// `Africa/Monrovia` before `1972-01-07`), but virtually all time zones
1084 /// use offsets with whole hours. Some go to whole minutes. The only other
1085 /// way to get non-zero seconds is to explicitly use a fixed offset.
1086 ///
1087 /// A pathological case is the minimum or maximum offset. In this case,
1088 /// truncation is used instead of rounding to the nearest whole minute.
1089 #[inline]
1090 pub(crate) fn round_to_nearest_minute(self) -> (u8, u8) {
1091 #[inline(never)]
1092 #[cold]
1093 fn round(mut hours: u8, mut minutes: u8) -> (u8, u8) {
1094 const MAX_HOURS: u8 = b::OffsetHours::MAX.unsigned_abs();
1095 const MAX_MINS: u8 = b::OffsetMinutes::MAX.unsigned_abs();
1096
1097 if minutes == 59 {
1098 hours += 1;
1099 minutes = 0;
1100 // An edge case: if rounding results in an offset beyond
1101 // Jiff's boundaries, then we truncate to the max (or min)
1102 // offset supported.
1103 if hours > MAX_HOURS {
1104 hours = MAX_HOURS;
1105 minutes = MAX_MINS;
1106 }
1107 } else {
1108 minutes += 1;
1109 }
1110 (hours, minutes)
1111 }
1112
1113 let total_seconds = self.seconds().unsigned_abs();
1114 let hours = (total_seconds / (60 * 60)) as u8;
1115 let minutes = ((total_seconds / 60) % 60) as u8;
1116 let seconds = (total_seconds % 60) as u8;
1117
1118 // RFCs 2822, 3339 and 9557 require that time zone offsets are an
1119 // integral number of minutes. While rounding based on seconds doesn't
1120 // seem clearly indicated, the `1937-01-01T12:00:27.87+00:20` example
1121 // in RFC 3339 seems to suggest that the number of minutes should be
1122 // "as close as possible" to the actual offset. So we just do basic
1123 // rounding here.
1124 if seconds >= 30 {
1125 return round(hours, minutes);
1126 }
1127 (hours, minutes)
1128 }
1129}
1130
1131impl core::fmt::Debug for Offset {
1132 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1133 let sign = if self.is_negative() { "-" } else { "" };
1134 write!(
1135 f,
1136 "{sign}{:02}:{:02}:{:02}",
1137 self.part_hours().unsigned_abs(),
1138 self.part_minutes().unsigned_abs(),
1139 self.part_seconds().unsigned_abs(),
1140 )
1141 }
1142}
1143
1144impl core::fmt::Display for Offset {
1145 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1146 let sign = if self.is_negative() { "-" } else { "+" };
1147 let hours = self.part_hours().unsigned_abs();
1148 let minutes = self.part_minutes().unsigned_abs();
1149 let seconds = self.part_seconds().unsigned_abs();
1150 if hours == 0 && minutes == 0 && seconds == 0 {
1151 f.write_str("+00")
1152 } else if hours != 0 && minutes == 0 && seconds == 0 {
1153 write!(f, "{sign}{hours:02}")
1154 } else if minutes != 0 && seconds == 0 {
1155 write!(f, "{sign}{hours:02}:{minutes:02}")
1156 } else {
1157 write!(f, "{sign}{hours:02}:{minutes:02}:{seconds:02}")
1158 }
1159 }
1160}
1161
1162/// Adds a span of time to an offset. This panics on overflow.
1163///
1164/// For checked arithmetic, see [`Offset::checked_add`].
1165impl Add<Span> for Offset {
1166 type Output = Offset;
1167
1168 #[inline]
1169 fn add(self, rhs: Span) -> Offset {
1170 self.checked_add(rhs)
1171 .expect("adding span to offset should not overflow")
1172 }
1173}
1174
1175/// Adds a span of time to an offset in place. This panics on overflow.
1176///
1177/// For checked arithmetic, see [`Offset::checked_add`].
1178impl AddAssign<Span> for Offset {
1179 #[inline]
1180 fn add_assign(&mut self, rhs: Span) {
1181 *self = self.add(rhs);
1182 }
1183}
1184
1185/// Subtracts a span of time from an offset. This panics on overflow.
1186///
1187/// For checked arithmetic, see [`Offset::checked_sub`].
1188impl Sub<Span> for Offset {
1189 type Output = Offset;
1190
1191 #[inline]
1192 fn sub(self, rhs: Span) -> Offset {
1193 self.checked_sub(rhs)
1194 .expect("subtracting span from offsetsshould not overflow")
1195 }
1196}
1197
1198/// Subtracts a span of time from an offset in place. This panics on overflow.
1199///
1200/// For checked arithmetic, see [`Offset::checked_sub`].
1201impl SubAssign<Span> for Offset {
1202 #[inline]
1203 fn sub_assign(&mut self, rhs: Span) {
1204 *self = self.sub(rhs);
1205 }
1206}
1207
1208/// Computes the span of time between two offsets.
1209///
1210/// This will return a negative span when the offset being subtracted is
1211/// greater (i.e., more east with respect to the prime meridian).
1212impl Sub for Offset {
1213 type Output = Span;
1214
1215 #[inline]
1216 fn sub(self, rhs: Offset) -> Span {
1217 self.since(rhs)
1218 }
1219}
1220
1221/// Adds a signed duration of time to an offset. This panics on overflow.
1222///
1223/// For checked arithmetic, see [`Offset::checked_add`].
1224impl Add<SignedDuration> for Offset {
1225 type Output = Offset;
1226
1227 #[inline]
1228 fn add(self, rhs: SignedDuration) -> Offset {
1229 self.checked_add(rhs)
1230 .expect("adding signed duration to offset should not overflow")
1231 }
1232}
1233
1234/// Adds a signed duration of time to an offset in place. This panics on
1235/// overflow.
1236///
1237/// For checked arithmetic, see [`Offset::checked_add`].
1238impl AddAssign<SignedDuration> for Offset {
1239 #[inline]
1240 fn add_assign(&mut self, rhs: SignedDuration) {
1241 *self = self.add(rhs);
1242 }
1243}
1244
1245/// Subtracts a signed duration of time from an offset. This panics on
1246/// overflow.
1247///
1248/// For checked arithmetic, see [`Offset::checked_sub`].
1249impl Sub<SignedDuration> for Offset {
1250 type Output = Offset;
1251
1252 #[inline]
1253 fn sub(self, rhs: SignedDuration) -> Offset {
1254 self.checked_sub(rhs).expect(
1255 "subtracting signed duration from offsetsshould not overflow",
1256 )
1257 }
1258}
1259
1260/// Subtracts a signed duration of time from an offset in place. This panics on
1261/// overflow.
1262///
1263/// For checked arithmetic, see [`Offset::checked_sub`].
1264impl SubAssign<SignedDuration> for Offset {
1265 #[inline]
1266 fn sub_assign(&mut self, rhs: SignedDuration) {
1267 *self = self.sub(rhs);
1268 }
1269}
1270
1271/// Adds an unsigned duration of time to an offset. This panics on overflow.
1272///
1273/// For checked arithmetic, see [`Offset::checked_add`].
1274impl Add<UnsignedDuration> for Offset {
1275 type Output = Offset;
1276
1277 #[inline]
1278 fn add(self, rhs: UnsignedDuration) -> Offset {
1279 self.checked_add(rhs)
1280 .expect("adding unsigned duration to offset should not overflow")
1281 }
1282}
1283
1284/// Adds an unsigned duration of time to an offset in place. This panics on
1285/// overflow.
1286///
1287/// For checked arithmetic, see [`Offset::checked_add`].
1288impl AddAssign<UnsignedDuration> for Offset {
1289 #[inline]
1290 fn add_assign(&mut self, rhs: UnsignedDuration) {
1291 *self = self.add(rhs);
1292 }
1293}
1294
1295/// Subtracts an unsigned duration of time from an offset. This panics on
1296/// overflow.
1297///
1298/// For checked arithmetic, see [`Offset::checked_sub`].
1299impl Sub<UnsignedDuration> for Offset {
1300 type Output = Offset;
1301
1302 #[inline]
1303 fn sub(self, rhs: UnsignedDuration) -> Offset {
1304 self.checked_sub(rhs).expect(
1305 "subtracting unsigned duration from offsetsshould not overflow",
1306 )
1307 }
1308}
1309
1310/// Subtracts an unsigned duration of time from an offset in place. This panics
1311/// on overflow.
1312///
1313/// For checked arithmetic, see [`Offset::checked_sub`].
1314impl SubAssign<UnsignedDuration> for Offset {
1315 #[inline]
1316 fn sub_assign(&mut self, rhs: UnsignedDuration) {
1317 *self = self.sub(rhs);
1318 }
1319}
1320
1321/// Negate this offset.
1322///
1323/// A positive offset becomes negative and vice versa. This is a no-op for the
1324/// zero offset.
1325///
1326/// This never panics.
1327impl Neg for Offset {
1328 type Output = Offset;
1329
1330 #[inline]
1331 fn neg(self) -> Offset {
1332 self.negate()
1333 }
1334}
1335
1336/// Converts a `SignedDuration` to a time zone offset.
1337///
1338/// If the signed duration has fractional seconds, then it is automatically
1339/// rounded to the nearest second. (Because an `Offset` has only second
1340/// precision.)
1341///
1342/// # Errors
1343///
1344/// This returns an error if the duration overflows the limits of an `Offset`.
1345///
1346/// # Example
1347///
1348/// ```
1349/// use jiff::{tz::{self, Offset}, SignedDuration};
1350///
1351/// let sdur = SignedDuration::from_secs(-5 * 60 * 60);
1352/// let offset = Offset::try_from(sdur)?;
1353/// assert_eq!(offset, tz::offset(-5));
1354///
1355/// // Sub-seconds results in rounded.
1356/// let sdur = SignedDuration::new(-5 * 60 * 60, -500_000_000);
1357/// let offset = Offset::try_from(sdur)?;
1358/// assert_eq!(offset, tz::Offset::from_seconds(-(5 * 60 * 60 + 1)).unwrap());
1359///
1360/// # Ok::<(), Box<dyn std::error::Error>>(())
1361/// ```
1362impl TryFrom<SignedDuration> for Offset {
1363 type Error = Error;
1364
1365 fn try_from(sdur: SignedDuration) -> Result<Offset, Error> {
1366 let mut seconds = sdur.as_secs();
1367 let subsec = sdur.subsec_nanos();
1368 if subsec >= 500_000_000 {
1369 seconds = seconds.saturating_add(1);
1370 } else if subsec <= -500_000_000 {
1371 seconds = seconds.saturating_sub(1);
1372 }
1373 let seconds =
1374 i32::try_from(seconds).map_err(|_| E::OverflowSignedDuration)?;
1375 Offset::from_seconds(seconds)
1376 .map_err(|_| Error::from(E::OverflowSignedDuration))
1377 }
1378}
1379
1380#[cfg(feature = "defmt")]
1381impl defmt::Format for Offset {
1382 fn format(&self, f: defmt::Formatter) {
1383 let sign = if self.is_negative() { "-" } else { "" };
1384 defmt::write!(
1385 f,
1386 "{=str}{=u8:02}:{=u8:02}:{=u8:02}",
1387 sign,
1388 self.part_hours().unsigned_abs(),
1389 self.part_minutes().unsigned_abs(),
1390 self.part_seconds().unsigned_abs(),
1391 )
1392 }
1393}
1394
1395/// Options for [`Offset::checked_add`] and [`Offset::checked_sub`].
1396///
1397/// This type provides a way to ergonomically add one of a few different
1398/// duration types to a [`Offset`].
1399///
1400/// The main way to construct values of this type is with its `From` trait
1401/// implementations:
1402///
1403/// * `From<Span> for OffsetArithmetic` adds (or subtracts) the given span to
1404/// the receiver offset.
1405/// * `From<SignedDuration> for OffsetArithmetic` adds (or subtracts)
1406/// the given signed duration to the receiver offset.
1407/// * `From<std::time::Duration> for OffsetArithmetic` adds (or subtracts)
1408/// the given unsigned duration to the receiver offset.
1409///
1410/// # Example
1411///
1412/// ```
1413/// use std::time::Duration;
1414///
1415/// use jiff::{tz::offset, SignedDuration, ToSpan};
1416///
1417/// let off = offset(-10);
1418/// assert_eq!(off.checked_add(11.hours())?, offset(1));
1419/// assert_eq!(off.checked_add(SignedDuration::from_hours(11))?, offset(1));
1420/// assert_eq!(off.checked_add(Duration::from_secs(11 * 60 * 60))?, offset(1));
1421///
1422/// # Ok::<(), Box<dyn std::error::Error>>(())
1423/// ```
1424#[derive(Clone, Copy, Debug)]
1425pub struct OffsetArithmetic {
1426 duration: Duration,
1427}
1428
1429impl OffsetArithmetic {
1430 #[inline]
1431 fn checked_add(self, offset: Offset) -> Result<Offset, Error> {
1432 match self.duration.to_signed()? {
1433 SDuration::Span(span) => offset.checked_add_span(span),
1434 SDuration::Absolute(sdur) => offset.checked_add_duration(sdur),
1435 }
1436 }
1437
1438 #[inline]
1439 fn saturating_add(self, offset: Offset) -> Result<Offset, Error> {
1440 let Ok(signed) = self.duration.to_signed() else {
1441 return Ok(Offset::MAX);
1442 };
1443 let result = match signed {
1444 SDuration::Span(span) => {
1445 if let Some(err) = span.smallest_non_time_non_zero_unit_error()
1446 {
1447 return Err(err);
1448 }
1449 offset.checked_add_span(span)
1450 }
1451 SDuration::Absolute(sdur) => offset.checked_add_duration(sdur),
1452 };
1453 Ok(result.unwrap_or_else(|_| {
1454 if self.is_negative() { Offset::MIN } else { Offset::MAX }
1455 }))
1456 }
1457
1458 #[inline]
1459 fn checked_neg(self) -> Result<OffsetArithmetic, Error> {
1460 let duration = self.duration.checked_neg()?;
1461 Ok(OffsetArithmetic { duration })
1462 }
1463
1464 #[inline]
1465 fn is_negative(&self) -> bool {
1466 self.duration.is_negative()
1467 }
1468}
1469
1470impl From<Span> for OffsetArithmetic {
1471 fn from(span: Span) -> OffsetArithmetic {
1472 let duration = Duration::from(span);
1473 OffsetArithmetic { duration }
1474 }
1475}
1476
1477impl From<SignedDuration> for OffsetArithmetic {
1478 fn from(sdur: SignedDuration) -> OffsetArithmetic {
1479 let duration = Duration::from(sdur);
1480 OffsetArithmetic { duration }
1481 }
1482}
1483
1484impl From<UnsignedDuration> for OffsetArithmetic {
1485 fn from(udur: UnsignedDuration) -> OffsetArithmetic {
1486 let duration = Duration::from(udur);
1487 OffsetArithmetic { duration }
1488 }
1489}
1490
1491impl<'a> From<&'a Span> for OffsetArithmetic {
1492 fn from(span: &'a Span) -> OffsetArithmetic {
1493 OffsetArithmetic::from(*span)
1494 }
1495}
1496
1497impl<'a> From<&'a SignedDuration> for OffsetArithmetic {
1498 fn from(sdur: &'a SignedDuration) -> OffsetArithmetic {
1499 OffsetArithmetic::from(*sdur)
1500 }
1501}
1502
1503impl<'a> From<&'a UnsignedDuration> for OffsetArithmetic {
1504 fn from(udur: &'a UnsignedDuration) -> OffsetArithmetic {
1505 OffsetArithmetic::from(*udur)
1506 }
1507}
1508
1509/// Options for [`Offset::round`].
1510///
1511/// This type provides a way to configure the rounding of an offset. This
1512/// includes setting the smallest unit (i.e., the unit to round), the rounding
1513/// increment and the rounding mode (e.g., "ceil" or "truncate").
1514///
1515/// [`Offset::round`] accepts anything that implements
1516/// `Into<OffsetRound>`. There are a few key trait implementations that
1517/// make this convenient:
1518///
1519/// * `From<Unit> for OffsetRound` will construct a rounding
1520/// configuration where the smallest unit is set to the one given.
1521/// * `From<(Unit, i64)> for OffsetRound` will construct a rounding
1522/// configuration where the smallest unit and the rounding increment are set to
1523/// the ones given.
1524///
1525/// In order to set other options (like the rounding mode), one must explicitly
1526/// create a `OffsetRound` and pass it to `Offset::round`.
1527///
1528/// # Example
1529///
1530/// This example shows how to always round up to the nearest half-hour:
1531///
1532/// ```
1533/// use jiff::{tz::{Offset, OffsetRound}, RoundMode, Unit};
1534///
1535/// let offset = Offset::from_seconds(4 * 60 * 60 + 17 * 60).unwrap();
1536/// let rounded = offset.round(
1537/// OffsetRound::new()
1538/// .smallest(Unit::Minute)
1539/// .increment(30)
1540/// .mode(RoundMode::Expand),
1541/// )?;
1542/// assert_eq!(rounded, Offset::from_seconds(4 * 60 * 60 + 30 * 60).unwrap());
1543///
1544/// # Ok::<(), Box<dyn std::error::Error>>(())
1545/// ```
1546#[derive(Clone, Copy, Debug)]
1547pub struct OffsetRound {
1548 smallest: Unit,
1549 mode: RoundMode,
1550 increment: i64,
1551}
1552
1553impl OffsetRound {
1554 /// Create a new default configuration for rounding a time zone offset via
1555 /// [`Offset::round`].
1556 ///
1557 /// The default configuration does no rounding.
1558 #[inline]
1559 pub fn new() -> OffsetRound {
1560 OffsetRound {
1561 smallest: Unit::Second,
1562 mode: RoundMode::HalfExpand,
1563 increment: 1,
1564 }
1565 }
1566
1567 /// Set the smallest units allowed in the offset returned. These are the
1568 /// units that the offset is rounded to.
1569 ///
1570 /// # Errors
1571 ///
1572 /// The unit must be [`Unit::Hour`], [`Unit::Minute`] or [`Unit::Second`].
1573 ///
1574 /// # Example
1575 ///
1576 /// A basic example that rounds to the nearest minute:
1577 ///
1578 /// ```
1579 /// use jiff::{tz::Offset, Unit};
1580 ///
1581 /// let offset = Offset::from_seconds(-(5 * 60 * 60 + 30)).unwrap();
1582 /// assert_eq!(offset.round(Unit::Hour)?, Offset::from_hours(-5).unwrap());
1583 ///
1584 /// # Ok::<(), Box<dyn std::error::Error>>(())
1585 /// ```
1586 #[inline]
1587 pub fn smallest(self, unit: Unit) -> OffsetRound {
1588 OffsetRound { smallest: unit, ..self }
1589 }
1590
1591 /// Set the rounding mode.
1592 ///
1593 /// This defaults to [`RoundMode::HalfExpand`], which makes rounding work
1594 /// like how you were taught in school.
1595 ///
1596 /// # Example
1597 ///
1598 /// A basic example that rounds to the nearest hour, but changing its
1599 /// rounding mode to truncation:
1600 ///
1601 /// ```
1602 /// use jiff::{tz::{Offset, OffsetRound}, RoundMode, Unit};
1603 ///
1604 /// let offset = Offset::from_seconds(-(5 * 60 * 60 + 30 * 60)).unwrap();
1605 /// assert_eq!(
1606 /// offset.round(OffsetRound::new()
1607 /// .smallest(Unit::Hour)
1608 /// .mode(RoundMode::Trunc),
1609 /// )?,
1610 /// // The default round mode does rounding like
1611 /// // how you probably learned in school, and would
1612 /// // result in rounding to -6 hours. But we
1613 /// // change it to truncation here, which makes it
1614 /// // round -5.
1615 /// Offset::from_hours(-5).unwrap(),
1616 /// );
1617 ///
1618 /// # Ok::<(), Box<dyn std::error::Error>>(())
1619 /// ```
1620 #[inline]
1621 pub fn mode(self, mode: RoundMode) -> OffsetRound {
1622 OffsetRound { mode, ..self }
1623 }
1624
1625 /// Set the rounding increment for the smallest unit.
1626 ///
1627 /// The default value is `1`. Other values permit rounding the smallest
1628 /// unit to the nearest integer increment specified. For example, if the
1629 /// smallest unit is set to [`Unit::Minute`], then a rounding increment of
1630 /// `30` would result in rounding in increments of a half hour. That is,
1631 /// the only minute value that could result would be `0` or `30`.
1632 ///
1633 /// # Errors
1634 ///
1635 /// Unlike rounding a [`Span`](crate::Span), the increment does not need to
1636 /// divide evenly into the next largest unit. Callers can round an offset
1637 /// to any increment value so long as it is greater than zero and less than
1638 /// or equal to `1_000_000_000`.
1639 ///
1640 /// # Example
1641 ///
1642 /// This shows how to round an offset to the nearest 30 minute increment:
1643 ///
1644 /// ```
1645 /// use jiff::{tz::Offset, Unit};
1646 ///
1647 /// let offset = Offset::from_seconds(4 * 60 * 60 + 15 * 60).unwrap();
1648 /// assert_eq!(
1649 /// offset.round((Unit::Minute, 30))?,
1650 /// Offset::from_seconds(4 * 60 * 60 + 30 * 60).unwrap(),
1651 /// );
1652 ///
1653 /// # Ok::<(), Box<dyn std::error::Error>>(())
1654 /// ```
1655 #[inline]
1656 pub fn increment(self, increment: i64) -> OffsetRound {
1657 OffsetRound { increment, ..self }
1658 }
1659
1660 /// Does the actual offset rounding.
1661 fn round(&self, offset: Offset) -> Result<Offset, Error> {
1662 let increment = Increment::for_offset(self.smallest, self.increment)?;
1663 // let rounded_sdur = SignedDuration::from(offset).round(self.0)?;
1664 let rounded = increment
1665 .round(self.mode, SignedDuration::from(offset))
1666 .context(E::RoundOverflow)?;
1667 Offset::try_from(rounded)
1668 .map_err(|_| b::OffsetTotalSeconds::error())
1669 .context(E::RoundOverflow)
1670 }
1671}
1672
1673impl Default for OffsetRound {
1674 fn default() -> OffsetRound {
1675 OffsetRound::new()
1676 }
1677}
1678
1679impl From<Unit> for OffsetRound {
1680 fn from(unit: Unit) -> OffsetRound {
1681 OffsetRound::default().smallest(unit)
1682 }
1683}
1684
1685impl From<(Unit, i64)> for OffsetRound {
1686 fn from((unit, increment): (Unit, i64)) -> OffsetRound {
1687 OffsetRound::default().smallest(unit).increment(increment)
1688 }
1689}
1690
1691/// Configuration for resolving disparities between an offset and a time zone.
1692///
1693/// A conflict between an offset and a time zone most commonly appears in a
1694/// datetime string. For example, `2024-06-14T17:30-05[America/New_York]`
1695/// has a definitive inconsistency between the reported offset (`-05`) and
1696/// the time zone (`America/New_York`), because at this time in New York,
1697/// daylight saving time (DST) was in effect. In New York in the year 2024,
1698/// DST corresponded to the UTC offset `-04`.
1699///
1700/// Other conflict variations exist. For example, in 2019, Brazil abolished
1701/// DST completely. But if one were to create a datetime for 2020 in 2018, that
1702/// datetime in 2020 would reflect the DST rules as they exist in 2018. That
1703/// could in turn result in a datetime with an offset that is incorrect with
1704/// respect to the rules in 2019.
1705///
1706/// For this reason, this crate exposes a few ways of resolving these
1707/// conflicts. It is most commonly used as configuration for parsing
1708/// [`ZonedDateTime`](crate::ZonedDateTime) values via
1709/// [`fmt::temporal::DateTimeParser::offset_conflict`](crate::fmt::temporal::DateTimeParser::offset_conflict).
1710/// But this configuration can also be used directly via
1711/// [`OffsetConflict::resolve`].
1712///
1713/// The default value is `OffsetConflict::Reject`, which results in an error
1714/// being returned if the offset and a time zone are not in agreement. This is
1715/// the default so that Jiff does not automatically make silent choices about
1716/// whether to prefer the time zone or the offset. The
1717/// [`fmt::temporal::DateTimeParser::parse_zoned_datetime_with`](crate::fmt::temporal::DateTimeParser::parse_zoned_datetime_with)
1718/// documentation shows an example demonstrating its utility in the face of
1719/// changes in the law, such as the abolition of daylight saving time. By
1720/// rejecting such things, one can ensure that the original timestamp is
1721/// preserved or else an error occurs.
1722///
1723/// This enum is non-exhaustive so that other forms of offset conflicts may be
1724/// added in semver compatible releases.
1725///
1726/// # Example
1727///
1728/// This example shows how to always use the time zone even if the offset is
1729/// wrong.
1730///
1731/// ```
1732/// use jiff::{civil::date, tz};
1733///
1734/// let dt = date(2024, 6, 14).at(17, 30, 0, 0);
1735/// let offset = tz::offset(-5); // wrong! should be -4
1736/// let newyork = tz::db().get("America/New_York")?;
1737///
1738/// // The default conflict resolution, 'Reject', will error.
1739/// let result = tz::OffsetConflict::Reject
1740/// .resolve(dt, offset, newyork.clone());
1741/// assert!(result.is_err());
1742///
1743/// // But we can change it to always prefer the time zone.
1744/// let zdt = tz::OffsetConflict::AlwaysTimeZone
1745/// .resolve(dt, offset, newyork.clone())?
1746/// .unambiguous()?;
1747/// assert_eq!(zdt.datetime(), date(2024, 6, 14).at(17, 30, 0, 0));
1748/// // The offset has been corrected automatically.
1749/// assert_eq!(zdt.offset(), tz::offset(-4));
1750///
1751/// # Ok::<(), Box<dyn std::error::Error>>(())
1752/// ```
1753///
1754/// # Example: parsing
1755///
1756/// This example shows how to set the offset conflict resolution configuration
1757/// while parsing a [`ZonedDateTime`](crate::ZonedDateTime) datetime. In this
1758/// example, we always prefer the offset, even if it conflicts with the time
1759/// zone.
1760///
1761/// ```
1762/// use jiff::{civil::date, fmt::temporal::DateTimeParser, tz};
1763///
1764/// static PARSER: DateTimeParser = DateTimeParser::new()
1765/// .offset_conflict(tz::OffsetConflict::AlwaysOffset);
1766///
1767/// let zdt = PARSER
1768/// .parse_zoned_datetime("2024-06-14T17:30-05[America/New_York]")?;
1769/// // The time *and* offset have been corrected. The offset given was invalid,
1770/// // so it cannot be kept, but the timestamp returned is equivalent to
1771/// // `2024-06-14T17:30-05`. It is just adjusted automatically to be correct
1772/// // in the `America/New_York` time zone.
1773/// assert_eq!(zdt.datetime(), date(2024, 6, 14).at(18, 30, 0, 0));
1774/// assert_eq!(zdt.offset(), tz::offset(-4));
1775///
1776/// # Ok::<(), Box<dyn std::error::Error>>(())
1777/// ```
1778#[derive(Clone, Copy, Debug, Default)]
1779#[non_exhaustive]
1780pub enum OffsetConflict {
1781 /// When the offset and time zone are in conflict, this will always use
1782 /// the offset to interpret the date time.
1783 ///
1784 /// When resolving to a [`AmbiguousZonedDateTime`], the time zone attached
1785 /// to the timestamp will still be the same as the time zone given. The
1786 /// difference here is that the offset will be adjusted such that it is
1787 /// correct for the given time zone. However, the timestamp itself will
1788 /// always match the datetime and offset given (and which is always
1789 /// unambiguous).
1790 ///
1791 /// Basically, you should use this option when you want to keep the exact
1792 /// time unchanged (as indicated by the datetime and offset), even if it
1793 /// means a change to civil time.
1794 AlwaysOffset,
1795 /// When the offset and time zone are in conflict, this will always use
1796 /// the time zone to interpret the date time.
1797 ///
1798 /// When resolving to an [`AmbiguousZonedDateTime`], the offset attached to
1799 /// the timestamp will always be determined by only looking at the time
1800 /// zone. This in turn implies that the timestamp returned could be
1801 /// ambiguous, since this conflict resolution strategy specifically ignores
1802 /// the offset. (And, we're only at this point because the offset is not
1803 /// possible for the given time zone, so it can't be used in concert with
1804 /// the time zone anyway.) This is unlike the `AlwaysOffset` strategy where
1805 /// the timestamp returned is guaranteed to be unambiguous.
1806 ///
1807 /// You should use this option when you want to keep the civil time
1808 /// unchanged even if it means a change to the exact time.
1809 AlwaysTimeZone,
1810 /// Always attempt to use the offset to resolve a datetime to a timestamp,
1811 /// unless the offset is invalid for the provided time zone. In that case,
1812 /// use the time zone. When the time zone is used, it's possible for an
1813 /// ambiguous datetime to be returned.
1814 ///
1815 /// See
1816 /// [`ZonedDateTimeWith::offset_conflict`](crate::ZonedDateTimeWith::offset_conflict)
1817 /// for an example of when this strategy is useful.
1818 PreferOffset,
1819 /// When the offset and time zone are in conflict, this strategy always
1820 /// results in conflict resolution returning an error.
1821 ///
1822 /// This is the default since a conflict between the offset and the time
1823 /// zone usually implies an invalid datetime in some way.
1824 #[default]
1825 Reject,
1826}
1827
1828impl OffsetConflict {
1829 /// Resolve a potential conflict between an [`Offset`] and a [`TimeZone`].
1830 ///
1831 /// # Errors
1832 ///
1833 /// This returns an error if this would have returned a timestamp outside
1834 /// of its minimum and maximum values.
1835 ///
1836 /// This can also return an error when using the [`OffsetConflict::Reject`]
1837 /// strategy. Namely, when using the `Reject` strategy, any offset that is
1838 /// not compatible with the given datetime and time zone will always result
1839 /// in an error.
1840 ///
1841 /// # Example
1842 ///
1843 /// This example shows how each of the different conflict resolution
1844 /// strategies are applied.
1845 ///
1846 /// ```
1847 /// use jiff::{civil::date, tz};
1848 ///
1849 /// let dt = date(2024, 6, 14).at(17, 30, 0, 0);
1850 /// let offset = tz::offset(-5); // wrong! should be -4
1851 /// let newyork = tz::db().get("America/New_York")?;
1852 ///
1853 /// // Here, we use the offset and ignore the time zone.
1854 /// let zdt = tz::OffsetConflict::AlwaysOffset
1855 /// .resolve(dt, offset, newyork.clone())?
1856 /// .unambiguous()?;
1857 /// // The datetime (and offset) have been corrected automatically
1858 /// // and the resulting ZonedDateTime instant corresponds precisely to
1859 /// // `2024-06-14T17:30-05[UTC]`.
1860 /// assert_eq!(zdt.to_string(), "2024-06-14T18:30:00-04:00[America/New_York]");
1861 ///
1862 /// // Here, we use the time zone and ignore the offset.
1863 /// let zdt = tz::OffsetConflict::AlwaysTimeZone
1864 /// .resolve(dt, offset, newyork.clone())?
1865 /// .unambiguous()?;
1866 /// // The offset has been corrected automatically and the resulting
1867 /// // ZonedDateTime instant corresponds precisely to
1868 /// // `2024-06-14T17:30-04[UTC]`. Notice how the civil time remains the
1869 /// // same, but the exact instant has changed!
1870 /// assert_eq!(zdt.to_string(), "2024-06-14T17:30:00-04:00[America/New_York]");
1871 ///
1872 /// // Here, we prefer the offset, but fall back to the time zone.
1873 /// // In this example, it has the same behavior as `AlwaysTimeZone`.
1874 /// let zdt = tz::OffsetConflict::PreferOffset
1875 /// .resolve(dt, offset, newyork.clone())?
1876 /// .unambiguous()?;
1877 /// assert_eq!(zdt.to_string(), "2024-06-14T17:30:00-04:00[America/New_York]");
1878 ///
1879 /// // The default conflict resolution, 'Reject', will error.
1880 /// let result = tz::OffsetConflict::Reject
1881 /// .resolve(dt, offset, newyork.clone());
1882 /// assert!(result.is_err());
1883 ///
1884 /// # Ok::<(), Box<dyn std::error::Error>>(())
1885 /// ```
1886 pub fn resolve(
1887 self,
1888 dt: civil::DateTime,
1889 offset: Offset,
1890 tz: TimeZone,
1891 ) -> Result<AmbiguousZonedDateTime, Error> {
1892 self.resolve_with(dt, offset, tz, |off1, off2| off1 == off2)
1893 }
1894
1895 /// Resolve a potential conflict between an [`Offset`] and a [`TimeZone`]
1896 /// using the given definition of equality for an `Offset`.
1897 ///
1898 /// The equality predicate is always given a pair of offsets where the
1899 /// first is the offset given to `resolve_with` and the second is the
1900 /// offset found in the `TimeZone`.
1901 ///
1902 /// With [`OffsetConflict::Reject`] or [`OffsetConflict::PreferOffset`],
1903 /// matching the offset to a fold checks the earlier candidate first. The
1904 /// timestamp is computed using the matching candidate's actual offset,
1905 /// which may differ from the offset given to this routine.
1906 ///
1907 /// # Errors
1908 ///
1909 /// This returns an error if this would have returned a timestamp outside
1910 /// of its minimum and maximum values.
1911 ///
1912 /// This can also return an error when using the [`OffsetConflict::Reject`]
1913 /// strategy. Namely, when using the `Reject` strategy, any offset that is
1914 /// not compatible with the given datetime and time zone will always result
1915 /// in an error.
1916 ///
1917 /// # Example
1918 ///
1919 /// Unlike [`OffsetConflict::resolve`], this routine permits overriding
1920 /// the definition of equality used for comparing offsets. In
1921 /// `OffsetConflict::resolve`, exact equality is used. This can be
1922 /// troublesome in some cases when a time zone has an offset with
1923 /// fractional minutes, such as `Africa/Monrovia` before 1972.
1924 ///
1925 /// Because RFC 3339 and RFC 9557 do not support time zone offsets
1926 /// with fractional minutes, Jiff will serialize offsets with
1927 /// fractional minutes by rounding to the nearest minute. This
1928 /// will result in a different offset than what is actually
1929 /// used in the time zone. Parsing this _should_ succeed, but
1930 /// if exact offset equality is used, it won't. This is why a
1931 /// [`fmt::temporal::DateTimeParser`](crate::fmt::temporal::DateTimeParser)
1932 /// uses this routine with offset equality that rounds offsets to the
1933 /// nearest minute before comparison.
1934 ///
1935 /// ```
1936 /// use jiff::{civil::date, tz::{Offset, OffsetConflict, TimeZone}, Unit};
1937 ///
1938 /// let dt = date(1968, 2, 1).at(23, 15, 0, 0);
1939 /// let offset = Offset::from_seconds(-(44 * 60 + 30)).unwrap();
1940 /// let zdt = dt.in_tz("Africa/Monrovia")?;
1941 /// assert_eq!(zdt.offset(), offset);
1942 /// // Notice that the offset has been rounded!
1943 /// assert_eq!(zdt.to_string(), "1968-02-01T23:15:00-00:45[Africa/Monrovia]");
1944 ///
1945 /// // Now imagine parsing extracts the civil datetime, the offset and
1946 /// // the time zone, and then naively does exact offset comparison:
1947 /// let tz = TimeZone::get("Africa/Monrovia")?;
1948 /// // This is the parsed offset, which won't precisely match the actual
1949 /// // offset used by `Africa/Monrovia` at this time.
1950 /// let offset = Offset::from_seconds(-45 * 60).unwrap();
1951 /// let result = OffsetConflict::Reject.resolve(dt, offset, tz.clone());
1952 /// assert_eq!(
1953 /// result.unwrap_err().to_string(),
1954 /// "datetime could not resolve to a timestamp since `reject` \
1955 /// conflict resolution was chosen, and because datetime has offset \
1956 /// `-00:45`, but the time zone `Africa/Monrovia` for the given \
1957 /// datetime unambiguously has offset `-00:44:30`",
1958 /// );
1959 /// let is_equal = |parsed: Offset, candidate: Offset| {
1960 /// parsed == candidate || candidate.round(Unit::Minute).map_or(
1961 /// parsed == candidate,
1962 /// |candidate| parsed == candidate,
1963 /// )
1964 /// };
1965 /// let zdt = OffsetConflict::Reject.resolve_with(
1966 /// dt,
1967 /// offset,
1968 /// tz.clone(),
1969 /// is_equal,
1970 /// )?.unambiguous()?;
1971 /// // Notice that the offset is the actual offset from the time zone:
1972 /// assert_eq!(zdt.offset(), Offset::from_seconds(-(44 * 60 + 30)).unwrap());
1973 /// // But when we serialize, the offset gets rounded. If we didn't
1974 /// // do this, we'd risk the datetime not being parsable by other
1975 /// // implementations since RFC 3339 and RFC 9557 don't support fractional
1976 /// // minutes in the offset.
1977 /// assert_eq!(zdt.to_string(), "1968-02-01T23:15:00-00:45[Africa/Monrovia]");
1978 ///
1979 /// # Ok::<(), Box<dyn std::error::Error>>(())
1980 /// ```
1981 ///
1982 /// And indeed, notice that parsing uses this same kind of offset equality
1983 /// to permit zoned datetimes whose offsets would be equivalent after
1984 /// rounding:
1985 ///
1986 /// ```
1987 /// use jiff::{ZonedDateTime, tz::Offset};
1988 ///
1989 /// let zdt: ZonedDateTime =
1990 /// "1968-02-01T23:15:00-00:45[Africa/Monrovia]".parse()?;
1991 /// // As above, notice that even though we parsed `-00:45` as the
1992 /// // offset, the actual offset of our zoned datetime is the correct
1993 /// // one from the time zone.
1994 /// assert_eq!(zdt.offset(), Offset::from_seconds(-(44 * 60 + 30)).unwrap());
1995 /// // And similarly, re-serializing it results in rounding the offset
1996 /// // again for compatibility with RFC 3339 and RFC 9557.
1997 /// assert_eq!(zdt.to_string(), "1968-02-01T23:15:00-00:45[Africa/Monrovia]");
1998 ///
1999 /// // And we also support parsing the actual fractional minute offset
2000 /// // as well:
2001 /// let zdt: ZonedDateTime =
2002 /// "1968-02-01T23:15:00-00:44:30[Africa/Monrovia]".parse()?;
2003 /// assert_eq!(zdt.offset(), Offset::from_seconds(-(44 * 60 + 30)).unwrap());
2004 /// assert_eq!(zdt.to_string(), "1968-02-01T23:15:00-00:45[Africa/Monrovia]");
2005 ///
2006 /// # Ok::<(), Box<dyn std::error::Error>>(())
2007 /// ```
2008 ///
2009 /// Rounding does not occur when the parsed offset itself contains
2010 /// sub-minute precision. In that case, exact equality is used:
2011 ///
2012 /// ```
2013 /// use jiff::ZonedDateTime;
2014 ///
2015 /// let result =
2016 /// "1970-06-01T00-00:45:00[Africa/Monrovia]".parse::<ZonedDateTime>();
2017 /// assert_eq!(
2018 /// result.unwrap_err().to_string(),
2019 /// "datetime could not resolve to a timestamp since `reject` \
2020 /// conflict resolution was chosen, and because datetime has offset \
2021 /// `-00:45`, but the time zone `Africa/Monrovia` for the given \
2022 /// datetime unambiguously has offset `-00:44:30`",
2023 /// );
2024 /// ```
2025 pub fn resolve_with<F>(
2026 self,
2027 dt: civil::DateTime,
2028 offset: Offset,
2029 tz: TimeZone,
2030 is_equal: F,
2031 ) -> Result<AmbiguousZonedDateTime, Error>
2032 where
2033 F: FnMut(Offset, Offset) -> bool,
2034 {
2035 match self {
2036 // In this case, we ignore any TZ annotation (although still
2037 // require that it exists) and always use the provided offset.
2038 OffsetConflict::AlwaysOffset => {
2039 let kind = AmbiguousOffset::Unambiguous { offset };
2040 Ok(AmbiguousTimestamp::new(dt, kind)
2041 .into_ambiguous_zoned_datetime(tz))
2042 }
2043 // In this case, we ignore any provided offset and always use the
2044 // time zone annotation.
2045 OffsetConflict::AlwaysTimeZone => {
2046 Ok(tz.into_ambiguous_zoned_datetime(dt))
2047 }
2048 // In this case, we use the offset if it's correct, but otherwise
2049 // fall back to the time zone annotation if it's not.
2050 OffsetConflict::PreferOffset => Ok(
2051 OffsetConflict::resolve_via_prefer(dt, offset, tz, is_equal),
2052 ),
2053 // In this case, if the offset isn't possible for the provided time
2054 // zone annotation, then we return an error.
2055 OffsetConflict::Reject => {
2056 OffsetConflict::resolve_via_reject(dt, offset, tz, is_equal)
2057 }
2058 }
2059 }
2060
2061 /// Given a parsed datetime, a parsed offset and a parsed time zone, this
2062 /// attempts to resolve the datetime to a particular instant based on the
2063 /// 'prefer' strategy.
2064 ///
2065 /// In a fold, we check the earlier candidate first using `is_equal`. The
2066 /// first match resolves the fold using the candidate's actual offset,
2067 /// which may differ from the parsed offset.
2068 ///
2069 /// If neither candidate matches, or if the datetime falls in a gap, then
2070 /// the parsed offset is ignored and disambiguation is left to the caller.
2071 fn resolve_via_prefer(
2072 dt: civil::DateTime,
2073 given: Offset,
2074 tz: TimeZone,
2075 mut is_equal: impl FnMut(Offset, Offset) -> bool,
2076 ) -> AmbiguousZonedDateTime {
2077 use crate::tz::AmbiguousOffset::*;
2078
2079 let amb = tz.to_ambiguous_timestamp(dt);
2080 match amb.offset() {
2081 // Only folds can be resolved by matching an offset. Gaps are left
2082 // for the caller to disambiguate because all offsets are invalid.
2083 Fold { before, after } => {
2084 let offset = if is_equal(given, before) {
2085 before
2086 } else if is_equal(given, after) {
2087 after
2088 } else {
2089 return amb.into_ambiguous_zoned_datetime(tz);
2090 };
2091 let kind = Unambiguous { offset };
2092 AmbiguousTimestamp::new(dt, kind)
2093 }
2094 _ => amb,
2095 }
2096 .into_ambiguous_zoned_datetime(tz)
2097 }
2098
2099 /// Given a parsed datetime, a parsed offset and a parsed time zone, this
2100 /// attempts to resolve the datetime to a particular instant based on the
2101 /// 'reject' strategy.
2102 ///
2103 /// That is, if the offset is not possibly valid for the given datetime and
2104 /// time zone, then this returns an error.
2105 ///
2106 /// This guarantees that on success, an unambiguous timestamp is returned.
2107 /// This occurs because if the datetime is ambiguous for the given time
2108 /// zone, then the parsed offset either matches one of the possible offsets
2109 /// (and thus provides an unambiguous choice), or it doesn't and an error
2110 /// is returned.
2111 fn resolve_via_reject(
2112 dt: civil::DateTime,
2113 given: Offset,
2114 tz: TimeZone,
2115 mut is_equal: impl FnMut(Offset, Offset) -> bool,
2116 ) -> Result<AmbiguousZonedDateTime, Error> {
2117 use crate::tz::AmbiguousOffset::*;
2118
2119 let amb = tz.to_ambiguous_timestamp(dt);
2120 match amb.offset() {
2121 Unambiguous { offset } if !is_equal(given, offset) => {
2122 Err(Error::from(E::ResolveRejectUnambiguous {
2123 given,
2124 offset,
2125 tz,
2126 }))
2127 }
2128 Unambiguous { .. } => Ok(amb.into_ambiguous_zoned_datetime(tz)),
2129 Gap { before, after } => {
2130 // In `jiff 0.1`, we reported an error when we found a gap
2131 // where neither offset matched what was given. But now we
2132 // report an error whenever we find a gap, as we consider
2133 // all offsets to be invalid for the gap. This now matches
2134 // Temporal's behavior which I think is more consistent. And in
2135 // particular, this makes it more consistent with the behavior
2136 // of `PreferOffset` when a gap is found (which was also
2137 // changed to treat all offsets in a gap as invalid).
2138 //
2139 // Ref: https://github.com/tc39/proposal-temporal/issues/2892
2140 Err(Error::from(E::ResolveRejectGap {
2141 given,
2142 before,
2143 after,
2144 tz,
2145 }))
2146 }
2147 Fold { before, after } => {
2148 let offset = if is_equal(given, before) {
2149 before
2150 } else if is_equal(given, after) {
2151 after
2152 } else {
2153 return Err(Error::from(E::ResolveRejectFold {
2154 given,
2155 before,
2156 after,
2157 tz,
2158 }));
2159 };
2160 let kind = Unambiguous { offset };
2161 Ok(AmbiguousTimestamp::new(dt, kind)
2162 .into_ambiguous_zoned_datetime(tz))
2163 }
2164 }
2165 }
2166}