Skip to main content

jiff/tz/
timezone.rs

1use jcore::tz::{posix, tzif};
2
3use crate::{
4    Timestamp, ZonedDateTime,
5    civil::DateTime,
6    error::{Error, tz::timezone::Error as E},
7    tz::{
8        ambiguous::{
9            AmbiguousOffset, AmbiguousTimestamp, AmbiguousZonedDateTime,
10        },
11        db::{TimeZoneLocation, find_primary_iana_name, find_tz_location},
12        offset::{Dst, Offset},
13    },
14    util::sync::Arc,
15};
16
17use self::repr::Repr;
18
19/// A representation of a [time zone].
20///
21/// A time zone is a set of rules for determining the civil time, via an offset
22/// from UTC, in a particular geographic region. In many cases, the offset
23/// in a particular time zone can vary over the course of a year through
24/// transitions into and out of [daylight saving time].
25///
26/// A `TimeZone` can be one of three possible representations:
27///
28/// * An identifier from the [IANA Time Zone Database] and the rules associated
29/// with that identifier.
30/// * A fixed offset where there are never any time zone transitions.
31/// * A [POSIX TZ] string that specifies a standard offset and an optional
32/// daylight saving time offset along with a rule for when DST is in effect.
33/// The rule applies for every year. Since POSIX TZ strings cannot capture the
34/// full complexity of time zone rules, they generally should not be used.
35///
36/// The most practical and useful representation is an IANA time zone. Namely,
37/// it enjoys broad support and its database is regularly updated to reflect
38/// real changes in time zone rules throughout the world. On Unix systems,
39/// the time zone database is typically found at `/usr/share/zoneinfo`. For
40/// more information on how Jiff interacts with The Time Zone Database, see
41/// [`TimeZoneDatabase`](crate::tz::TimeZoneDatabase).
42///
43/// In typical usage, users of Jiff shouldn't need to reference a `TimeZone`
44/// directly. Instead, there are convenience APIs on datetime types that accept
45/// IANA time zone identifiers and do automatic database lookups for you. For
46/// example, to convert a timestamp to a zone aware datetime:
47///
48/// ```
49/// use jiff::Timestamp;
50///
51/// let ts = Timestamp::from_second(1_456_789_123)?;
52/// let zdt = ts.in_tz("America/New_York")?;
53/// assert_eq!(zdt.to_string(), "2016-02-29T18:38:43-05:00[America/New_York]");
54///
55/// # Ok::<(), Box<dyn std::error::Error>>(())
56/// ```
57///
58/// Or to convert a civil datetime to a zoned datetime corresponding to a
59/// precise instant in time:
60///
61/// ```
62/// use jiff::civil::date;
63///
64/// let dt = date(2024, 7, 15).at(21, 27, 0, 0);
65/// let zdt = dt.in_tz("America/New_York")?;
66/// assert_eq!(zdt.to_string(), "2024-07-15T21:27:00-04:00[America/New_York]");
67///
68/// # Ok::<(), Box<dyn std::error::Error>>(())
69/// ```
70///
71/// Or even converted a zoned datetime from one time zone to another:
72///
73/// ```
74/// use jiff::civil::date;
75///
76/// let dt = date(2024, 7, 15).at(21, 27, 0, 0);
77/// let zdt1 = dt.in_tz("America/New_York")?;
78/// let zdt2 = zdt1.in_tz("Asia/Jerusalem")?;
79/// assert_eq!(zdt2.to_string(), "2024-07-16T04:27:00+03:00[Asia/Jerusalem]");
80///
81/// # Ok::<(), Box<dyn std::error::Error>>(())
82/// ```
83///
84/// # The system time zone
85///
86/// The system time zone can be retrieved via [`TimeZone::system`]. If it
87/// couldn't be detected or if the `tz-system` crate feature is not enabled,
88/// then [`TimeZone::unknown`] is returned. `TimeZone::system` is what's used
89/// internally for retrieving the current zoned datetime via
90/// [`ZonedDateTime::now`].
91///
92/// While there is no platform independent way to detect your system's
93/// "default" time zone, Jiff employs best-effort heuristics to determine it.
94/// (For example, by examining `/etc/localtime` on Unix systems or the `TZ`
95/// environment variable.) When the heuristics fail, Jiff will emit a `WARN`
96/// level log. It can be viewed by installing a `log` compatible logger, such
97/// as [`env_logger`].
98///
99/// # Custom time zones
100///
101/// At present, Jiff doesn't provide any APIs for manually constructing a
102/// custom time zone. However, [`TimeZone::tzif`] is provided for reading
103/// any valid TZif formatted data, as specified by [RFC 8536]. This provides
104/// an interoperable way of utilizing custom time zone rules.
105///
106/// # A `TimeZone` is immutable
107///
108/// Once a `TimeZone` is created, it is immutable. That is, its underlying
109/// time zone transition rules will never change. This is true for system time
110/// zones or even if the IANA Time Zone Database it was loaded from changes on
111/// disk. The only way such changes can be observed is by re-requesting the
112/// `TimeZone` from a `TimeZoneDatabase`. (Or, in the case of the system time
113/// zone, by calling `TimeZone::system`.)
114///
115/// # A `TimeZone` is cheap to clone
116///
117/// A `TimeZone` can be cheaply cloned. It uses automatic reference counting
118/// internally. When `alloc` is disabled, cloning a `TimeZone` is still cheap
119/// because POSIX time zones and TZif time zones are unsupported. Therefore,
120/// cloning a time zone does a deep copy (since automatic reference counting is
121/// not available), but the data being copied is small.
122///
123/// # Time zone equality
124///
125/// `TimeZone` provides an imperfect notion of equality. That is, when two time
126/// zones are equal, then it is guaranteed for them to have the same rules.
127/// However, two time zones may compare unequal and yet still have the same
128/// rules.
129///
130/// The equality semantics are as follows:
131///
132/// * Two fixed offset time zones are equal when their offsets are equal.
133/// * Two POSIX time zones are equal when their rule strings parse to identical
134/// rules in memory.
135/// * Two IANA time zones are equal when their primary identifiers are equal
136/// and their underlying checksums of the TZif data are equivalent. If a
137/// primary identifier is unavailable, then the time zone's IANA identifier
138/// is used instead.
139/// * Two TZif time zones whose `iana_name()` is `None` are equivalent only
140/// when their underlying checksums of the TZif data are equivalent. * In all
141/// other cases, time zones are unequal.
142///
143/// Time zone equality is, for example, used in APIs like
144/// [`ZonedDateTime::since`] when asking for spans with calendar units. Namely,
145/// since days can be of different lengths in different time zones,
146/// `ZonedDateTime::since` will return an error when the two zoned datetimes
147/// are in different time zones and when the caller requests units greater than
148/// hours.
149///
150/// # Dealing with ambiguity
151///
152/// The principal job of a `TimeZone` is to provide two different
153/// transformations:
154///
155/// * A conversion from a [`Timestamp`] to a civil time (also known as local,
156/// naive or plain time). This conversion is always unambiguous. That is,
157/// there is always precisely one representation of civil time for any
158/// particular instant in time for a particular time zone.
159/// * A conversion from a [`civil::DateTime`](crate::civil::DateTime) to an
160/// instant in time. This conversion is sometimes ambiguous in that a civil
161/// time might have either never appear on the clocks in a particular
162/// time zone (a gap), or in that the civil time may have been repeated on the
163/// clocks in a particular time zone (a fold). Typically, a transition to
164/// daylight saving time is a gap, while a transition out of daylight saving
165/// time is a fold.
166///
167/// The timestamp-to-civil time conversion is done via
168/// [`TimeZone::to_datetime`], or its lower level counterpart,
169/// [`TimeZone::to_offset`]. The civil time-to-timestamp conversion is done
170/// via one of the following routines:
171///
172/// * [`TimeZone::to_zoned_datetime`] conveniently returns a [`ZonedDateTime`]
173/// and automatically uses the
174/// [`Disambiguation::Compatible`](crate::tz::Disambiguation::Compatible)
175/// strategy if the given civil datetime is ambiguous in the time zone.
176/// * [`TimeZone::to_ambiguous_zoned_datetime`] returns a potentially
177/// ambiguous zoned datetime, [`AmbiguousZonedDateTime`], and provides
178/// fine-grained control over how to resolve ambiguity, if it occurs.
179/// * [`TimeZone::to_timestamp`] is like `TimeZone::to_zoned_datetime`, but
180/// returns a [`Timestamp`] instead.
181/// * [`TimeZone::to_ambiguous_timestamp`] is like
182/// `TimeZone::to_ambiguous_zoned_datetime`, but returns an
183/// [`AmbiguousTimestamp`] instead.
184///
185/// Here is an example where we explore the different disambiguation strategies
186/// for a fold in time, where in this case, the 1 o'clock hour is repeated:
187///
188/// ```
189/// use jiff::{civil::date, tz::TimeZone};
190///
191/// let tz = TimeZone::get("America/New_York")?;
192/// let dt = date(2024, 11, 3).at(1, 30, 0, 0);
193/// // It's ambiguous, so asking for an unambiguous instant presents an error!
194/// assert!(tz.to_ambiguous_zoned_datetime(dt).unambiguous().is_err());
195/// // Gives you the earlier time in a fold, i.e., before DST ends:
196/// assert_eq!(
197///     tz.to_ambiguous_zoned_datetime(dt).earlier()?.to_string(),
198///     "2024-11-03T01:30:00-04:00[America/New_York]",
199/// );
200/// // Gives you the later time in a fold, i.e., after DST ends.
201/// // Notice the offset change from the previous example!
202/// assert_eq!(
203///     tz.to_ambiguous_zoned_datetime(dt).later()?.to_string(),
204///     "2024-11-03T01:30:00-05:00[America/New_York]",
205/// );
206/// // "Just give me something reasonable"
207/// assert_eq!(
208///     tz.to_ambiguous_zoned_datetime(dt).compatible()?.to_string(),
209///     "2024-11-03T01:30:00-04:00[America/New_York]",
210/// );
211///
212/// # Ok::<(), Box<dyn std::error::Error>>(())
213/// ```
214///
215/// # Serde integration
216///
217/// At present, a `TimeZone` does not implement Serde's `Serialize` or
218/// `Deserialize` traits directly. Nor does it implement `std::fmt::Display`
219/// or `std::str::FromStr`. The reason for this is that it's not totally
220/// clear if there is one single obvious behavior. Moreover, some `TimeZone`
221/// values do not have an obvious succinct serialized representation. (For
222/// example, when `/etc/localtime` on a Unix system is your system's time zone,
223/// and it isn't a symlink to a TZif file in `/usr/share/zoneinfo`. In which
224/// case, an IANA time zone identifier cannot easily be deduced by Jiff.)
225///
226/// Instead, Jiff offers helpers for use with Serde's [`with` attribute] via
227/// the [`fmt::serde`](crate::fmt::serde) module:
228///
229/// ```
230/// use jiff::tz::TimeZone;
231///
232/// #[derive(Debug, serde::Deserialize, serde::Serialize)]
233/// struct Record {
234///     #[serde(with = "jiff::fmt::serde::tz::optional")]
235///     tz: Option<TimeZone>,
236/// }
237///
238/// let json = r#"{"tz":"America/Nuuk"}"#;
239/// let got: Record = serde_json::from_str(&json)?;
240/// assert_eq!(got.tz, Some(TimeZone::get("America/Nuuk")?));
241/// assert_eq!(serde_json::to_string(&got)?, json);
242///
243/// # Ok::<(), Box<dyn std::error::Error>>(())
244/// ```
245///
246/// Alternatively, you may use the
247/// [`fmt::temporal::DateTimeParser::parse_time_zone`](crate::fmt::temporal::DateTimeParser::parse_time_zone)
248/// or
249/// [`fmt::temporal::DateTimePrinter::print_time_zone`](crate::fmt::temporal::DateTimePrinter::print_time_zone)
250/// routines to parse or print `TimeZone` values without using Serde.
251///
252/// [time zone]: https://en.wikipedia.org/wiki/Time_zone
253/// [daylight saving time]: https://en.wikipedia.org/wiki/Daylight_saving_time
254/// [IANA Time Zone Database]: https://en.wikipedia.org/wiki/Tz_database
255/// [POSIX TZ]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
256/// [`env_logger`]: https://docs.rs/env_logger
257/// [RFC 8536]: https://datatracker.ietf.org/doc/html/rfc8536
258/// [`with` attribute]: https://serde.rs/field-attrs.html#with
259#[derive(#[automatically_derived]impl ::core::clone::Clone for TimeZone {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        TimeZone { repr: ::core::clone::Clone::clone(&self.repr) }
    }
}Clone, #[automatically_derived]impl ::core::cmp::Eq for TimeZone {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Repr>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for TimeZone
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for TimeZone {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.repr == other.repr }
}PartialEq)]
260pub struct TimeZone {
261    repr: Repr,
262}
263
264impl TimeZone {
265    /// The UTC time zone.
266    ///
267    /// The offset of this time is `0` and never has any transitions.
268    pub const UTC: TimeZone = TimeZone { repr: Repr::utc() };
269
270    /// Returns the system configured time zone, if available.
271    ///
272    /// Detection of a system's default time zone is generally heuristic
273    /// based and platform specific.
274    ///
275    /// If callers need to know whether discovery of the system time zone
276    /// failed, then use [`TimeZone::try_system`].
277    ///
278    /// # Fallback behavior
279    ///
280    /// If the system's default time zone could not be determined, or if
281    /// the `tz-system` crate feature is not enabled, then this returns
282    /// [`TimeZone::unknown`]. A `WARN` level log will also be emitted with
283    /// a message explaining why time zone detection failed. The fallback to
284    /// an unknown time zone is a practical trade-off, is what most other
285    /// systems tend to do and is also recommended by [relevant standards such
286    /// as freedesktop.org][freedesktop-org-localtime].
287    ///
288    /// An unknown time zone _behaves_ like [`TimeZone::UTC`], but will
289    /// print as `Etc/Unknown` when converting a `ZonedDateTime` to a string.
290    ///
291    /// If you would like to fall back to UTC instead of
292    /// the special "unknown" time zone, then you can do
293    /// `TimeZone::try_system().unwrap_or(TimeZone::UTC)`.
294    ///
295    /// # Platform behavior
296    ///
297    /// This section is a "best effort" explanation of how the time zone is
298    /// detected on supported platforms. The behavior is subject to change.
299    ///
300    /// On all platforms, the `TZ` environment variable overrides any other
301    /// heuristic, and provides a way for end users to set the time zone for
302    /// specific use cases. In general, Jiff respects the [POSIX TZ] rules.
303    /// Here are some examples:
304    ///
305    /// * `TZ=America/New_York` for setting a time zone via an IANA Time Zone
306    /// Database Identifier.
307    /// * `TZ=/usr/share/zoneinfo/America/New_York` for setting a time zone
308    /// by providing a file path to a TZif file directly.
309    /// * `TZ=EST5EDT,M3.2.0,M11.1.0` for setting a time zone via a daylight
310    /// saving time transition rule.
311    ///
312    /// When `TZ` is set to an invalid value, Jiff uses the fallback behavior
313    /// described above.
314    ///
315    /// Otherwise, when `TZ` isn't set, then:
316    ///
317    /// On Unix non-Android systems, this inspects `/etc/localtime`. If it's
318    /// a symbolic link to an entry in `/usr/share/zoneinfo`, then the suffix
319    /// is considered an IANA Time Zone Database identifier. Otherwise,
320    /// `/etc/localtime` is read as a TZif file directly.
321    ///
322    /// On Android systems, this inspects the `persist.sys.timezone` property.
323    ///
324    /// On Windows, the system time zone is determined via
325    /// [`GetDynamicTimeZoneInformation`]. The result is then mapped to an
326    /// IANA Time Zone Database identifier via Unicode's
327    /// [CLDR XML data].
328    ///
329    /// [freedesktop-org-localtime]: https://www.freedesktop.org/software/systemd/man/latest/localtime.html
330    /// [POSIX TZ]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
331    /// [`GetDynamicTimeZoneInformation`]: https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-getdynamictimezoneinformation
332    /// [CLDR XML data]: https://github.com/unicode-org/cldr/raw/main/common/supplemental/windowsZones.xml
333    #[inline]
334    pub fn system() -> TimeZone {
335        match TimeZone::try_system() {
336            Ok(tz) => tz,
337            Err(_err) => {
338                warn!(
339                    "failed to get system time zone, \
340                     falling back to `Etc/Unknown` \
341                     (which behaves like UTC): {_err}",
342                );
343                TimeZone::unknown()
344            }
345        }
346    }
347
348    /// Returns the system configured time zone, if available.
349    ///
350    /// If the system's default time zone could not be determined, or if the
351    /// `tz-system` crate feature is not enabled, then this returns an error.
352    ///
353    /// Detection of a system's default time zone is generally heuristic
354    /// based and platform specific.
355    ///
356    /// Note that callers should generally prefer using [`TimeZone::system`].
357    /// If a system time zone could not be found, then it falls
358    /// back to [`TimeZone::UTC`] automatically. This is often
359    /// what is recommended by [relevant standards such as
360    /// freedesktop.org][freedesktop-org-localtime]. Conversely, this routine
361    /// is useful if detection of a system's default time zone is critical.
362    ///
363    /// # Platform behavior
364    ///
365    /// This section is a "best effort" explanation of how the time zone is
366    /// detected on supported platforms. The behavior is subject to change.
367    ///
368    /// On all platforms, the `TZ` environment variable overrides any other
369    /// heuristic, and provides a way for end users to set the time zone for
370    /// specific use cases. In general, Jiff respects the [POSIX TZ] rules.
371    /// Here are some examples:
372    ///
373    /// * `TZ=America/New_York` for setting a time zone via an IANA Time Zone
374    /// Database Identifier.
375    /// * `TZ=/usr/share/zoneinfo/America/New_York` for setting a time zone
376    /// by providing a file path to a TZif file directly.
377    /// * `TZ=EST5EDT,M3.2.0,M11.1.0` for setting a time zone via a daylight
378    /// saving time transition rule.
379    ///
380    /// When `TZ` is set to an invalid value, then this routine returns an
381    /// error.
382    ///
383    /// Otherwise, when `TZ` isn't set, then:
384    ///
385    /// On Unix systems, this inspects `/etc/localtime`. If it's a symbolic
386    /// link to an entry in `/usr/share/zoneinfo`, then the suffix is
387    /// considered an IANA Time Zone Database identifier. Otherwise,
388    /// `/etc/localtime` is read as a TZif file directly.
389    ///
390    /// On Windows, the system time zone is determined via
391    /// [`GetDynamicTimeZoneInformation`]. The result is then mapped to an
392    /// IANA Time Zone Database identifier via Unicode's
393    /// [CLDR XML data].
394    ///
395    /// [freedesktop-org-localtime]: https://www.freedesktop.org/software/systemd/man/latest/localtime.html
396    /// [POSIX TZ]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
397    /// [`GetDynamicTimeZoneInformation`]: https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-getdynamictimezoneinformation
398    /// [CLDR XML data]: https://github.com/unicode-org/cldr/raw/main/common/supplemental/windowsZones.xml
399    #[inline]
400    pub fn try_system() -> Result<TimeZone, Error> {
401        #[cfg(not(feature = "tz-system"))]
402        {
403            Err(Error::from(crate::error::CrateFeatureError::TzSystem)
404                .context(E::FailedSystem))
405        }
406        #[cfg(feature = "tz-system")]
407        {
408            crate::tz::system::get(crate::tz::db())
409        }
410    }
411
412    /// A convenience function for performing a time zone database lookup for
413    /// the given time zone identifier. It uses the default global time zone
414    /// database via [`tz::db()`](crate::tz::db()).
415    ///
416    /// It is guaranteed that if the given time zone name is case insensitively
417    /// equivalent to `UTC`, then the time zone returned will be equivalent to
418    /// `TimeZone::UTC`. Similarly for `Etc/Unknown` and `TimeZone::unknown()`.
419    ///
420    /// # Errors
421    ///
422    /// This returns an error if the given time zone identifier could not be
423    /// found in the default [`TimeZoneDatabase`](crate::tz::TimeZoneDatabase).
424    ///
425    /// # Example
426    ///
427    /// ```
428    /// use jiff::{tz::TimeZone, Timestamp};
429    ///
430    /// let tz = TimeZone::get("Asia/Tokyo")?;
431    /// assert_eq!(
432    ///     tz.to_datetime(Timestamp::UNIX_EPOCH).to_string(),
433    ///     "1970-01-01T09:00:00",
434    /// );
435    ///
436    /// # Ok::<(), Box<dyn std::error::Error>>(())
437    /// ```
438    #[inline]
439    pub fn get(time_zone_name: &str) -> Result<TimeZone, Error> {
440        crate::tz::db().get(time_zone_name)
441    }
442
443    /// Returns a time zone with a fixed offset.
444    ///
445    /// A fixed offset will never have any transitions and won't follow any
446    /// particular time zone rules. In general, one should avoid using fixed
447    /// offset time zones unless you have a specific need for them. Otherwise,
448    /// IANA time zones via [`TimeZone::get`] should be preferred, as they
449    /// more accurately model the actual time zone transitions rules used in
450    /// practice.
451    ///
452    /// # Example
453    ///
454    /// ```
455    /// use jiff::{tz::{self, TimeZone}, Timestamp};
456    ///
457    /// let tz = TimeZone::fixed(tz::offset(10));
458    /// assert_eq!(
459    ///     tz.to_datetime(Timestamp::UNIX_EPOCH).to_string(),
460    ///     "1970-01-01T10:00:00",
461    /// );
462    ///
463    /// # Ok::<(), Box<dyn std::error::Error>>(())
464    /// ```
465    #[inline]
466    pub const fn fixed(offset: Offset) -> TimeZone {
467        // Not doing `offset == Offset::UTC` because of `const`.
468        if offset.seconds() == 0 {
469            return TimeZone::UTC;
470        }
471        let repr = Repr::fixed(offset);
472        TimeZone { repr }
473    }
474
475    /// Creates a time zone from a [POSIX TZ] rule string.
476    ///
477    /// A POSIX time zone provides a way to tersely define a single daylight
478    /// saving time transition rule (or none at all) that applies for all
479    /// years.
480    ///
481    /// Users should avoid using this kind of time zone unless there is a
482    /// specific need for it. Namely, POSIX time zones cannot capture the full
483    /// complexity of time zone transition rules in the real world. (See the
484    /// example below.)
485    ///
486    /// [POSIX TZ]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
487    ///
488    /// # Errors
489    ///
490    /// This returns an error if the given POSIX time zone string is invalid.
491    ///
492    /// # Example
493    ///
494    /// This example demonstrates how a POSIX time zone may be historically
495    /// inaccurate:
496    ///
497    /// ```
498    /// use jiff::{civil::date, tz::TimeZone};
499    ///
500    /// // The tzdb entry for America/New_York.
501    /// let iana = TimeZone::get("America/New_York")?;
502    /// // The POSIX TZ string for New York DST that went into effect in 2007.
503    /// let posix = TimeZone::posix("EST5EDT,M3.2.0,M11.1.0")?;
504    ///
505    /// // New York entered DST on April 2, 2006 at 2am:
506    /// let dt = date(2006, 4, 2).at(2, 0, 0, 0);
507    /// // The IANA tzdb entry correctly reports it as ambiguous:
508    /// assert!(iana.to_ambiguous_timestamp(dt).is_ambiguous());
509    /// // But the POSIX time zone does not:
510    /// assert!(!posix.to_ambiguous_timestamp(dt).is_ambiguous());
511    ///
512    /// # Ok::<(), Box<dyn std::error::Error>>(())
513    /// ```
514    #[cfg(feature = "alloc")]
515    pub fn posix(posix_tz_string: &str) -> Result<TimeZone, Error> {
516        let posix_tz = posix::TimeZone::parse(posix_tz_string)
517            .map_err(Error::jcore_posix_parse)?;
518        Ok(TimeZone::from_posix_tz(posix_tz))
519    }
520
521    /// Creates a time zone from a POSIX tz. Expose so that other parts of Jiff
522    /// can create a `TimeZone` from a POSIX tz. (Kinda sloppy to be honest.)
523    #[cfg(feature = "alloc")]
524    pub(crate) fn from_posix_tz(posix: posix::TimeZone) -> TimeZone {
525        let repr = Repr::arc_posix(Arc::new(posix));
526        TimeZone { repr }
527    }
528
529    /// Creates a time zone from TZif binary data, whose format is specified
530    /// in [RFC 8536]. All versions of TZif (up through version 4) are
531    /// supported.
532    ///
533    /// This constructor is typically not used, and instead, one should rely
534    /// on time zone lookups via time zone identifiers with routines like
535    /// [`TimeZone::get`]. However, this constructor does provide one way
536    /// of using custom time zones with Jiff.
537    ///
538    /// The name given should be a IANA time zone database identifier.
539    ///
540    /// [RFC 8536]: https://datatracker.ietf.org/doc/html/rfc8536
541    ///
542    /// # Errors
543    ///
544    /// This returns an error if the given data was not recognized as valid
545    /// TZif.
546    #[cfg(feature = "alloc")]
547    pub fn tzif(name: &str, data: &[u8]) -> Result<TimeZone, Error> {
548        let name = jcore::tz::TimeZoneId::new_or_heap(name);
549        let tzif = tzif::TimeZone::parse(data)
550            .map_err(Error::jcore_tzif_parse)?
551            .into_named(name);
552        let repr = Repr::arc_tzif(Arc::new(tzif));
553        Ok(TimeZone { repr })
554    }
555
556    /// Returns a `TimeZone` that is specifically marked as "unknown."
557    ///
558    /// This corresponds to the Unicode CLDR identifier `Etc/Unknown`, which
559    /// is guaranteed to never be a valid IANA time zone identifier (as of
560    /// the `2025a` release of tzdb).
561    ///
562    /// This type of `TimeZone` is used in circumstances where one wants to
563    /// signal that discovering a time zone failed for some reason, but that
564    /// execution can reasonably continue. For example, [`TimeZone::system`]
565    /// returns this type of time zone when the system time zone could not be
566    /// discovered.
567    ///
568    /// # Example
569    ///
570    /// Jiff permits an "unknown" time zone to losslessly be transmitted
571    /// through serialization:
572    ///
573    /// ```
574    /// use jiff::{civil::date, tz::TimeZone, ZonedDateTime};
575    ///
576    /// let tz = TimeZone::unknown();
577    /// let zdt = date(2025, 2, 1).at(17, 0, 0, 0).to_zoned_datetime(tz)?;
578    /// assert_eq!(zdt.to_string(), "2025-02-01T17:00:00Z[Etc/Unknown]");
579    /// let got: ZonedDateTime = "2025-02-01T17:00:00Z[Etc/Unknown]".parse()?;
580    /// assert_eq!(got, zdt);
581    ///
582    /// # Ok::<(), Box<dyn std::error::Error>>(())
583    /// ```
584    ///
585    /// Note that not all systems support this. Some systems will reject
586    /// `Etc/Unknown` because it is not a valid IANA time zone identifier and
587    /// does not have an entry in the IANA time zone database. However, Jiff
588    /// takes this approach because it surfaces an error condition in detecting
589    /// the end user's time zone. Callers not wanting an "unknown" time zone
590    /// can use `TimeZone::try_system().unwrap_or(TimeZone::UTC)` instead of
591    /// `TimeZone::system`. (Where the latter falls back to the "unknown" time
592    /// zone when a system configured time zone could not be found.)
593    pub const fn unknown() -> TimeZone {
594        let repr = Repr::unknown();
595        TimeZone { repr }
596    }
597
598    /// This creates an unnamed TZif-backed `TimeZone`.
599    ///
600    /// At present, the only way for an unnamed TZif-backed `TimeZone` to be
601    /// created is when the system time zone has no identifiable name. For
602    /// example, when `/etc/localtime` is hard-linked to a TZif file instead
603    /// of being symlinked. In this case, there is no cheap and unambiguous
604    /// way to determine the time zone name. So we just let it be unnamed.
605    /// Since this is the only such case, and hopefully will only ever be the
606    /// only such case, we consider such unnamed TZif-back `TimeZone` values
607    /// as being the "system" time zone.
608    ///
609    /// When this is used to construct a `TimeZone`, the `TimeZone::name`
610    /// method will be "Local". This is... pretty unfortunate. I'm not sure
611    /// what else to do other than to make `TimeZone::name` return an
612    /// `Option<&str>`. But... we use it in a bunch of places and it just
613    /// seems bad for a time zone to not have a name.
614    ///
615    /// OK, because of the above, I renamed `TimeZone::name` to
616    /// `TimeZone::diagnostic_name`. This should make it clearer that you can't
617    /// really use the name to do anything interesting. This also makes more
618    /// sense for POSIX TZ strings too.
619    ///
620    /// In any case, this routine stays unexported because I don't want TZif
621    /// backed `TimeZone` values to proliferate. If you have a legitimate use
622    /// case otherwise, please file an issue. It will require API design.
623    ///
624    /// # Errors
625    ///
626    /// This returns an error if the given TZif data is invalid.
627    #[cfg(feature = "tz-system")]
628    pub(crate) fn tzif_system(data: &[u8]) -> Result<TimeZone, Error> {
629        let tzif = tzif::TimeZone::parse(data)
630            .map_err(Error::jcore_tzif_parse)?
631            .into_maybe_named(None);
632        let repr = Repr::arc_tzif(Arc::new(tzif));
633        Ok(TimeZone { repr })
634    }
635
636    #[inline]
637    pub(crate) fn diagnostic_name(&self) -> DiagnosticName<'_> {
638        DiagnosticName(self)
639    }
640
641    /// Returns true if and only if this `TimeZone` can be succinctly
642    /// serialized.
643    ///
644    /// Basically, this is only `false` when this `TimeZone` was created from
645    /// a `/etc/localtime` for which a valid IANA time zone identifier could
646    /// not be extracted.
647    #[cfg(feature = "serde")]
648    #[inline]
649    pub(crate) fn has_succinct_serialization(&self) -> bool {
650        repr::each! {
651            &self.repr,
652            UTC => true,
653            UNKNOWN => true,
654            FIXED(_offset) => true,
655            STATIC_TZIF(tzif) => tzif.name().is_some(),
656            ARC_TZIF(tzif) => tzif.name().is_some(),
657            ARC_POSIX(_posix) => true,
658        }
659    }
660
661    /// When this time zone was loaded from an IANA time zone database entry,
662    /// then this returns the canonicalized name for that time zone.
663    ///
664    /// # Example
665    ///
666    /// ```
667    /// use jiff::tz::TimeZone;
668    ///
669    /// let tz = TimeZone::get("america/NEW_YORK")?;
670    /// assert_eq!(tz.iana_name(), Some("America/New_York"));
671    ///
672    /// # Ok::<(), Box<dyn std::error::Error>>(())
673    /// ```
674    #[inline]
675    pub fn iana_name(&self) -> Option<&str> {
676        {
    let repr = &self.repr;
    match repr.tag() {
        Repr::UTC => Some("UTC"),
        Repr::UNKNOWN => None,
        Repr::FIXED => { let _offset = unsafe { repr.get_fixed() }; None }
        Repr::STATIC_TZIF => {
            let tzif = unsafe { repr.get_static_tzif() };
            tzif.name()
        }Repr::ARC_TZIF => {
            let tzif = unsafe { repr.get_arc_tzif() };
            tzif.name()
        }Repr::ARC_POSIX => {
            let _posix = unsafe { repr.get_arc_posix() };
            None
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}repr::each! {
677            &self.repr,
678            UTC => Some("UTC"),
679            // Note that while `Etc/Unknown` looks like an IANA time zone
680            // identifier, it is specifically and explicitly NOT an IANA time
681            // zone identifier. So we do not return it here if we have an
682            // unknown time zone identifier.
683            UNKNOWN => None,
684            FIXED(_offset) => None,
685            STATIC_TZIF(tzif) => tzif.name(),
686            ARC_TZIF(tzif) => tzif.name(),
687            ARC_POSIX(_posix) => None,
688        }
689    }
690
691    /// When this time zone was loaded from an IANA time zone database entry,
692    /// then this returns the primary name for that time zone.
693    ///
694    /// This follows the same [rules as ECMAScript][rules]. In effect, there is
695    /// at least one primary time zone identifier for each ISO 3166 country
696    /// code.
697    ///
698    /// [rules]: https://tc39.es/ecma402/#sup-availablenamedtimezoneidentifiers
699    ///
700    /// # Example
701    ///
702    /// ```
703    /// use jiff::tz::TimeZone;
704    /// # if TimeZone::get("Asia/Calcutta").is_err() { return Ok(()) };
705    ///
706    /// let tz = TimeZone::get("Asia/Calcutta")?;
707    /// assert_eq!(tz.primary_iana_name(), Some("Asia/Kolkata"));
708    ///
709    /// let tz = TimeZone::get("Europe/Prague")?;
710    /// assert_eq!(tz.primary_iana_name(), Some("Europe/Prague"));
711    ///
712    /// let tz = TimeZone::get("Asia/Kolkata")?;
713    /// assert_eq!(tz.primary_iana_name(), Some("Asia/Kolkata"));
714    ///
715    /// let tz = TimeZone::get("Atlantic/Jan_Mayen")?;
716    /// assert_eq!(tz.primary_iana_name(), Some("Arctic/Longyearbyen"));
717    ///
718    /// # Ok::<(), Box<dyn std::error::Error>>(())
719    /// ```
720    #[inline]
721    pub fn primary_iana_name(&self) -> Option<&str> {
722        {
    let repr = &self.repr;
    match repr.tag() {
        Repr::UTC => Some("UTC"),
        Repr::UNKNOWN => None,
        Repr::FIXED => { let _offset = unsafe { repr.get_fixed() }; None }
        Repr::STATIC_TZIF => {
            let tzif = unsafe { repr.get_static_tzif() };
            tzif.name().and_then(find_primary_iana_name)
        }Repr::ARC_TZIF => {
            let tzif = unsafe { repr.get_arc_tzif() };
            tzif.name().and_then(find_primary_iana_name)
        }Repr::ARC_POSIX => {
            let _posix = unsafe { repr.get_arc_posix() };
            None
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}repr::each! {
723            &self.repr,
724            UTC => Some("UTC"),
725            UNKNOWN => None,
726            FIXED(_offset) => None,
727            STATIC_TZIF(tzif) => tzif.name().and_then(find_primary_iana_name),
728            ARC_TZIF(tzif) => tzif.name().and_then(find_primary_iana_name),
729            ARC_POSIX(_posix) => None,
730        }
731    }
732
733    /// Returns true when this time zone is "primary."
734    ///
735    /// A time zone is primary when it is the preferred identifier according
736    /// to the [ECMAScript rules][rules]. Specifically, a time zone is
737    /// primary precisely when its IANA time zone identifier is equivalent to
738    /// its primary IANA time zone identifier.
739    ///
740    /// [rules]: https://tc39.es/ecma402/#sup-availablenamedtimezoneidentifiers
741    ///
742    /// # Example
743    ///
744    /// ```
745    /// use jiff::tz::TimeZone;
746    /// # if TimeZone::get("Asia/Calcutta").is_err() { return Ok(()) };
747    ///
748    /// let tz = TimeZone::get("Asia/Calcutta")?;
749    /// assert!(!tz.is_primary());
750    /// let tz = TimeZone::get("Asia/Kolkata")?;
751    /// assert!(tz.is_primary());
752    ///
753    /// let tz = TimeZone::get("Europe/Berlin")?;
754    /// assert!(tz.is_primary());
755    /// let tz = TimeZone::get("Europe/Copenhagen")?;
756    /// assert!(tz.is_primary());
757    ///
758    /// let tz1 = TimeZone::get("Asia/Calcutta")?;
759    /// let tz2 = TimeZone::get("Asia/Kolkata")?;
760    /// assert_eq!(tz1, tz2);
761    ///
762    /// # Ok::<(), Box<dyn std::error::Error>>(())
763    /// ```
764    #[inline]
765    pub fn is_primary(&self) -> bool {
766        self.iana_name()
767            .and_then(|name| Some((name, self.primary_iana_name()?)))
768            .map(|(name, primary)| name == primary)
769            .unwrap_or(false)
770    }
771
772    /// Returns geographical location information corresponding to this
773    /// time zone's primary time zone identifier.
774    ///
775    /// # Example
776    ///
777    /// ```
778    /// use jiff::tz::TimeZone;
779    /// # if TimeZone::get("Asia/Calcutta").is_err() { return Ok(()) };
780    ///
781    /// let tz = TimeZone::get("Europe/Copenhagen")?;
782    /// let loc = tz.location().unwrap();
783    /// assert_eq!(loc.country(), "DK");
784    ///
785    /// let tz = TimeZone::get("EuRoPe/BeRlIn")?;
786    /// let loc = tz.location().unwrap();
787    /// assert_eq!(loc.country(), "DE");
788    ///
789    /// let tz = TimeZone::get("asia/calcutta")?;
790    /// let loc = tz.location().unwrap();
791    /// assert_eq!(loc.country(), "IN");
792    ///
793    /// # Ok::<(), Box<dyn std::error::Error>>(())
794    /// ```
795    #[inline]
796    pub fn location(&self) -> Option<TimeZoneLocation> {
797        {
    let repr = &self.repr;
    match repr.tag() {
        Repr::UTC => None,
        Repr::UNKNOWN => None,
        Repr::FIXED => { let _offset = unsafe { repr.get_fixed() }; None }
        Repr::STATIC_TZIF => {
            let tzif = unsafe { repr.get_static_tzif() };
            tzif.name().and_then(find_tz_location)
        }Repr::ARC_TZIF => {
            let tzif = unsafe { repr.get_arc_tzif() };
            tzif.name().and_then(find_tz_location)
        }Repr::ARC_POSIX => {
            let _posix = unsafe { repr.get_arc_posix() };
            None
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}repr::each! {
798            &self.repr,
799            UTC => None,
800            UNKNOWN => None,
801            FIXED(_offset) => None,
802            STATIC_TZIF(tzif) => tzif.name().and_then(find_tz_location),
803            ARC_TZIF(tzif) => tzif.name().and_then(find_tz_location),
804            ARC_POSIX(_posix) => None,
805        }
806    }
807
808    /// Returns true if and only if this time zone is unknown.
809    ///
810    /// This has the special internal identifier of `Etc/Unknown`, and this
811    /// is what will be used when converting a `ZonedDateTime` to a string.
812    ///
813    /// Note that while `Etc/Unknown` looks like an IANA time zone identifier,
814    /// it is specifically and explicitly not one. It is reserved and is
815    /// guaranteed to never be an IANA time zone identifier.
816    ///
817    /// An unknown time zone can be created via [`TimeZone::unknown`]. It is
818    /// also returned by [`TimeZone::system`] when a system configured time
819    /// zone could not be found.
820    ///
821    /// # Example
822    ///
823    /// ```
824    /// use jiff::tz::TimeZone;
825    ///
826    /// let tz = TimeZone::unknown();
827    /// assert_eq!(tz.iana_name(), None);
828    /// assert!(tz.is_unknown());
829    /// ```
830    #[inline]
831    pub fn is_unknown(&self) -> bool {
832        self.repr.is_unknown()
833    }
834
835    /// When this time zone is a POSIX time zone, return it.
836    ///
837    /// This doesn't attempt to convert other time zones that are representable
838    /// as POSIX time zones to POSIX time zones (e.g., fixed offset time
839    /// zones). Instead, this only returns something when the actual
840    /// representation of the time zone is a POSIX time zone.
841    #[inline]
842    pub(crate) fn posix_tz(&self) -> Option<&posix::TimeZone> {
843        {
    let repr = &self.repr;
    match repr.tag() {
        Repr::UTC => None,
        Repr::UNKNOWN => None,
        Repr::FIXED => { let _offset = unsafe { repr.get_fixed() }; None }
        Repr::STATIC_TZIF => {
            let _tzif = unsafe { repr.get_static_tzif() };
            None
        }Repr::ARC_TZIF => {
            let _tzif = unsafe { repr.get_arc_tzif() };
            None
        }Repr::ARC_POSIX => {
            let posix = unsafe { repr.get_arc_posix() };
            Some(posix)
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}repr::each! {
844            &self.repr,
845            UTC => None,
846            UNKNOWN => None,
847            FIXED(_offset) => None,
848            STATIC_TZIF(_tzif) => None,
849            ARC_TZIF(_tzif) => None,
850            ARC_POSIX(posix) => Some(posix),
851        }
852    }
853
854    /// Returns the civil datetime corresponding to the given timestamp in this
855    /// time zone.
856    ///
857    /// This operation is always unambiguous. That is, for any instant in time
858    /// supported by Jiff (that is, a `Timestamp`), there is always precisely
859    /// one civil datetime corresponding to that instant.
860    ///
861    /// Note that this is considered a lower level routine. Consider working
862    /// with zoned datetimes instead, and use [`ZonedDateTime::datetime`] to
863    /// get its civil time if necessary.
864    ///
865    /// # Example
866    ///
867    /// ```
868    /// use jiff::{tz::TimeZone, Timestamp};
869    ///
870    /// let tz = TimeZone::get("Europe/Rome")?;
871    /// assert_eq!(
872    ///     tz.to_datetime(Timestamp::UNIX_EPOCH).to_string(),
873    ///     "1970-01-01T01:00:00",
874    /// );
875    ///
876    /// # Ok::<(), Box<dyn std::error::Error>>(())
877    /// ```
878    ///
879    /// As mentioned above, consider using `ZonedDateTime` instead:
880    ///
881    /// ```
882    /// use jiff::Timestamp;
883    ///
884    /// let zdt = Timestamp::UNIX_EPOCH.in_tz("Europe/Rome")?;
885    /// assert_eq!(zdt.datetime().to_string(), "1970-01-01T01:00:00");
886    ///
887    /// # Ok::<(), Box<dyn std::error::Error>>(())
888    /// ```
889    #[inline]
890    pub fn to_datetime(&self, timestamp: Timestamp) -> DateTime {
891        self.to_offset(timestamp).to_datetime(timestamp)
892    }
893
894    /// Returns the offset corresponding to the given timestamp in this time
895    /// zone.
896    ///
897    /// This operation is always unambiguous. That is, for any instant in time
898    /// supported by Jiff (that is, a `Timestamp`), there is always precisely
899    /// one offset corresponding to that instant.
900    ///
901    /// Given an offset, one can use APIs like [`Offset::to_datetime`] to
902    /// create a civil datetime from a timestamp.
903    ///
904    /// This also returns whether this timestamp is considered to be in
905    /// "daylight saving time," as well as the abbreviation for the time zone
906    /// at this time.
907    ///
908    /// # Example
909    ///
910    /// ```
911    /// use jiff::{tz::{self, TimeZone}, Timestamp};
912    ///
913    /// let tz = TimeZone::get("America/New_York")?;
914    ///
915    /// // A timestamp in DST in New York.
916    /// let ts = Timestamp::from_second(1_720_493_204)?;
917    /// let offset = tz.to_offset(ts);
918    /// assert_eq!(offset, tz::offset(-4));
919    /// assert_eq!(offset.to_datetime(ts).to_string(), "2024-07-08T22:46:44");
920    ///
921    /// // A timestamp *not* in DST in New York.
922    /// let ts = Timestamp::from_second(1_704_941_204)?;
923    /// let offset = tz.to_offset(ts);
924    /// assert_eq!(offset, tz::offset(-5));
925    /// assert_eq!(offset.to_datetime(ts).to_string(), "2024-01-10T21:46:44");
926    ///
927    /// # Ok::<(), Box<dyn std::error::Error>>(())
928    /// ```
929    #[inline]
930    pub fn to_offset(&self, timestamp: Timestamp) -> Offset {
931        {
    let repr = &self.repr;
    match repr.tag() {
        Repr::UTC => Offset::UTC,
        Repr::UNKNOWN => Offset::UTC,
        Repr::FIXED => { let offset = unsafe { repr.get_fixed() }; offset }
        Repr::STATIC_TZIF => {
            let tzif = unsafe { repr.get_static_tzif() };
            Offset::from_jcore(tzif.tz().to_offset(timestamp.to_jcore()))
        }Repr::ARC_TZIF => {
            let tzif = unsafe { repr.get_arc_tzif() };
            Offset::from_jcore(tzif.tz().to_offset(timestamp.to_jcore()))
        }Repr::ARC_POSIX => {
            let posix = unsafe { repr.get_arc_posix() };
            Offset::from_jcore(posix.to_offset(timestamp.to_jcore()))
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}repr::each! {
932            &self.repr,
933            UTC => Offset::UTC,
934            UNKNOWN => Offset::UTC,
935            FIXED(offset) => offset,
936            STATIC_TZIF(tzif) => Offset::from_jcore(
937                tzif.tz().to_offset(timestamp.to_jcore()),
938            ),
939            ARC_TZIF(tzif) => Offset::from_jcore(
940                tzif.tz().to_offset(timestamp.to_jcore()),
941            ),
942            ARC_POSIX(posix) => Offset::from_jcore(
943                posix.to_offset(timestamp.to_jcore()),
944            ),
945        }
946    }
947
948    /// Returns the offset information corresponding to the given timestamp in
949    /// this time zone. This includes the offset along with daylight saving
950    /// time status and a time zone abbreviation.
951    ///
952    /// This is like [`TimeZone::to_offset`], but returns the aforementioned
953    /// extra data in addition to the offset. This data may, in some cases, be
954    /// more expensive to compute.
955    ///
956    /// # Example
957    ///
958    /// ```
959    /// use jiff::{tz::{self, Dst, TimeZone}, Timestamp};
960    ///
961    /// let tz = TimeZone::get("America/New_York")?;
962    ///
963    /// // A timestamp in DST in New York.
964    /// let ts = Timestamp::from_second(1_720_493_204)?;
965    /// let info = tz.to_offset_info(ts);
966    /// assert_eq!(info.offset(), tz::offset(-4));
967    /// assert_eq!(info.dst(), Dst::Yes);
968    /// assert_eq!(info.abbreviation(), "EDT");
969    /// assert_eq!(
970    ///     info.offset().to_datetime(ts).to_string(),
971    ///     "2024-07-08T22:46:44",
972    /// );
973    ///
974    /// // A timestamp *not* in DST in New York.
975    /// let ts = Timestamp::from_second(1_704_941_204)?;
976    /// let info = tz.to_offset_info(ts);
977    /// assert_eq!(info.offset(), tz::offset(-5));
978    /// assert_eq!(info.dst(), Dst::No);
979    /// assert_eq!(info.abbreviation(), "EST");
980    /// assert_eq!(
981    ///     info.offset().to_datetime(ts).to_string(),
982    ///     "2024-01-10T21:46:44",
983    /// );
984    ///
985    /// # Ok::<(), Box<dyn std::error::Error>>(())
986    /// ```
987    #[inline]
988    pub fn to_offset_info<'t>(
989        &'t self,
990        timestamp: Timestamp,
991    ) -> TimeZoneOffsetInfo<'t> {
992        static UTC: jcore::tz::Abbreviation =
993            jcore::tz::Abbreviation::array("UTC");
994        {
    let repr = &self.repr;
    match repr.tag() {
        Repr::UTC =>
            TimeZoneOffsetInfo {
                offset: Offset::UTC,
                dst: Dst::No,
                abbreviation: UTC.clone(),
                vestigial_lifetime: core::marker::PhantomData,
            },
        Repr::UNKNOWN =>
            TimeZoneOffsetInfo {
                offset: Offset::UTC,
                dst: Dst::No,
                abbreviation: UTC.clone(),
                vestigial_lifetime: core::marker::PhantomData,
            },
        Repr::FIXED => {
            let offset = unsafe { repr.get_fixed() };
            {
                let abbreviation = offset.to_abbreviation();
                TimeZoneOffsetInfo {
                    offset,
                    dst: Dst::No,
                    abbreviation,
                    vestigial_lifetime: core::marker::PhantomData,
                }
            }
        }
        Repr::STATIC_TZIF => {
            let tzif = unsafe { repr.get_static_tzif() };
            TimeZoneOffsetInfo::from_jcore(tzif.tz().to_offset_info(timestamp.to_jcore()))
        }Repr::ARC_TZIF => {
            let tzif = unsafe { repr.get_arc_tzif() };
            TimeZoneOffsetInfo::from_jcore(tzif.tz().to_offset_info(timestamp.to_jcore()))
        }Repr::ARC_POSIX => {
            let posix = unsafe { repr.get_arc_posix() };
            TimeZoneOffsetInfo::from_jcore(posix.to_offset_info(timestamp.to_jcore()))
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}repr::each! {
995            &self.repr,
996            UTC => TimeZoneOffsetInfo {
997                offset: Offset::UTC,
998                dst: Dst::No,
999                abbreviation: UTC.clone(),
1000                vestigial_lifetime: core::marker::PhantomData,
1001            },
1002            UNKNOWN => TimeZoneOffsetInfo {
1003                offset: Offset::UTC,
1004                dst: Dst::No,
1005                // It'd be kinda nice if this were just `ERR` to
1006                // indicate an error, but I can't find any precedent
1007                // for that. And CLDR says `Etc/Unknown` should behave
1008                // like UTC, so... I guess we use UTC here.
1009                abbreviation: UTC.clone(),
1010                vestigial_lifetime: core::marker::PhantomData,
1011            },
1012            FIXED(offset) => {
1013                let abbreviation =
1014                    offset.to_abbreviation();
1015                TimeZoneOffsetInfo {
1016                    offset,
1017                    dst: Dst::No,
1018                    abbreviation,
1019                    vestigial_lifetime: core::marker::PhantomData,
1020                }
1021            },
1022            STATIC_TZIF(tzif) => TimeZoneOffsetInfo::from_jcore(
1023                tzif.tz().to_offset_info(timestamp.to_jcore()),
1024            ),
1025            ARC_TZIF(tzif) => TimeZoneOffsetInfo::from_jcore(
1026                tzif.tz().to_offset_info(timestamp.to_jcore()),
1027            ),
1028            ARC_POSIX(posix) => TimeZoneOffsetInfo::from_jcore(
1029                posix.to_offset_info(timestamp.to_jcore()),
1030            ),
1031        }
1032    }
1033
1034    /// If this time zone is a fixed offset, then this returns the offset.
1035    /// If this time zone is not a fixed offset, then an error is returned.
1036    ///
1037    /// If you just need an offset for a given timestamp, then you can use
1038    /// [`TimeZone::to_offset`]. Or, if you need an offset for a civil
1039    /// datetime, then you can use [`TimeZone::to_ambiguous_timestamp`] or
1040    /// [`TimeZone::to_ambiguous_zoned_datetime`], although the result may be
1041    /// ambiguous.
1042    ///
1043    /// Generally, this routine is useful when you need to know whether the
1044    /// time zone is fixed, and you want to get the offset without having to
1045    /// specify a timestamp. This is sometimes required for interoperating with
1046    /// other datetime systems that need to distinguish between time zones that
1047    /// are fixed and time zones that are based on rules such as those found in
1048    /// the IANA time zone database.
1049    ///
1050    /// # Example
1051    ///
1052    /// ```
1053    /// use jiff::tz::{Offset, TimeZone};
1054    ///
1055    /// let tz = TimeZone::get("America/New_York")?;
1056    /// // A named time zone is not a fixed offset
1057    /// // and so cannot be converted to an offset
1058    /// // without a timestamp or civil datetime.
1059    /// assert_eq!(
1060    ///     tz.to_fixed_offset().unwrap_err().to_string(),
1061    ///     "cannot convert non-fixed IANA time zone \
1062    ///      to offset without a timestamp or civil datetime",
1063    /// );
1064    ///
1065    /// let tz = TimeZone::UTC;
1066    /// // UTC is a fixed offset and so can be converted
1067    /// // without a timestamp.
1068    /// assert_eq!(tz.to_fixed_offset()?, Offset::UTC);
1069    ///
1070    /// // And of course, creating a time zone from a
1071    /// // fixed offset results in a fixed offset time
1072    /// // zone too:
1073    /// let tz = TimeZone::fixed(jiff::tz::offset(-10));
1074    /// assert_eq!(tz.to_fixed_offset()?, jiff::tz::offset(-10));
1075    ///
1076    /// # Ok::<(), Box<dyn std::error::Error>>(())
1077    /// ```
1078    #[inline]
1079    pub fn to_fixed_offset(&self) -> Result<Offset, Error> {
1080        let mkerr = || {
1081            Error::from(E::ConvertNonFixed { kind: self.kind_description() })
1082        };
1083        {
    let repr = &self.repr;
    match repr.tag() {
        Repr::UTC => Ok(Offset::UTC),
        Repr::UNKNOWN => Ok(Offset::UTC),
        Repr::FIXED => {
            let offset = unsafe { repr.get_fixed() };
            Ok(offset)
        }
        Repr::STATIC_TZIF => {
            let _tzif = unsafe { repr.get_static_tzif() };
            Err(mkerr())
        }Repr::ARC_TZIF => {
            let _tzif = unsafe { repr.get_arc_tzif() };
            Err(mkerr())
        }Repr::ARC_POSIX => {
            let _posix = unsafe { repr.get_arc_posix() };
            Err(mkerr())
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}repr::each! {
1084            &self.repr,
1085            UTC => Ok(Offset::UTC),
1086            UNKNOWN => Ok(Offset::UTC),
1087            FIXED(offset) => Ok(offset),
1088            STATIC_TZIF(_tzif) => Err(mkerr()),
1089            ARC_TZIF(_tzif) => Err(mkerr()),
1090            ARC_POSIX(_posix) => Err(mkerr()),
1091        }
1092    }
1093
1094    /// Converts a civil datetime to a [`ZonedDateTime`] in this time zone.
1095    ///
1096    /// The given civil datetime may be ambiguous in this time zone. A civil
1097    /// datetime is ambiguous when either of the following occurs:
1098    ///
1099    /// * When the civil datetime falls into a "gap." That is, when there is a
1100    /// jump forward in time where a span of time does not appear on the clocks
1101    /// in this time zone. This _typically_ manifests as a 1 hour jump forward
1102    /// into daylight saving time.
1103    /// * When the civil datetime falls into a "fold." That is, when there is
1104    /// a jump backward in time where a span of time is _repeated_ on the
1105    /// clocks in this time zone. This _typically_ manifests as a 1 hour jump
1106    /// backward out of daylight saving time.
1107    ///
1108    /// This routine automatically resolves both of the above ambiguities via
1109    /// the
1110    /// [`Disambiguation::Compatible`](crate::tz::Disambiguation::Compatible)
1111    /// strategy. That in, the case of a gap, the time after the gap is used.
1112    /// In the case of a fold, the first repetition of the clock time is used.
1113    ///
1114    /// # Example
1115    ///
1116    /// This example shows how disambiguation works:
1117    ///
1118    /// ```
1119    /// use jiff::{civil::date, tz::TimeZone};
1120    ///
1121    /// let tz = TimeZone::get("America/New_York")?;
1122    ///
1123    /// // This demonstrates disambiguation behavior for a gap.
1124    /// let zdt = tz.to_zoned_datetime(date(2024, 3, 10).at(2, 30, 0, 0))?;
1125    /// assert_eq!(zdt.to_string(), "2024-03-10T03:30:00-04:00[America/New_York]");
1126    /// // This demonstrates disambiguation behavior for a fold.
1127    /// // Notice the offset: the -04 corresponds to the time while
1128    /// // still in DST. The second repetition of the 1 o'clock hour
1129    /// // occurs outside of DST, in "standard" time, with the offset -5.
1130    /// let zdt = tz.to_zoned_datetime(date(2024, 11, 3).at(1, 30, 0, 0))?;
1131    /// assert_eq!(zdt.to_string(), "2024-11-03T01:30:00-04:00[America/New_York]");
1132    ///
1133    /// # Ok::<(), Box<dyn std::error::Error>>(())
1134    /// ```
1135    #[inline]
1136    pub fn to_zoned_datetime(
1137        &self,
1138        dt: DateTime,
1139    ) -> Result<ZonedDateTime, Error> {
1140        self.to_ambiguous_zoned_datetime(dt).compatible()
1141    }
1142
1143    /// Converts a civil datetime to a possibly ambiguous zoned datetime in
1144    /// this time zone.
1145    ///
1146    /// The given civil datetime may be ambiguous in this time zone. A civil
1147    /// datetime is ambiguous when either of the following occurs:
1148    ///
1149    /// * When the civil datetime falls into a "gap." That is, when there is a
1150    /// jump forward in time where a span of time does not appear on the clocks
1151    /// in this time zone. This _typically_ manifests as a 1 hour jump forward
1152    /// into daylight saving time.
1153    /// * When the civil datetime falls into a "fold." That is, when there is
1154    /// a jump backward in time where a span of time is _repeated_ on the
1155    /// clocks in this time zone. This _typically_ manifests as a 1 hour jump
1156    /// backward out of daylight saving time.
1157    ///
1158    /// Unlike [`TimeZone::to_zoned_datetime`], this method does not do any
1159    /// automatic disambiguation. Instead, callers are expected to use the
1160    /// methods on [`AmbiguousZonedDateTime`] to resolve any ambiguity, if it
1161    /// occurs.
1162    ///
1163    /// # Example
1164    ///
1165    /// This example shows how to return an error when the civil datetime given
1166    /// is ambiguous:
1167    ///
1168    /// ```
1169    /// use jiff::{civil::date, tz::TimeZone};
1170    ///
1171    /// let tz = TimeZone::get("America/New_York")?;
1172    ///
1173    /// // This is not ambiguous:
1174    /// let dt = date(2024, 3, 10).at(1, 0, 0, 0);
1175    /// assert_eq!(
1176    ///     tz.to_ambiguous_zoned_datetime(dt).unambiguous()?.to_string(),
1177    ///     "2024-03-10T01:00:00-05:00[America/New_York]",
1178    /// );
1179    /// // But this is a gap, and thus ambiguous! So an error is returned.
1180    /// let dt = date(2024, 3, 10).at(2, 0, 0, 0);
1181    /// assert!(tz.to_ambiguous_zoned_datetime(dt).unambiguous().is_err());
1182    /// // And so is this, because it's a fold.
1183    /// let dt = date(2024, 11, 3).at(1, 0, 0, 0);
1184    /// assert!(tz.to_ambiguous_zoned_datetime(dt).unambiguous().is_err());
1185    ///
1186    /// # Ok::<(), Box<dyn std::error::Error>>(())
1187    /// ```
1188    #[inline]
1189    pub fn to_ambiguous_zoned_datetime(
1190        &self,
1191        dt: DateTime,
1192    ) -> AmbiguousZonedDateTime {
1193        self.clone().into_ambiguous_zoned_datetime(dt)
1194    }
1195
1196    /// Converts a civil datetime to a possibly ambiguous zoned datetime in
1197    /// this time zone, and does so by assuming ownership of this `TimeZone`.
1198    ///
1199    /// This is identical to [`TimeZone::to_ambiguous_zoned_datetime`], but it
1200    /// avoids a `TimeZone::clone()` call. (Which are cheap, but not completely
1201    /// free.)
1202    ///
1203    /// # Example
1204    ///
1205    /// This example shows how to create a `ZonedDateTime` value from a
1206    /// `TimeZone` and a `DateTime` without cloning the `TimeZone`:
1207    ///
1208    /// ```
1209    /// use jiff::{civil::date, tz::TimeZone};
1210    ///
1211    /// let tz = TimeZone::get("America/New_York")?;
1212    /// let dt = date(2024, 3, 10).at(1, 0, 0, 0);
1213    /// assert_eq!(
1214    ///     tz.into_ambiguous_zoned_datetime(dt).unambiguous()?.to_string(),
1215    ///     "2024-03-10T01:00:00-05:00[America/New_York]",
1216    /// );
1217    ///
1218    /// # Ok::<(), Box<dyn std::error::Error>>(())
1219    /// ```
1220    #[inline]
1221    pub fn into_ambiguous_zoned_datetime(
1222        self,
1223        dt: DateTime,
1224    ) -> AmbiguousZonedDateTime {
1225        self.to_ambiguous_timestamp(dt).into_ambiguous_zoned_datetime(self)
1226    }
1227
1228    /// Converts a civil datetime to a [`Timestamp`] in this time zone.
1229    ///
1230    /// The given civil datetime may be ambiguous in this time zone. A civil
1231    /// datetime is ambiguous when either of the following occurs:
1232    ///
1233    /// * When the civil datetime falls into a "gap." That is, when there is a
1234    /// jump forward in time where a span of time does not appear on the clocks
1235    /// in this time zone. This _typically_ manifests as a 1 hour jump forward
1236    /// into daylight saving time.
1237    /// * When the civil datetime falls into a "fold." That is, when there is
1238    /// a jump backward in time where a span of time is _repeated_ on the
1239    /// clocks in this time zone. This _typically_ manifests as a 1 hour jump
1240    /// backward out of daylight saving time.
1241    ///
1242    /// This routine automatically resolves both of the above ambiguities via
1243    /// the
1244    /// [`Disambiguation::Compatible`](crate::tz::Disambiguation::Compatible)
1245    /// strategy. That in, the case of a gap, the time after the gap is used.
1246    /// In the case of a fold, the first repetition of the clock time is used.
1247    ///
1248    /// This routine is identical to [`TimeZone::to_zoned_datetime`], except
1249    /// it returns a `Timestamp` instead of a zoned datetime. The benefit of
1250    /// this method is that it never requires cloning or consuming ownership of
1251    /// a `TimeZone`, and it doesn't require construction of `ZonedDateTime`
1252    /// which has a small but non-zero cost. (This is partially because a
1253    /// `ZonedDateTime` value contains a `TimeZone`, but of course, a
1254    /// `Timestamp` does not.)
1255    ///
1256    /// # Example
1257    ///
1258    /// This example shows how disambiguation works:
1259    ///
1260    /// ```
1261    /// use jiff::{civil::date, tz::TimeZone};
1262    ///
1263    /// let tz = TimeZone::get("America/New_York")?;
1264    ///
1265    /// // This demonstrates disambiguation behavior for a gap.
1266    /// let ts = tz.to_timestamp(date(2024, 3, 10).at(2, 30, 0, 0))?;
1267    /// assert_eq!(ts.to_string(), "2024-03-10T07:30:00Z");
1268    /// // This demonstrates disambiguation behavior for a fold.
1269    /// // Notice the offset: the -04 corresponds to the time while
1270    /// // still in DST. The second repetition of the 1 o'clock hour
1271    /// // occurs outside of DST, in "standard" time, with the offset -5.
1272    /// let ts = tz.to_timestamp(date(2024, 11, 3).at(1, 30, 0, 0))?;
1273    /// assert_eq!(ts.to_string(), "2024-11-03T05:30:00Z");
1274    ///
1275    /// # Ok::<(), Box<dyn std::error::Error>>(())
1276    /// ```
1277    #[inline]
1278    pub fn to_timestamp(&self, dt: DateTime) -> Result<Timestamp, Error> {
1279        self.to_ambiguous_timestamp(dt).compatible()
1280    }
1281
1282    /// Converts a civil datetime to a possibly ambiguous timestamp in
1283    /// this time zone.
1284    ///
1285    /// The given civil datetime may be ambiguous in this time zone. A civil
1286    /// datetime is ambiguous when either of the following occurs:
1287    ///
1288    /// * When the civil datetime falls into a "gap." That is, when there is a
1289    /// jump forward in time where a span of time does not appear on the clocks
1290    /// in this time zone. This _typically_ manifests as a 1 hour jump forward
1291    /// into daylight saving time.
1292    /// * When the civil datetime falls into a "fold." That is, when there is
1293    /// a jump backward in time where a span of time is _repeated_ on the
1294    /// clocks in this time zone. This _typically_ manifests as a 1 hour jump
1295    /// backward out of daylight saving time.
1296    ///
1297    /// Unlike [`TimeZone::to_timestamp`], this method does not do any
1298    /// automatic disambiguation. Instead, callers are expected to use the
1299    /// methods on [`AmbiguousTimestamp`] to resolve any ambiguity, if it
1300    /// occurs.
1301    ///
1302    /// This routine is identical to
1303    /// [`TimeZone::to_ambiguous_zoned_datetime`], except it returns an
1304    /// `AmbiguousTimestamp` instead of a `AmbiguousZonedDateTime`. The benefit
1305    /// of this method is that it never requires cloning or consuming ownership
1306    /// of a `TimeZone`, and it doesn't require construction of `ZonedDateTime`
1307    /// which has a small but non-zero cost. (This is partially because a
1308    /// `ZonedDateTime` value contains a `TimeZone`, but of course, a
1309    /// `Timestamp` does not.)
1310    ///
1311    /// # Example
1312    ///
1313    /// This example shows how to return an error when the civil datetime given
1314    /// is ambiguous:
1315    ///
1316    /// ```
1317    /// use jiff::{civil::date, tz::TimeZone};
1318    ///
1319    /// let tz = TimeZone::get("America/New_York")?;
1320    ///
1321    /// // This is not ambiguous:
1322    /// let dt = date(2024, 3, 10).at(1, 0, 0, 0);
1323    /// assert_eq!(
1324    ///     tz.to_ambiguous_timestamp(dt).unambiguous()?.to_string(),
1325    ///     "2024-03-10T06:00:00Z",
1326    /// );
1327    /// // But this is a gap, and thus ambiguous! So an error is returned.
1328    /// let dt = date(2024, 3, 10).at(2, 0, 0, 0);
1329    /// assert!(tz.to_ambiguous_timestamp(dt).unambiguous().is_err());
1330    /// // And so is this, because it's a fold.
1331    /// let dt = date(2024, 11, 3).at(1, 0, 0, 0);
1332    /// assert!(tz.to_ambiguous_timestamp(dt).unambiguous().is_err());
1333    ///
1334    /// # Ok::<(), Box<dyn std::error::Error>>(())
1335    /// ```
1336    #[inline]
1337    pub fn to_ambiguous_timestamp(&self, dt: DateTime) -> AmbiguousTimestamp {
1338        let ambiguous_kind = {
    let repr = &self.repr;
    match repr.tag() {
        Repr::UTC => AmbiguousOffset::Unambiguous { offset: Offset::UTC },
        Repr::UNKNOWN => AmbiguousOffset::Unambiguous { offset: Offset::UTC },
        Repr::FIXED => {
            let offset = unsafe { repr.get_fixed() };
            AmbiguousOffset::Unambiguous { offset }
        }
        Repr::STATIC_TZIF => {
            let tzif = unsafe { repr.get_static_tzif() };
            AmbiguousOffset::from_jcore(tzif.tz().to_ambiguous_timestamp(dt.to_jcore()).offset())
        }Repr::ARC_TZIF => {
            let tzif = unsafe { repr.get_arc_tzif() };
            AmbiguousOffset::from_jcore(tzif.tz().to_ambiguous_timestamp(dt.to_jcore()).offset())
        }Repr::ARC_POSIX => {
            let posix = unsafe { repr.get_arc_posix() };
            AmbiguousOffset::from_jcore(posix.to_ambiguous_timestamp(dt.to_jcore()).offset())
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}repr::each! {
1339            &self.repr,
1340            UTC => AmbiguousOffset::Unambiguous { offset: Offset::UTC },
1341            UNKNOWN => AmbiguousOffset::Unambiguous { offset: Offset::UTC },
1342            FIXED(offset) => AmbiguousOffset::Unambiguous { offset },
1343            STATIC_TZIF(tzif) => AmbiguousOffset::from_jcore(
1344                tzif.tz().to_ambiguous_timestamp(dt.to_jcore()).offset(),
1345            ),
1346            ARC_TZIF(tzif) => AmbiguousOffset::from_jcore(
1347                tzif.tz().to_ambiguous_timestamp(dt.to_jcore()).offset()
1348            ),
1349            ARC_POSIX(posix) => AmbiguousOffset::from_jcore(
1350                posix.to_ambiguous_timestamp(dt.to_jcore()).offset(),
1351            ),
1352        };
1353        AmbiguousTimestamp::new(dt, ambiguous_kind)
1354    }
1355
1356    /// Returns an iterator of time zone transitions preceding the given
1357    /// timestamp. The iterator returned yields [`TimeZoneTransition`]
1358    /// elements.
1359    ///
1360    /// The order of the iterator returned moves backward through time. If
1361    /// there is a previous transition, then the timestamp of that transition
1362    /// is guaranteed to be strictly less than the timestamp given.
1363    ///
1364    /// This is a low level API that you generally shouldn't need. It's
1365    /// useful in cases where you need to know something about the specific
1366    /// instants at which time zone transitions occur. For example, an embedded
1367    /// device might need to be explicitly programmed with daylight saving
1368    /// time transitions. APIs like this enable callers to explore those
1369    /// transitions.
1370    ///
1371    /// A time zone transition refers to a specific point in time when the
1372    /// offset from UTC for a particular geographical region changes. This
1373    /// is usually a result of daylight saving time, but it can also occur
1374    /// when a geographic region changes its permanent offset from UTC.
1375    ///
1376    /// The iterator returned is not guaranteed to yield any elements. For
1377    /// example, this occurs with a fixed offset time zone. Logically, it
1378    /// would also be possible for the iterator to be infinite, except that
1379    /// eventually the timestamp would overflow Jiff's minimum timestamp
1380    /// value, at which point, iteration stops.
1381    ///
1382    /// # Example: time since the previous transition
1383    ///
1384    /// This example shows how much time has passed since the previous time
1385    /// zone transition:
1386    ///
1387    /// ```
1388    /// use jiff::{Unit, ZonedDateTime};
1389    ///
1390    /// let now: ZonedDateTime =
1391    ///     "2024-12-31 18:25-05[America/New_York]".parse()?;
1392    /// let trans = now.time_zone().preceding(now.timestamp()).next().unwrap();
1393    /// let prev_at =
1394    ///     trans.timestamp().to_zoned_datetime(now.time_zone().clone());
1395    /// let span = now.since((Unit::Year, &prev_at))?;
1396    /// assert_eq!(format!("{span:#}"), "1mo 27d 17h 25m");
1397    ///
1398    /// # Ok::<(), Box<dyn std::error::Error>>(())
1399    /// ```
1400    ///
1401    /// # Example: show the 5 previous time zone transitions
1402    ///
1403    /// This shows how to find the 5 preceding time zone transitions (from a
1404    /// particular datetime) for a particular time zone:
1405    ///
1406    /// ```
1407    /// use jiff::{ZonedDateTime, tz::offset};
1408    ///
1409    /// let now: ZonedDateTime =
1410    ///     "2024-12-31 18:25-05[America/New_York]".parse()?;
1411    /// let transitions = now
1412    ///     .time_zone()
1413    ///     .preceding(now.timestamp())
1414    ///     .take(5)
1415    ///     .map(|t| {
1416    ///         (
1417    ///             t.timestamp().to_zoned_datetime(now.time_zone().clone()),
1418    ///             t.offset(),
1419    ///             t.abbreviation().to_string(),
1420    ///         )
1421    ///     })
1422    ///     .collect::<Vec<_>>();
1423    /// assert_eq!(transitions, vec![
1424    ///     (
1425    ///         "2024-11-03 01:00-05[America/New_York]".parse()?,
1426    ///         offset(-5),
1427    ///         "EST".to_string(),
1428    ///     ),
1429    ///     (
1430    ///         "2024-03-10 03:00-04[America/New_York]".parse()?,
1431    ///         offset(-4),
1432    ///         "EDT".to_string(),
1433    ///     ),
1434    ///     (
1435    ///         "2023-11-05 01:00-05[America/New_York]".parse()?,
1436    ///         offset(-5),
1437    ///         "EST".to_string(),
1438    ///     ),
1439    ///     (
1440    ///         "2023-03-12 03:00-04[America/New_York]".parse()?,
1441    ///         offset(-4),
1442    ///         "EDT".to_string(),
1443    ///     ),
1444    ///     (
1445    ///         "2022-11-06 01:00-05[America/New_York]".parse()?,
1446    ///         offset(-5),
1447    ///         "EST".to_string(),
1448    ///     ),
1449    /// ]);
1450    ///
1451    /// # Ok::<(), Box<dyn std::error::Error>>(())
1452    /// ```
1453    #[inline]
1454    pub fn preceding<'t>(
1455        &'t self,
1456        timestamp: Timestamp,
1457    ) -> TimeZonePrecedingTransitions<'t> {
1458        TimeZonePrecedingTransitions { tz: self, cur: timestamp }
1459    }
1460
1461    /// Returns an iterator of time zone transitions following the given
1462    /// timestamp. The iterator returned yields [`TimeZoneTransition`]
1463    /// elements.
1464    ///
1465    /// The order of the iterator returned moves forward through time. If
1466    /// there is a following transition, then the timestamp of that transition
1467    /// is guaranteed to be strictly greater than the timestamp given.
1468    ///
1469    /// This is a low level API that you generally shouldn't need. It's
1470    /// useful in cases where you need to know something about the specific
1471    /// instants at which time zone transitions occur. For example, an embedded
1472    /// device might need to be explicitly programmed with daylight saving
1473    /// time transitions. APIs like this enable callers to explore those
1474    /// transitions.
1475    ///
1476    /// A time zone transition refers to a specific point in time when the
1477    /// offset from UTC for a particular geographical region changes. This
1478    /// is usually a result of daylight saving time, but it can also occur
1479    /// when a geographic region changes its permanent offset from UTC.
1480    ///
1481    /// The iterator returned is not guaranteed to yield any elements. For
1482    /// example, this occurs with a fixed offset time zone. Logically, it
1483    /// would also be possible for the iterator to be infinite, except that
1484    /// eventually the timestamp would overflow Jiff's maximum timestamp
1485    /// value, at which point, iteration stops.
1486    ///
1487    /// # Example: time until the next transition
1488    ///
1489    /// This example shows how much time is left until the next time zone
1490    /// transition:
1491    ///
1492    /// ```
1493    /// use jiff::{Unit, ZonedDateTime};
1494    ///
1495    /// let now: ZonedDateTime =
1496    ///     "2024-12-31 18:25-05[America/New_York]".parse()?;
1497    /// let trans = now.time_zone().following(now.timestamp()).next().unwrap();
1498    /// let next_at =
1499    ///     trans.timestamp().to_zoned_datetime(now.time_zone().clone());
1500    /// let span = now.until((Unit::Year, &next_at))?;
1501    /// assert_eq!(format!("{span:#}"), "2mo 8d 7h 35m");
1502    ///
1503    /// # Ok::<(), Box<dyn std::error::Error>>(())
1504    /// ```
1505    ///
1506    /// # Example: show the 5 next time zone transitions
1507    ///
1508    /// This shows how to find the 5 following time zone transitions (from a
1509    /// particular datetime) for a particular time zone:
1510    ///
1511    /// ```
1512    /// use jiff::{ZonedDateTime, tz::offset};
1513    ///
1514    /// let now: ZonedDateTime =
1515    ///     "2024-12-31 18:25-05[America/New_York]".parse()?;
1516    /// let transitions = now
1517    ///     .time_zone()
1518    ///     .following(now.timestamp())
1519    ///     .take(5)
1520    ///     .map(|t| {
1521    ///         (
1522    ///             t.timestamp().to_zoned_datetime(now.time_zone().clone()),
1523    ///             t.offset(),
1524    ///             t.abbreviation().to_string(),
1525    ///         )
1526    ///     })
1527    ///     .collect::<Vec<_>>();
1528    /// assert_eq!(transitions, vec![
1529    ///     (
1530    ///         "2025-03-09 03:00-04[America/New_York]".parse()?,
1531    ///         offset(-4),
1532    ///         "EDT".to_string(),
1533    ///     ),
1534    ///     (
1535    ///         "2025-11-02 01:00-05[America/New_York]".parse()?,
1536    ///         offset(-5),
1537    ///         "EST".to_string(),
1538    ///     ),
1539    ///     (
1540    ///         "2026-03-08 03:00-04[America/New_York]".parse()?,
1541    ///         offset(-4),
1542    ///         "EDT".to_string(),
1543    ///     ),
1544    ///     (
1545    ///         "2026-11-01 01:00-05[America/New_York]".parse()?,
1546    ///         offset(-5),
1547    ///         "EST".to_string(),
1548    ///     ),
1549    ///     (
1550    ///         "2027-03-14 03:00-04[America/New_York]".parse()?,
1551    ///         offset(-4),
1552    ///         "EDT".to_string(),
1553    ///     ),
1554    /// ]);
1555    ///
1556    /// # Ok::<(), Box<dyn std::error::Error>>(())
1557    /// ```
1558    #[inline]
1559    pub fn following<'t>(
1560        &'t self,
1561        timestamp: Timestamp,
1562    ) -> TimeZoneFollowingTransitions<'t> {
1563        TimeZoneFollowingTransitions { tz: self, cur: timestamp }
1564    }
1565
1566    /// Used by the "preceding transitions" iterator.
1567    #[inline]
1568    fn previous_transition<'t>(
1569        &'t self,
1570        timestamp: Timestamp,
1571    ) -> Option<TimeZoneTransition<'t>> {
1572        {
    let repr = &self.repr;
    match repr.tag() {
        Repr::UTC => None,
        Repr::UNKNOWN => None,
        Repr::FIXED => { let _offset = unsafe { repr.get_fixed() }; None }
        Repr::STATIC_TZIF => {
            let tzif = unsafe { repr.get_static_tzif() };
            {
                tzif.tz().previous_transition(timestamp.to_jcore()).map(TimeZoneTransition::from_jcore)
            }
        }Repr::ARC_TZIF => {
            let tzif = unsafe { repr.get_arc_tzif() };
            {
                tzif.tz().previous_transition(timestamp.to_jcore()).map(TimeZoneTransition::from_jcore)
            }
        }Repr::ARC_POSIX => {
            let posix = unsafe { repr.get_arc_posix() };
            {
                posix.previous_transition(timestamp.to_jcore()).map(TimeZoneTransition::from_jcore)
            }
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}repr::each! {
1573            &self.repr,
1574            UTC => None,
1575            UNKNOWN => None,
1576            FIXED(_offset) => None,
1577            STATIC_TZIF(tzif) => {
1578                tzif.tz()
1579                    .previous_transition(timestamp.to_jcore())
1580                    .map(TimeZoneTransition::from_jcore)
1581            },
1582            ARC_TZIF(tzif) => {
1583                tzif.tz()
1584                    .previous_transition(timestamp.to_jcore())
1585                    .map(TimeZoneTransition::from_jcore)
1586            },
1587            ARC_POSIX(posix) => {
1588                posix.previous_transition(timestamp.to_jcore())
1589                    .map(TimeZoneTransition::from_jcore)
1590            },
1591        }
1592    }
1593
1594    /// Used by the "following transitions" iterator.
1595    #[inline]
1596    fn next_transition<'t>(
1597        &'t self,
1598        timestamp: Timestamp,
1599    ) -> Option<TimeZoneTransition<'t>> {
1600        {
    let repr = &self.repr;
    match repr.tag() {
        Repr::UTC => None,
        Repr::UNKNOWN => None,
        Repr::FIXED => { let _offset = unsafe { repr.get_fixed() }; None }
        Repr::STATIC_TZIF => {
            let tzif = unsafe { repr.get_static_tzif() };
            {
                tzif.tz().next_transition(timestamp.to_jcore()).map(TimeZoneTransition::from_jcore)
            }
        }Repr::ARC_TZIF => {
            let tzif = unsafe { repr.get_arc_tzif() };
            {
                tzif.tz().next_transition(timestamp.to_jcore()).map(TimeZoneTransition::from_jcore)
            }
        }Repr::ARC_POSIX => {
            let posix = unsafe { repr.get_arc_posix() };
            {
                posix.next_transition(timestamp.to_jcore()).map(TimeZoneTransition::from_jcore)
            }
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}repr::each! {
1601            &self.repr,
1602            UTC => None,
1603            UNKNOWN => None,
1604            FIXED(_offset) => None,
1605            STATIC_TZIF(tzif) => {
1606                tzif.tz()
1607                    .next_transition(timestamp.to_jcore())
1608                    .map(TimeZoneTransition::from_jcore)
1609            },
1610            ARC_TZIF(tzif) => {
1611                tzif.tz()
1612                    .next_transition(timestamp.to_jcore())
1613                    .map(TimeZoneTransition::from_jcore)
1614            },
1615            ARC_POSIX(posix) => {
1616                posix.next_transition(timestamp.to_jcore())
1617                    .map(TimeZoneTransition::from_jcore)
1618            },
1619        }
1620    }
1621
1622    /// Returns a short description about the kind of this time zone.
1623    ///
1624    /// This is useful in error messages.
1625    fn kind_description(&self) -> &'static str {
1626        {
    let repr = &self.repr;
    match repr.tag() {
        Repr::UTC => "UTC",
        Repr::UNKNOWN => "Etc/Unknown",
        Repr::FIXED => { let _offset = unsafe { repr.get_fixed() }; "fixed" }
        Repr::STATIC_TZIF => {
            let _tzif = unsafe { repr.get_static_tzif() };
            "IANA"
        }Repr::ARC_TZIF => {
            let _tzif = unsafe { repr.get_arc_tzif() };
            "IANA"
        }Repr::ARC_POSIX => {
            let _posix = unsafe { repr.get_arc_posix() };
            "POSIX"
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}repr::each! {
1627            &self.repr,
1628            UTC => "UTC",
1629            UNKNOWN => "Etc/Unknown",
1630            FIXED(_offset) => "fixed",
1631            STATIC_TZIF(_tzif) => "IANA",
1632            ARC_TZIF(_tzif) => "IANA",
1633            ARC_POSIX(_posix) => "POSIX",
1634        }
1635    }
1636
1637    /// Returns the heap memory usage, in bytes, of this timezone.
1638    ///
1639    /// This does **not** include the stack size used up by this timezone.
1640    /// To compute that, use `std::mem::size_of::<TimeZone>()`.
1641    pub fn memory_usage(&self) -> usize {
1642        {
    let repr = &self.repr;
    match repr.tag() {
        Repr::UTC => 0,
        Repr::UNKNOWN => 0,
        Repr::FIXED => { let _offset = unsafe { repr.get_fixed() }; 0 }
        Repr::STATIC_TZIF => {
            let _tzif = unsafe { repr.get_static_tzif() };
            0
        }Repr::ARC_TZIF => {
            let _tzif = unsafe { repr.get_arc_tzif() };
            {
                core::mem::size_of::<tzif::MaybeNamedTimeZone>() +
                    (core::mem::size_of::<core::sync::atomic::AtomicUsize>() *
                            2)
            }
        }Repr::ARC_POSIX => {
            let _posix = unsafe { repr.get_arc_posix() };
            {
                core::mem::size_of::<posix::TimeZone>() +
                    (core::mem::size_of::<core::sync::atomic::AtomicUsize>() *
                            2)
            }
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}repr::each! {
1643            &self.repr,
1644            UTC => 0,
1645            UNKNOWN => 0,
1646            FIXED(_offset) => 0,
1647            STATIC_TZIF(_tzif) => 0,
1648            ARC_TZIF(_tzif) => {
1649                core::mem::size_of::<tzif::MaybeNamedTimeZone>() +
1650                (core::mem::size_of::<core::sync::atomic::AtomicUsize>() * 2)
1651            },
1652            ARC_POSIX(_posix) => {
1653                core::mem::size_of::<posix::TimeZone>() +
1654                (core::mem::size_of::<core::sync::atomic::AtomicUsize>() * 2)
1655            },
1656        }
1657    }
1658}
1659
1660// Exposed APIs for Jiff's time zone proc macro.
1661//
1662// These are NOT part of Jiff's public API. There are *zero* semver guarantees
1663// for them.
1664#[doc(hidden)]
1665impl TimeZone {
1666    /// Constructs a `TimeZone` from a static TZif time zone from jcore.
1667    pub const fn __internal_from_tzif(
1668        tzif: &'static tzif::MaybeNamedTimeZone,
1669    ) -> TimeZone {
1670        let repr = Repr::static_tzif(tzif);
1671        TimeZone { repr }
1672    }
1673
1674    /// Returns a dumb copy of this `TimeZone`.
1675    ///
1676    /// # Safety
1677    ///
1678    /// Callers must ensure that this time zone is UTC, unknown, a fixed
1679    /// offset or created with `TimeZone::__internal_from_tzif`.
1680    ///
1681    /// Namely, this specifically does not increment the ref count for
1682    /// the `Arc` pointers when the tag is `ARC_TZIF` or `ARC_POSIX`.
1683    /// This means that incorrect usage of this routine can lead to
1684    /// use-after-free.
1685    #[inline]
1686    pub const unsafe fn copy(&self) -> TimeZone {
1687        // SAFETY: Requirements are forwarded to the caller.
1688        unsafe { TimeZone { repr: self.repr.copy() } }
1689    }
1690}
1691
1692impl core::fmt::Debug for TimeZone {
1693    #[inline]
1694    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1695        f.debug_tuple("TimeZone").field(&self.repr).finish()
1696    }
1697}
1698
1699#[cfg(feature = "defmt")]
1700impl defmt::Format for TimeZone {
1701    fn format(&self, f: defmt::Formatter) {
1702        defmt::write!(f, "TimeZone({})", self.repr);
1703    }
1704}
1705
1706#[cfg(feature = "arbitrary")]
1707impl<'a> arbitrary::Arbitrary<'a> for TimeZone {
1708    fn arbitrary(
1709        u: &mut arbitrary::Unstructured<'a>,
1710    ) -> arbitrary::Result<TimeZone> {
1711        #[cfg(feature = "alloc")]
1712        {
1713            if bool::arbitrary(u)? {
1714                let names: alloc::vec::Vec<_> =
1715                    crate::tz::db().available().collect();
1716                if let Ok(name) = u.choose(&names) {
1717                    if let Ok(tz) = crate::tz::db().get(name.as_str()) {
1718                        return Ok(tz);
1719                    }
1720                }
1721            }
1722        }
1723        Ok(TimeZone::fixed(Offset::arbitrary(u)?))
1724    }
1725
1726    fn size_hint(depth: usize) -> (usize, Option<usize>) {
1727        arbitrary::size_hint::and(
1728            <bool as arbitrary::Arbitrary>::size_hint(depth),
1729            <Offset as arbitrary::Arbitrary>::size_hint(depth),
1730        )
1731    }
1732}
1733
1734/// A representation a single time zone transition.
1735///
1736/// A time zone transition is an instant in time the marks the beginning of
1737/// a change in the offset from UTC that civil time is computed from in a
1738/// particular time zone. For example, when daylight saving time comes into
1739/// effect (or goes away). Another example is when a geographic region changes
1740/// its permanent offset from UTC.
1741///
1742/// This is a low level type that you generally shouldn't need. It's useful in
1743/// cases where you need to know something about the specific instants at which
1744/// time zone transitions occur. For example, an embedded device might need to
1745/// be explicitly programmed with daylight saving time transitions. APIs like
1746/// this enable callers to explore those transitions.
1747///
1748/// This type is yielded by the iterators
1749/// [`TimeZonePrecedingTransitions`] and
1750/// [`TimeZoneFollowingTransitions`]. The iterators are created by
1751/// [`TimeZone::preceding`] and [`TimeZone::following`], respectively.
1752///
1753/// # Example
1754///
1755/// This shows a somewhat silly example that finds all of the unique civil
1756/// (or "clock" or "local") times at which a time zone transition has occurred
1757/// in a particular time zone:
1758///
1759/// ```
1760/// use jiff::{civil, tz::TimeZone};
1761/// use std::collections::BTreeSet;
1762///
1763/// let tz = TimeZone::get("America/New_York")?;
1764/// let now = civil::date(2024, 12, 31)
1765///     .at(18, 25, 0, 0)
1766///     .to_zoned_datetime(tz.clone())?;
1767/// let mut set = BTreeSet::new();
1768/// for trans in tz.preceding(now.timestamp()) {
1769///     let time = tz.to_datetime(trans.timestamp()).time();
1770///     set.insert(time);
1771/// }
1772/// assert_eq!(Vec::from_iter(set), vec![
1773///     civil::time(1, 0, 0, 0),  // typical transition out of DST
1774///     civil::time(3, 0, 0, 0),  // typical transition into DST
1775///     civil::time(12, 0, 0, 0), // from when IANA starts keeping track
1776///     civil::time(19, 0, 0, 0), // from World War 2
1777/// ]);
1778///
1779/// # Ok::<(), Box<dyn std::error::Error>>(())
1780/// ```
1781#[derive(#[automatically_derived]impl<'t> ::core::clone::Clone for
    TimeZoneTransition<'t> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        TimeZoneTransition {
            timestamp: ::core::clone::Clone::clone(&self.timestamp),
            offset: ::core::clone::Clone::clone(&self.offset),
            abbreviation: ::core::clone::Clone::clone(&self.abbreviation),
            dst: ::core::clone::Clone::clone(&self.dst),
            vestigial_lifetime: ::core::clone::Clone::clone(&self.vestigial_lifetime),
        }
    }
}Clone, #[automatically_derived]impl<'t> ::core::fmt::Debug for TimeZoneTransition<'t>
    {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f,
            "TimeZoneTransition timestamp offset abbreviation dst vestigial_lifetime",
            &self.timestamp, &self.offset, &self.abbreviation, &self.dst,
            &&self.vestigial_lifetime)
    }
}Debug)]
1782pub struct TimeZoneTransition<'t> {
1783    // We don't currently do anything smart to make iterating over
1784    // transitions faster. We could if we pushed the iterator impl down into
1785    // the respective modules (`posix` and `tzif`), but it's not clear such
1786    // optimization is really worth it. However, this API should permit that
1787    // kind of optimization in the future.
1788    pub(crate) timestamp: Timestamp,
1789    pub(crate) offset: Offset,
1790    pub(crate) abbreviation: jcore::tz::Abbreviation,
1791    pub(crate) dst: Dst,
1792    pub(crate) vestigial_lifetime: core::marker::PhantomData<&'t ()>,
1793}
1794
1795impl<'t> TimeZoneTransition<'t> {
1796    /// Returns the timestamp at which this transition began.
1797    ///
1798    /// # Example
1799    ///
1800    /// ```
1801    /// use jiff::{civil, tz::TimeZone};
1802    ///
1803    /// let tz = TimeZone::get("America/New_York")?;
1804    /// // Look for the first time zone transition in `America/New_York`
1805    /// // following 2023-03-09 00:00:00.
1806    /// let start = civil::date(2024, 3, 9)
1807    ///     .to_zoned_datetime(tz.clone())?
1808    ///     .timestamp();
1809    /// let next = tz.following(start).next().unwrap();
1810    /// assert_eq!(
1811    ///     next.timestamp().to_zoned_datetime(tz.clone()).to_string(),
1812    ///     "2024-03-10T03:00:00-04:00[America/New_York]",
1813    /// );
1814    ///
1815    /// # Ok::<(), Box<dyn std::error::Error>>(())
1816    /// ```
1817    #[inline]
1818    pub fn timestamp(&self) -> Timestamp {
1819        self.timestamp
1820    }
1821
1822    /// Returns the offset corresponding to this time zone transition. All
1823    /// instants at and following this transition's timestamp (and before the
1824    /// next transition's timestamp) need to apply this offset from UTC to get
1825    /// the civil or "local" time in the corresponding time zone.
1826    ///
1827    /// # Example
1828    ///
1829    /// ```
1830    /// use jiff::{civil, tz::{TimeZone, offset}};
1831    ///
1832    /// let tz = TimeZone::get("America/New_York")?;
1833    /// // Get the offset of the next transition after
1834    /// // 2023-03-09 00:00:00.
1835    /// let start = civil::date(2024, 3, 9)
1836    ///     .to_zoned_datetime(tz.clone())?
1837    ///     .timestamp();
1838    /// let next = tz.following(start).next().unwrap();
1839    /// assert_eq!(next.offset(), offset(-4));
1840    /// // Or go backwards to find the previous transition.
1841    /// let prev = tz.preceding(start).next().unwrap();
1842    /// assert_eq!(prev.offset(), offset(-5));
1843    ///
1844    /// # Ok::<(), Box<dyn std::error::Error>>(())
1845    /// ```
1846    #[inline]
1847    pub fn offset(&self) -> Offset {
1848        self.offset
1849    }
1850
1851    /// Returns the time zone abbreviation corresponding to this time
1852    /// zone transition. All instants at and following this transition's
1853    /// timestamp (and before the next transition's timestamp) may use this
1854    /// abbreviation when creating a human readable string. For example,
1855    /// this is the abbreviation used with the `%Z` specifier with Jiff's
1856    /// [`fmt::strtime`](crate::fmt::strtime) module.
1857    ///
1858    /// Note that abbreviations can to be ambiguous. For example, the
1859    /// abbreviation `CST` can be used for the time zones `Asia/Shanghai`,
1860    /// `America/Chicago` and `America/Havana`.
1861    ///
1862    /// The lifetime of the string returned is tied to this
1863    /// `TimeZoneTransition`, which may be shorter than `'t` (the lifetime of
1864    /// the time zone this transition was created from).
1865    ///
1866    /// # Example
1867    ///
1868    /// ```
1869    /// use jiff::{civil, tz::TimeZone};
1870    ///
1871    /// let tz = TimeZone::get("America/New_York")?;
1872    /// // Get the abbreviation of the next transition after
1873    /// // 2023-03-09 00:00:00.
1874    /// let start = civil::date(2024, 3, 9)
1875    ///     .to_zoned_datetime(tz.clone())?
1876    ///     .timestamp();
1877    /// let next = tz.following(start).next().unwrap();
1878    /// assert_eq!(next.abbreviation(), "EDT");
1879    /// // Or go backwards to find the previous transition.
1880    /// let prev = tz.preceding(start).next().unwrap();
1881    /// assert_eq!(prev.abbreviation(), "EST");
1882    ///
1883    /// # Ok::<(), Box<dyn std::error::Error>>(())
1884    /// ```
1885    #[inline]
1886    pub fn abbreviation<'a>(&'a self) -> &'a str {
1887        self.abbreviation.as_str()
1888    }
1889
1890    /// Returns whether daylight saving time is enabled for this time zone
1891    /// transition.
1892    ///
1893    /// Callers should generally treat this as informational only. In
1894    /// particular, not all time zone transitions are related to daylight
1895    /// saving time. For example, some transitions are a result of a region
1896    /// permanently changing their offset from UTC.
1897    ///
1898    /// # Example
1899    ///
1900    /// ```
1901    /// use jiff::{civil, tz::{Dst, TimeZone}};
1902    ///
1903    /// let tz = TimeZone::get("America/New_York")?;
1904    /// // Get the DST status of the next transition after
1905    /// // 2023-03-09 00:00:00.
1906    /// let start = civil::date(2024, 3, 9)
1907    ///     .to_zoned_datetime(tz.clone())?
1908    ///     .timestamp();
1909    /// let next = tz.following(start).next().unwrap();
1910    /// assert_eq!(next.dst(), Dst::Yes);
1911    /// // Or go backwards to find the previous transition.
1912    /// let prev = tz.preceding(start).next().unwrap();
1913    /// assert_eq!(prev.dst(), Dst::No);
1914    ///
1915    /// # Ok::<(), Box<dyn std::error::Error>>(())
1916    /// ```
1917    #[inline]
1918    pub fn dst(&self) -> Dst {
1919        self.dst
1920    }
1921
1922    pub(crate) fn from_jcore(
1923        trans: jcore::tz::Transition,
1924    ) -> TimeZoneTransition<'static> {
1925        let timestamp = Timestamp::from_jcore(trans.timestamp());
1926        let offset = Offset::from_jcore(trans.offset());
1927        let dst = Dst::from_jcore(trans.dst());
1928        let abbreviation = trans.into_offset_info().into_abbreviation();
1929        let vestigial_lifetime = core::marker::PhantomData;
1930        TimeZoneTransition {
1931            timestamp,
1932            offset,
1933            dst,
1934            abbreviation,
1935            vestigial_lifetime,
1936        }
1937    }
1938}
1939
1940/// An offset along with DST status and a time zone abbreviation.
1941///
1942/// This information can be computed from a [`TimeZone`] given a [`Timestamp`]
1943/// via [`TimeZone::to_offset_info`].
1944///
1945/// Generally, the extra information associated with the offset is not commonly
1946/// needed. And indeed, inspecting the daylight saving time status of a
1947/// particular instant in a time zone _usually_ leads to bugs. For example, not
1948/// all time zone transitions are the result of daylight saving time. Some are
1949/// the result of permanent changes to the standard UTC offset of a region.
1950///
1951/// This information is available via an API distinct from
1952/// [`TimeZone::to_offset`] because it is not commonly needed and because it
1953/// can sometimes be more expensive to compute.
1954///
1955/// The main use case for daylight saving time status or time zone
1956/// abbreviations is for formatting datetimes in an end user's locale. If you
1957/// want this, consider using the [`icu`] crate via [`jiff-icu`].
1958///
1959/// The lifetime parameter `'t` corresponds to the lifetime of the `TimeZone`
1960/// that this info was extracted from.
1961///
1962/// # Example
1963///
1964/// ```
1965/// use jiff::{tz::{self, Dst, TimeZone}, Timestamp};
1966///
1967/// let tz = TimeZone::get("America/New_York")?;
1968///
1969/// // A timestamp in DST in New York.
1970/// let ts = Timestamp::from_second(1_720_493_204)?;
1971/// let info = tz.to_offset_info(ts);
1972/// assert_eq!(info.offset(), tz::offset(-4));
1973/// assert_eq!(info.dst(), Dst::Yes);
1974/// assert_eq!(info.abbreviation(), "EDT");
1975/// assert_eq!(
1976///     info.offset().to_datetime(ts).to_string(),
1977///     "2024-07-08T22:46:44",
1978/// );
1979///
1980/// // A timestamp *not* in DST in New York.
1981/// let ts = Timestamp::from_second(1_704_941_204)?;
1982/// let info = tz.to_offset_info(ts);
1983/// assert_eq!(info.offset(), tz::offset(-5));
1984/// assert_eq!(info.dst(), Dst::No);
1985/// assert_eq!(info.abbreviation(), "EST");
1986/// assert_eq!(
1987///     info.offset().to_datetime(ts).to_string(),
1988///     "2024-01-10T21:46:44",
1989/// );
1990///
1991/// # Ok::<(), Box<dyn std::error::Error>>(())
1992/// ```
1993///
1994/// [`icu`]: https://docs.rs/icu
1995/// [`jiff-icu`]: https://docs.rs/jiff-icu
1996#[derive(#[automatically_derived]impl<'t> ::core::clone::Clone for
    TimeZoneOffsetInfo<'t> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        TimeZoneOffsetInfo {
            offset: ::core::clone::Clone::clone(&self.offset),
            dst: ::core::clone::Clone::clone(&self.dst),
            abbreviation: ::core::clone::Clone::clone(&self.abbreviation),
            vestigial_lifetime: ::core::clone::Clone::clone(&self.vestigial_lifetime),
        }
    }
}Clone, #[automatically_derived]impl<'t> ::core::fmt::Debug for TimeZoneOffsetInfo<'t>
    {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "TimeZoneOffsetInfo offset dst abbreviation vestigial_lifetime",
            &self.offset, &self.dst, &self.abbreviation,
            &&self.vestigial_lifetime)
    }
}Debug, #[automatically_derived]impl<'t> ::core::cmp::Eq for TimeZoneOffsetInfo<'t> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Offset>;
        let _: ::core::cmp::AssertParamIsEq<Dst>;
        let _: ::core::cmp::AssertParamIsEq<jcore::tz::Abbreviation>;
        let _:
                ::core::cmp::AssertParamIsEq<core::marker::PhantomData<&'t ()>>;
    }
}Eq, #[automatically_derived]impl<'t> ::core::hash::Hash for TimeZoneOffsetInfo<'t>
    {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.offset, state);
        ::core::hash::Hash::hash(&self.dst, state);
        ::core::hash::Hash::hash(&self.abbreviation, state);
        ::core::hash::Hash::hash(&self.vestigial_lifetime, state)
    }
}Hash, #[automatically_derived]impl<'t> ::core::marker::StructuralPartialEq for
    TimeZoneOffsetInfo<'t> {
}
#[automatically_derived]impl<'t> ::core::cmp::PartialEq for
    TimeZoneOffsetInfo<'t> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.offset == other.offset && self.dst == other.dst &&
                self.abbreviation == other.abbreviation &&
            self.vestigial_lifetime == other.vestigial_lifetime
    }
}PartialEq)]
1997pub struct TimeZoneOffsetInfo<'t> {
1998    pub(crate) offset: Offset,
1999    pub(crate) dst: Dst,
2000    pub(crate) abbreviation: jcore::tz::Abbreviation,
2001    pub(crate) vestigial_lifetime: core::marker::PhantomData<&'t ()>,
2002}
2003
2004impl<'t> TimeZoneOffsetInfo<'t> {
2005    /// Returns the offset.
2006    ///
2007    /// The offset is duration, from UTC, that should be used to offset the
2008    /// civil time in a particular location.
2009    ///
2010    /// # Example
2011    ///
2012    /// ```
2013    /// use jiff::{civil, tz::{TimeZone, offset}};
2014    ///
2015    /// let tz = TimeZone::get("America/New_York")?;
2016    /// // Get the offset for 2023-03-10 00:00:00.
2017    /// let start = civil::date(2024, 3, 10)
2018    ///     .to_zoned_datetime(tz.clone())?
2019    ///     .timestamp();
2020    /// let info = tz.to_offset_info(start);
2021    /// assert_eq!(info.offset(), offset(-5));
2022    /// // Go forward a day and notice the offset changes due to DST!
2023    /// let start = civil::date(2024, 3, 11)
2024    ///     .to_zoned_datetime(tz.clone())?
2025    ///     .timestamp();
2026    /// let info = tz.to_offset_info(start);
2027    /// assert_eq!(info.offset(), offset(-4));
2028    ///
2029    /// # Ok::<(), Box<dyn std::error::Error>>(())
2030    /// ```
2031    #[inline]
2032    pub fn offset(&self) -> Offset {
2033        self.offset
2034    }
2035
2036    /// Returns the time zone abbreviation corresponding to this offset info.
2037    ///
2038    /// Note that abbreviations can to be ambiguous. For example, the
2039    /// abbreviation `CST` can be used for the time zones `Asia/Shanghai`,
2040    /// `America/Chicago` and `America/Havana`.
2041    ///
2042    /// The lifetime of the string returned is tied to this
2043    /// `TimeZoneOffsetInfo`, which may be shorter than `'t` (the lifetime of
2044    /// the time zone this transition was created from).
2045    ///
2046    /// # Example
2047    ///
2048    /// ```
2049    /// use jiff::{civil, tz::TimeZone};
2050    ///
2051    /// let tz = TimeZone::get("America/New_York")?;
2052    /// // Get the time zone abbreviation for 2023-03-10 00:00:00.
2053    /// let start = civil::date(2024, 3, 10)
2054    ///     .to_zoned_datetime(tz.clone())?
2055    ///     .timestamp();
2056    /// let info = tz.to_offset_info(start);
2057    /// assert_eq!(info.abbreviation(), "EST");
2058    /// // Go forward a day and notice the abbreviation changes due to DST!
2059    /// let start = civil::date(2024, 3, 11)
2060    ///     .to_zoned_datetime(tz.clone())?
2061    ///     .timestamp();
2062    /// let info = tz.to_offset_info(start);
2063    /// assert_eq!(info.abbreviation(), "EDT");
2064    ///
2065    /// # Ok::<(), Box<dyn std::error::Error>>(())
2066    /// ```
2067    #[inline]
2068    pub fn abbreviation(&self) -> &str {
2069        self.abbreviation.as_str()
2070    }
2071
2072    /// Returns whether daylight saving time is enabled for this offset
2073    /// info.
2074    ///
2075    /// Callers should generally treat this as informational only. In
2076    /// particular, not all time zone transitions are related to daylight
2077    /// saving time. For example, some transitions are a result of a region
2078    /// permanently changing their offset from UTC.
2079    ///
2080    /// # Example
2081    ///
2082    /// ```
2083    /// use jiff::{civil, tz::{Dst, TimeZone}};
2084    ///
2085    /// let tz = TimeZone::get("America/New_York")?;
2086    /// // Get the DST status of 2023-03-11 00:00:00.
2087    /// let start = civil::date(2024, 3, 11)
2088    ///     .to_zoned_datetime(tz.clone())?
2089    ///     .timestamp();
2090    /// let info = tz.to_offset_info(start);
2091    /// assert_eq!(info.dst(), Dst::Yes);
2092    ///
2093    /// # Ok::<(), Box<dyn std::error::Error>>(())
2094    /// ```
2095    #[inline]
2096    pub fn dst(&self) -> Dst {
2097        self.dst
2098    }
2099
2100    pub(crate) fn from_jcore(
2101        info: jcore::tz::OffsetInfo,
2102    ) -> TimeZoneOffsetInfo<'static> {
2103        let offset = Offset::from_jcore(info.offset());
2104        let dst = Dst::from_jcore(info.dst());
2105        let abbreviation = info.into_abbreviation();
2106        let vestigial_lifetime = core::marker::PhantomData;
2107        TimeZoneOffsetInfo { offset, dst, abbreviation, vestigial_lifetime }
2108    }
2109}
2110
2111/// An iterator over time zone transitions going backward in time.
2112///
2113/// This iterator is created by [`TimeZone::preceding`].
2114///
2115/// # Example: show the 5 previous time zone transitions
2116///
2117/// This shows how to find the 5 preceding time zone transitions (from a
2118/// particular datetime) for a particular time zone:
2119///
2120/// ```
2121/// use jiff::{tz::offset, ZonedDateTime};
2122///
2123/// let now: ZonedDateTime = "2024-12-31 18:25-05[America/New_York]".parse()?;
2124/// let transitions = now
2125///     .time_zone()
2126///     .preceding(now.timestamp())
2127///     .take(5)
2128///     .map(|t| (
2129///         t.timestamp().to_zoned_datetime(now.time_zone().clone()),
2130///         t.offset(),
2131///         t.abbreviation().to_string(),
2132///     ))
2133///     .collect::<Vec<_>>();
2134/// assert_eq!(transitions, vec![
2135///     (
2136///         "2024-11-03 01:00-05[America/New_York]".parse()?,
2137///         offset(-5),
2138///         "EST".to_string(),
2139///     ),
2140///     (
2141///         "2024-03-10 03:00-04[America/New_York]".parse()?,
2142///         offset(-4),
2143///         "EDT".to_string(),
2144///     ),
2145///     (
2146///         "2023-11-05 01:00-05[America/New_York]".parse()?,
2147///         offset(-5),
2148///         "EST".to_string(),
2149///     ),
2150///     (
2151///         "2023-03-12 03:00-04[America/New_York]".parse()?,
2152///         offset(-4),
2153///         "EDT".to_string(),
2154///     ),
2155///     (
2156///         "2022-11-06 01:00-05[America/New_York]".parse()?,
2157///         offset(-5),
2158///         "EST".to_string(),
2159///     ),
2160/// ]);
2161///
2162/// # Ok::<(), Box<dyn std::error::Error>>(())
2163/// ```
2164#[derive(#[automatically_derived]impl<'t> ::core::clone::Clone for
    TimeZonePrecedingTransitions<'t> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        TimeZonePrecedingTransitions {
            tz: ::core::clone::Clone::clone(&self.tz),
            cur: ::core::clone::Clone::clone(&self.cur),
        }
    }
}Clone, #[automatically_derived]impl<'t> ::core::fmt::Debug for
    TimeZonePrecedingTransitions<'t> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "TimeZonePrecedingTransitions tz cur", &self.tz, &&self.cur)
    }
}Debug)]
2165pub struct TimeZonePrecedingTransitions<'t> {
2166    tz: &'t TimeZone,
2167    cur: Timestamp,
2168}
2169
2170impl<'t> Iterator for TimeZonePrecedingTransitions<'t> {
2171    type Item = TimeZoneTransition<'t>;
2172
2173    fn next(&mut self) -> Option<TimeZoneTransition<'t>> {
2174        let trans = self.tz.previous_transition(self.cur)?;
2175        self.cur = trans.timestamp();
2176        Some(trans)
2177    }
2178}
2179
2180impl<'t> core::iter::FusedIterator for TimeZonePrecedingTransitions<'t> {}
2181
2182/// An iterator over time zone transitions going forward in time.
2183///
2184/// This iterator is created by [`TimeZone::following`].
2185///
2186/// # Example: show the 5 next time zone transitions
2187///
2188/// This shows how to find the 5 following time zone transitions (from a
2189/// particular datetime) for a particular time zone:
2190///
2191/// ```
2192/// use jiff::{tz::offset, ZonedDateTime};
2193///
2194/// let now: ZonedDateTime = "2024-12-31 18:25-05[America/New_York]".parse()?;
2195/// let transitions = now
2196///     .time_zone()
2197///     .following(now.timestamp())
2198///     .take(5)
2199///     .map(|t| (
2200///         t.timestamp().to_zoned_datetime(now.time_zone().clone()),
2201///         t.offset(),
2202///         t.abbreviation().to_string(),
2203///     ))
2204///     .collect::<Vec<_>>();
2205/// assert_eq!(transitions, vec![
2206///     (
2207///         "2025-03-09 03:00-04[America/New_York]".parse()?,
2208///         offset(-4),
2209///         "EDT".to_string(),
2210///     ),
2211///     (
2212///         "2025-11-02 01:00-05[America/New_York]".parse()?,
2213///         offset(-5),
2214///         "EST".to_string(),
2215///     ),
2216///     (
2217///         "2026-03-08 03:00-04[America/New_York]".parse()?,
2218///         offset(-4),
2219///         "EDT".to_string(),
2220///     ),
2221///     (
2222///         "2026-11-01 01:00-05[America/New_York]".parse()?,
2223///         offset(-5),
2224///         "EST".to_string(),
2225///     ),
2226///     (
2227///         "2027-03-14 03:00-04[America/New_York]".parse()?,
2228///         offset(-4),
2229///         "EDT".to_string(),
2230///     ),
2231/// ]);
2232///
2233/// # Ok::<(), Box<dyn std::error::Error>>(())
2234/// ```
2235#[derive(#[automatically_derived]impl<'t> ::core::clone::Clone for
    TimeZoneFollowingTransitions<'t> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        TimeZoneFollowingTransitions {
            tz: ::core::clone::Clone::clone(&self.tz),
            cur: ::core::clone::Clone::clone(&self.cur),
        }
    }
}Clone, #[automatically_derived]impl<'t> ::core::fmt::Debug for
    TimeZoneFollowingTransitions<'t> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "TimeZoneFollowingTransitions tz cur", &self.tz, &&self.cur)
    }
}Debug)]
2236pub struct TimeZoneFollowingTransitions<'t> {
2237    tz: &'t TimeZone,
2238    cur: Timestamp,
2239}
2240
2241impl<'t> Iterator for TimeZoneFollowingTransitions<'t> {
2242    type Item = TimeZoneTransition<'t>;
2243
2244    fn next(&mut self) -> Option<TimeZoneTransition<'t>> {
2245        let trans = self.tz.next_transition(self.cur)?;
2246        self.cur = trans.timestamp();
2247        Some(trans)
2248    }
2249}
2250
2251impl<'t> core::iter::FusedIterator for TimeZoneFollowingTransitions<'t> {}
2252
2253/// A helper type for converting a `TimeZone` to a succinct human readable
2254/// description.
2255///
2256/// This is principally used in error messages in various places.
2257///
2258/// A previous iteration of this was just an `as_str() -> &str` method on
2259/// `TimeZone`, but that's difficult to do without relying on dynamic memory
2260/// allocation (or chunky arrays).
2261pub(crate) struct DiagnosticName<'a>(&'a TimeZone);
2262
2263impl<'a> core::fmt::Display for DiagnosticName<'a> {
2264    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2265        {
    let repr = &self.0.repr;
    match repr.tag() {
        Repr::UTC => f.write_str("UTC"),
        Repr::UNKNOWN => f.write_str("Etc/Unknown"),
        Repr::FIXED => {
            let offset = unsafe { repr.get_fixed() };
            offset.fmt(f)
        }
        Repr::STATIC_TZIF => {
            let tzif = unsafe { repr.get_static_tzif() };
            f.write_str(tzif.name().unwrap_or("Local"))
        }Repr::ARC_TZIF => {
            let tzif = unsafe { repr.get_arc_tzif() };
            f.write_str(tzif.name().unwrap_or("Local"))
        }Repr::ARC_POSIX => {
            let posix = unsafe { repr.get_arc_posix() };
            crate::tz::posix::TimeZoneFormatter(posix).fmt(f)
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}repr::each! {
2266            &self.0.repr,
2267            UTC => f.write_str("UTC"),
2268            UNKNOWN => f.write_str("Etc/Unknown"),
2269            FIXED(offset) => offset.fmt(f),
2270            STATIC_TZIF(tzif) => f.write_str(
2271                tzif.name().unwrap_or("Local"),
2272            ),
2273            ARC_TZIF(tzif) => f.write_str(
2274                tzif.name().unwrap_or("Local"),
2275            ),
2276            ARC_POSIX(posix) => crate::tz::posix::TimeZoneFormatter(posix).fmt(f),
2277        }
2278    }
2279}
2280
2281/// This module defines the internal representation of a `TimeZone`.
2282///
2283/// This module exists to _encapsulate_ the representation rigorously and
2284/// expose a safe and sound API.
2285mod repr {
2286    use core::{mem::ManuallyDrop, ptr::without_provenance};
2287
2288    use jcore::tz::{posix, tzif};
2289
2290    use crate::util::constant::unwrap;
2291    #[cfg(feature = "alloc")]
2292    use crate::util::sync::Arc;
2293
2294    use super::Offset;
2295
2296    /// A macro for "matching" over the time zone representation variants.
2297    ///
2298    /// This macro is safe to use.
2299    ///
2300    /// Note that the `ARC_TZIF` and `ARC_POSIX` branches are automatically
2301    /// removed when `alloc` isn't enabled. Users of this macro needn't handle
2302    /// the `cfg` themselves.
2303    macro_rules! each {
2304        (
2305            $repr:expr,
2306            UTC => $utc:expr,
2307            UNKNOWN => $unknown:expr,
2308            FIXED($offset:ident) => $fixed:expr,
2309            STATIC_TZIF($static_tzif:ident) => $static_tzif_block:expr,
2310            ARC_TZIF($arc_tzif:ident) => $arc_tzif_block:expr,
2311            ARC_POSIX($arc_posix:ident) => $arc_posix_block:expr,
2312        ) => {{
2313            let repr = $repr;
2314            match repr.tag() {
2315                Repr::UTC => $utc,
2316                Repr::UNKNOWN => $unknown,
2317                Repr::FIXED => {
2318                    // SAFETY: We've ensured our pointer tag is correct.
2319                    let $offset = unsafe { repr.get_fixed() };
2320                    $fixed
2321                }
2322                Repr::STATIC_TZIF => {
2323                    // SAFETY: We've ensured our pointer tag is correct.
2324                    let $static_tzif = unsafe { repr.get_static_tzif() };
2325                    $static_tzif_block
2326                }
2327                #[cfg(feature = "alloc")]
2328                Repr::ARC_TZIF => {
2329                    // SAFETY: We've ensured our pointer tag is correct.
2330                    let $arc_tzif = unsafe { repr.get_arc_tzif() };
2331                    $arc_tzif_block
2332                }
2333                #[cfg(feature = "alloc")]
2334                Repr::ARC_POSIX => {
2335                    // SAFETY: We've ensured our pointer tag is correct.
2336                    let $arc_posix = unsafe { repr.get_arc_posix() };
2337                    $arc_posix_block
2338                }
2339                _ => {
2340                    debug_assert!(false, "each: invalid time zone repr tag!");
2341                    // SAFETY: The constructors for `Repr` guarantee that the
2342                    // tag is always one of the values matched above.
2343                    unsafe {
2344                        core::hint::unreachable_unchecked();
2345                    }
2346                }
2347            }
2348        }};
2349    }
2350    pub(super) use each;
2351
2352    /// The internal representation of a `TimeZone`.
2353    ///
2354    /// It has 6 different possible variants: `UTC`, `Etc/Unknown`, fixed
2355    /// offset, `static` TZif, `Arc` TZif or `Arc` POSIX time zone.
2356    ///
2357    /// This design uses pointer tagging so that:
2358    ///
2359    /// * The size of a `TimeZone` stays no bigger than a single word.
2360    /// * In core-only environments, a `TimeZone` can be created from
2361    ///   compile-time TZif data without allocating.
2362    /// * UTC, unknown and fixed offset time zone does not require allocating.
2363    /// * We can still alloc for TZif and POSIX time zones created at runtime.
2364    ///   (Allocating for TZif at runtime is the intended common case, and
2365    ///   corresponds to reading `/usr/share/zoneinfo` entries.)
2366    ///
2367    /// We achieve this through pointer tagging and careful use of a strict
2368    /// provenance polyfill (because of MSRV). We use the lower 4 bits of a
2369    /// pointer to indicate which variant we have. This is sound because we
2370    /// require all types that we allocate for to have a minimum alignment of
2371    /// 8 bytes.
2372    pub(super) struct Repr {
2373        ptr: *const u8,
2374    }
2375
2376    impl Repr {
2377        const BITS: usize = 0b111;
2378        pub(super) const UTC: usize = 1;
2379        pub(super) const UNKNOWN: usize = 2;
2380        pub(super) const FIXED: usize = 3;
2381        pub(super) const STATIC_TZIF: usize = 0;
2382        pub(super) const ARC_TZIF: usize = 4;
2383        pub(super) const ARC_POSIX: usize = 5;
2384
2385        // The minimum alignment required for any heap allocated time zone
2386        // variants. This is related to the number of tags. We have 6 distinct
2387        // values above, which means we need an alignment of at least 6. Since
2388        // alignment must be a power of 2, the smallest possible alignment
2389        // is 8.
2390        const ALIGN: usize = 8;
2391
2392        /// Creates a representation for a `UTC` time zone.
2393        #[inline]
2394        pub(super) const fn utc() -> Repr {
2395            let ptr = without_provenance(Repr::UTC);
2396            Repr { ptr }
2397        }
2398
2399        /// Creates a representation for a `Etc/Unknown` time zone.
2400        #[inline]
2401        pub(super) const fn unknown() -> Repr {
2402            let ptr = without_provenance(Repr::UNKNOWN);
2403            Repr { ptr }
2404        }
2405
2406        /// Creates a representation for a fixed offset time zone.
2407        #[inline]
2408        pub(super) const fn fixed(offset: Offset) -> Repr {
2409            let seconds = offset.seconds();
2410            // OK because offset is in -93599..=93599.
2411            let shifted = match seconds.checked_shl(4) {
    Some(val) => val,
    None => {
        ::core::panicking::panic_fmt(format_args!("offset small enough for left shift by 4 bits"));
    }
}unwrap!(
2412                seconds.checked_shl(4),
2413                "offset small enough for left shift by 4 bits",
2414            );
2415            if !(usize::MAX >= 4_294_967_295) {
    ::core::panicking::panic("assertion failed: usize::MAX >= 4_294_967_295")
};assert!(usize::MAX >= 4_294_967_295);
2416            // usize cast is okay because Jiff requires 32-bit.
2417            let ptr = without_provenance((shifted as usize) | Repr::FIXED);
2418            Repr { ptr }
2419        }
2420
2421        /// Creates a representation for a created-at-compile-time TZif time
2422        /// zone.
2423        ///
2424        /// This can only be correctly called by the `jiff-static` proc macro.
2425        #[inline]
2426        pub(super) const fn static_tzif(
2427            tzif: &'static tzif::MaybeNamedTimeZone,
2428        ) -> Repr {
2429            if !(core::mem::align_of::<tzif::MaybeNamedTimeZone>() >= Repr::ALIGN) {
    ::core::panicking::panic("assertion failed: core::mem::align_of::<tzif::MaybeNamedTimeZone>() >= Repr::ALIGN")
};assert!(
2430                core::mem::align_of::<tzif::MaybeNamedTimeZone>()
2431                    >= Repr::ALIGN
2432            );
2433            let tzif = (tzif as *const tzif::MaybeNamedTimeZone).cast::<u8>();
2434            // We very specifically do no materialize the pointer address here
2435            // because 1) it's UB and 2) the compiler generally prevents. This
2436            // is because in a const context, the specific pointer address
2437            // cannot be relied upon. Yet, we still want to do pointer tagging.
2438            //
2439            // Thankfully, this is the only variant that is a pointer that
2440            // we want to create in a const context. So we just make this
2441            // variant's tag `0`, and thus, no explicit pointer tagging is
2442            // required. (Because we ensure the alignment is at least 4, and
2443            // thus the least significant 3 bits are 0.)
2444            //
2445            // If this ends up not working out or if we need to support
2446            // another `static` variant, then we could perhaps to pointer
2447            // tagging with pointer arithmetic (like what the `tagged-pointer`
2448            // crate does). I haven't tried it though and I'm unclear if it
2449            // work.
2450            Repr { ptr: tzif }
2451        }
2452
2453        /// Creates a representation for a TZif time zone.
2454        #[cfg(feature = "alloc")]
2455        #[inline]
2456        pub(super) fn arc_tzif(tzif: Arc<tzif::MaybeNamedTimeZone>) -> Repr {
2457            if !(core::mem::align_of::<tzif::MaybeNamedTimeZone>() >= Repr::ALIGN) {
    ::core::panicking::panic("assertion failed: core::mem::align_of::<tzif::MaybeNamedTimeZone>() >= Repr::ALIGN")
};assert!(
2458                core::mem::align_of::<tzif::MaybeNamedTimeZone>()
2459                    >= Repr::ALIGN
2460            );
2461            let tzif = Arc::into_raw(tzif).cast::<u8>();
2462            if !(tzif.addr() % 4 == 0) {
    ::core::panicking::panic("assertion failed: tzif.addr() % 4 == 0")
};assert!(tzif.addr() % 4 == 0);
2463            let ptr = tzif.map_addr(|addr| addr | Repr::ARC_TZIF);
2464            Repr { ptr }
2465        }
2466
2467        /// Creates a representation for a POSIX time zone.
2468        #[cfg(feature = "alloc")]
2469        #[inline]
2470        pub(super) fn arc_posix(posix_tz: Arc<posix::TimeZone>) -> Repr {
2471            if !(core::mem::align_of::<posix::TimeZone>() >= Repr::ALIGN) {
    ::core::panicking::panic("assertion failed: core::mem::align_of::<posix::TimeZone>() >= Repr::ALIGN")
};assert!(core::mem::align_of::<posix::TimeZone>() >= Repr::ALIGN);
2472            let posix_tz = Arc::into_raw(posix_tz).cast::<u8>();
2473            if !(posix_tz.addr() % 4 == 0) {
    ::core::panicking::panic("assertion failed: posix_tz.addr() % 4 == 0")
};assert!(posix_tz.addr() % 4 == 0);
2474            let ptr = posix_tz.map_addr(|addr| addr | Repr::ARC_POSIX);
2475            Repr { ptr }
2476        }
2477
2478        /// Gets the offset representation.
2479        ///
2480        /// # Safety
2481        ///
2482        /// Callers must ensure that the pointer tag is `FIXED`.
2483        #[inline]
2484        pub(super) unsafe fn get_fixed(&self) -> Offset {
2485            #[allow(unstable_name_collisions)]
2486            let addr = self.ptr.addr();
2487            // NOTE: Because of sign extension, we need to cast to `i32`
2488            // before shifting.
2489            Offset::from_seconds_unchecked((addr as i32) >> 4)
2490        }
2491
2492        /// Returns true if and only if this representation corresponds to the
2493        /// `Etc/Unknown` time zone.
2494        #[inline]
2495        pub(super) fn is_unknown(&self) -> bool {
2496            self.tag() == Repr::UNKNOWN
2497        }
2498
2499        /// Gets the static TZif representation.
2500        ///
2501        /// # Safety
2502        ///
2503        /// Callers must ensure that the pointer tag is `STATIC_TZIF`.
2504        #[inline]
2505        pub(super) unsafe fn get_static_tzif(
2506            &self,
2507        ) -> &'static tzif::MaybeNamedTimeZone {
2508            #[allow(unstable_name_collisions)]
2509            let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2510            // SAFETY: Getting a `STATIC_TZIF` tag is only possible when
2511            // `self.ptr` was constructed from a valid and aligned (to at least
2512            // 4 bytes) `&TzifStatic` borrow. Which must be guaranteed by the
2513            // caller. We've also removed the tag bits above, so we must now
2514            // have the original pointer.
2515            unsafe { &*ptr.cast::<tzif::MaybeNamedTimeZone>() }
2516        }
2517
2518        /// Gets the `Arc` TZif representation.
2519        ///
2520        /// # Safety
2521        ///
2522        /// Callers must ensure that the pointer tag is `ARC_TZIF`.
2523        #[cfg(feature = "alloc")]
2524        #[inline]
2525        pub(super) unsafe fn get_arc_tzif<'a>(
2526            &'a self,
2527        ) -> &'a tzif::MaybeNamedTimeZone {
2528            let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2529            // SAFETY: Getting a `ARC_TZIF` tag is only possible when
2530            // `self.ptr` was constructed from a valid and aligned (to at least
2531            // 4 bytes) `Arc<tzif::MaybeNamedTimeZone>`. We've removed the tag
2532            // bits above, so we must now have the original pointer.
2533            let arc = ManuallyDrop::new(unsafe {
2534                Arc::from_raw(ptr.cast::<tzif::MaybeNamedTimeZone>())
2535            });
2536            // SAFETY: The lifetime of the pointer returned is always
2537            // valid as long as the strong count on `arc` is at least
2538            // 1. Since the lifetime is no longer than `Repr` itself,
2539            // and a `Repr` being alive implies there is at least 1
2540            // for the strong `Arc` count, it follows that the lifetime
2541            // returned here is correct.
2542            unsafe { &*Arc::as_ptr(&arc) }
2543        }
2544
2545        /// Gets the `Arc` POSIX time zone representation.
2546        ///
2547        /// # Safety
2548        ///
2549        /// Callers must ensure that the pointer tag is `ARC_POSIX`.
2550        #[cfg(feature = "alloc")]
2551        #[inline]
2552        pub(super) unsafe fn get_arc_posix<'a>(
2553            &'a self,
2554        ) -> &'a posix::TimeZone {
2555            let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2556            // SAFETY: Getting a `ARC_POSIX` tag is only possible when
2557            // `self.ptr` was constructed from a valid and aligned (to at least
2558            // 4 bytes) `Arc<jcore::tz::posix::TimeZone>`. We've removed the
2559            // tag bits above, so we must now have the original pointer.
2560            let arc = ManuallyDrop::new(unsafe {
2561                Arc::from_raw(ptr.cast::<posix::TimeZone>())
2562            });
2563            // SAFETY: The lifetime of the pointer returned is always
2564            // valid as long as the strong count on `arc` is at least
2565            // 1. Since the lifetime is no longer than `Repr` itself,
2566            // and a `Repr` being alive implies there is at least 1
2567            // for the strong `Arc` count, it follows that the lifetime
2568            // returned here is correct.
2569            unsafe { &*Arc::as_ptr(&arc) }
2570        }
2571
2572        /// Returns the tag on the representation's pointer.
2573        ///
2574        /// The value is guaranteed to be one of the constant tag values.
2575        #[inline]
2576        pub(super) fn tag(&self) -> usize {
2577            #[allow(unstable_name_collisions)]
2578            {
2579                self.ptr.addr() & Repr::BITS
2580            }
2581        }
2582
2583        /// Returns a dumb copy of this representation.
2584        ///
2585        /// # Safety
2586        ///
2587        /// Callers must ensure that this representation's tag is UTC,
2588        /// UNKNOWN, FIXED or STATIC_TZIF.
2589        ///
2590        /// Namely, this specifically does not increment the ref count for
2591        /// the `Arc` pointers when the tag is `ARC_TZIF` or `ARC_POSIX`.
2592        /// This means that incorrect usage of this routine can lead to
2593        /// use-after-free.
2594        ///
2595        /// NOTE: It would be nice if we could make this `copy` routine safe,
2596        /// or at least panic if it's misused. But to do that, you need to know
2597        /// the time zone variant. And to know the time zone variant, you need
2598        /// to "look" at the tag in the pointer. And looking at the address of
2599        /// a pointer in a `const` context is precarious.
2600        #[inline]
2601        pub(super) const unsafe fn copy(&self) -> Repr {
2602            Repr { ptr: self.ptr }
2603        }
2604    }
2605
2606    // SAFETY: We use automatic reference counting.
2607    unsafe impl Send for Repr {}
2608    // SAFETY: We don't use an interior mutability and otherwise don't permit
2609    // any kind of mutation (other than for an `Arc` managing its ref counts)
2610    // of a `Repr`.
2611    unsafe impl Sync for Repr {}
2612
2613    impl core::fmt::Debug for Repr {
2614        fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2615            {
    let repr = self;
    match repr.tag() {
        Repr::UTC => f.write_str("UTC"),
        Repr::UNKNOWN => f.write_str("Etc/Unknown"),
        Repr::FIXED => {
            let offset = unsafe { repr.get_fixed() };
            core::fmt::Debug::fmt(&offset, f)
        }
        Repr::STATIC_TZIF => {
            let tzif = unsafe { repr.get_static_tzif() };
            {
                let field = tzif.name().unwrap_or("Local");
                f.debug_tuple("TZif").field(&field).finish()
            }
        }Repr::ARC_TZIF => {
            let tzif = unsafe { repr.get_arc_tzif() };
            {
                let field = tzif.name().unwrap_or("Local");
                f.debug_tuple("TZif").field(&field).finish()
            }
        }Repr::ARC_POSIX => {
            let posix = unsafe { repr.get_arc_posix() };
            {
                f.write_str("Posix(")?;
                core::fmt::Display::fmt(&crate::tz::posix::TimeZoneFormatter(posix),
                        f)?;
                f.write_str(")")
            }
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}each! {
2616                self,
2617                UTC => f.write_str("UTC"),
2618                UNKNOWN => f.write_str("Etc/Unknown"),
2619                FIXED(offset) => core::fmt::Debug::fmt(&offset, f),
2620                STATIC_TZIF(tzif) => {
2621                    // The full debug output is a bit much, so constrain it.
2622                    let field = tzif.name().unwrap_or("Local");
2623                    f.debug_tuple("TZif").field(&field).finish()
2624                },
2625                ARC_TZIF(tzif) => {
2626                    // The full debug output is a bit much, so constrain it.
2627                    let field = tzif.name().unwrap_or("Local");
2628                    f.debug_tuple("TZif").field(&field).finish()
2629                },
2630                ARC_POSIX(posix) => {
2631                    f.write_str("Posix(")?;
2632                    core::fmt::Display::fmt(
2633                        &crate::tz::posix::TimeZoneFormatter(posix),
2634                        f,
2635                    )?;
2636                    f.write_str(")")
2637                },
2638            }
2639        }
2640    }
2641
2642    impl Clone for Repr {
2643        #[inline]
2644        fn clone(&self) -> Repr {
2645            // This `match` is written in an exhaustive fashion so that if
2646            // a new tag is added, it should be explicitly considered here.
2647            match self.tag() {
2648                // These are all `Copy` and can just be memcpy'd as-is.
2649                Repr::UTC
2650                | Repr::UNKNOWN
2651                | Repr::FIXED
2652                | Repr::STATIC_TZIF => Repr { ptr: self.ptr },
2653                #[cfg(feature = "alloc")]
2654                Repr::ARC_TZIF => {
2655                    let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2656                    // SAFETY: Getting a `ARC_TZIF` tag is only possible when
2657                    // `self.ptr` was constructed from a valid and aligned (to
2658                    // at least 4 bytes) `Arc<tzif::MaybeNamedTimeZone>`. We've
2659                    // removed the tag bits above, so we must now have the
2660                    // original pointer.
2661                    unsafe {
2662                        Arc::increment_strong_count(
2663                            ptr.cast::<tzif::MaybeNamedTimeZone>(),
2664                        );
2665                    }
2666                    Repr { ptr: self.ptr }
2667                }
2668                #[cfg(feature = "alloc")]
2669                Repr::ARC_POSIX => {
2670                    let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2671                    // SAFETY: Getting a `ARC_POSIX` tag is only possible when
2672                    // `self.ptr` was constructed from a valid and aligned (to
2673                    // at least 4 bytes) `Arc<jcore::tz::posix::TimeZone>`.
2674                    // We've removed the tag bits above, so we must now have
2675                    // the original pointer.
2676                    unsafe {
2677                        Arc::increment_strong_count(
2678                            ptr.cast::<posix::TimeZone>(),
2679                        );
2680                    }
2681                    Repr { ptr: self.ptr }
2682                }
2683                _ => {
2684                    if true {
    if !false {
        {
            ::core::panicking::panic_fmt(format_args!("clone: invalid time zone repr tag!"));
        }
    };
};debug_assert!(false, "clone: invalid time zone repr tag!");
2685                    // SAFETY: The constructors for `Repr` guarantee that the
2686                    // tag is always one of the values matched above.
2687                    unsafe {
2688                        core::hint::unreachable_unchecked();
2689                    }
2690                }
2691            }
2692        }
2693    }
2694
2695    impl Drop for Repr {
2696        #[inline]
2697        fn drop(&mut self) {
2698            // This `match` is written in an exhaustive fashion so that if
2699            // a new tag is added, it should be explicitly considered here.
2700            match self.tag() {
2701                // These are all `Copy` and have no destructor.
2702                Repr::UTC
2703                | Repr::UNKNOWN
2704                | Repr::FIXED
2705                | Repr::STATIC_TZIF => {}
2706                #[cfg(feature = "alloc")]
2707                Repr::ARC_TZIF => {
2708                    let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2709                    // SAFETY: Getting a `ARC_TZIF` tag is only
2710                    // possible when `self.ptr` was constructed from
2711                    // a valid and aligned (to at least 4 bytes)
2712                    // `Arc<tzif::MaybeNamedTimeZone>`. We've removed the tag
2713                    // bits above, so we must now have the original
2714                    // pointer.
2715                    unsafe {
2716                        Arc::decrement_strong_count(
2717                            ptr.cast::<tzif::MaybeNamedTimeZone>(),
2718                        );
2719                    }
2720                }
2721                #[cfg(feature = "alloc")]
2722                Repr::ARC_POSIX => {
2723                    let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2724                    // SAFETY: Getting a `ARC_POSIX` tag is only possible when
2725                    // `self.ptr` was constructed from a valid and aligned (to
2726                    // at least 4 bytes) `Arc<jcore::tz::posix::TimeZone>`.
2727                    // We've removed the tag bits above, so we must now have
2728                    // the original pointer.
2729                    unsafe {
2730                        Arc::decrement_strong_count(
2731                            ptr.cast::<posix::TimeZone>(),
2732                        );
2733                    }
2734                }
2735                _ => {
2736                    if true {
    if !false {
        {
            ::core::panicking::panic_fmt(format_args!("drop: invalid time zone repr tag!"));
        }
    };
};debug_assert!(false, "drop: invalid time zone repr tag!");
2737                    // SAFETY: The constructors for `Repr` guarantee that the
2738                    // tag is always one of the values matched above.
2739                    unsafe {
2740                        core::hint::unreachable_unchecked();
2741                    }
2742                }
2743            }
2744        }
2745    }
2746
2747    impl Eq for Repr {}
2748
2749    impl PartialEq for Repr {
2750        fn eq(&self, other: &Repr) -> bool {
2751            fn is_tzif_eq(
2752                tzif1: &tzif::MaybeNamedTimeZone,
2753                tzif2: &tzif::MaybeNamedTimeZone,
2754            ) -> bool {
2755                // We check the underlying TZ itself (which is
2756                // just done via a checksum) to catch cases where
2757                // two different TimeZone values with the same
2758                // name came from different databases. This is
2759                // also important for cases when neither time
2760                // zone has an IANA name, in which case, we just
2761                // rely on the checksum.
2762                if tzif1.tz() != tzif2.tz() {
2763                    return false;
2764                }
2765                primary_name_fallback(tzif1) == primary_name_fallback(tzif2)
2766            }
2767
2768            fn primary_name_fallback(
2769                tzif: &tzif::MaybeNamedTimeZone,
2770            ) -> Option<&str> {
2771                super::find_primary_iana_name(tzif.name()?)
2772                    .or_else(|| tzif.name())
2773            }
2774
2775            if self.tag() != other.tag() {
2776                return false;
2777            }
2778            {
    let repr = self;
    match repr.tag() {
        Repr::UTC => true,
        Repr::UNKNOWN => true,
        Repr::FIXED => {
            let offset = unsafe { repr.get_fixed() };
            offset == unsafe { other.get_fixed() }
        }
        Repr::STATIC_TZIF => {
            let tzif1 = unsafe { repr.get_static_tzif() };
            {
                let tzif2 = unsafe { other.get_static_tzif() };
                is_tzif_eq(tzif1, tzif2)
            }
        }Repr::ARC_TZIF => {
            let tzif1 = unsafe { repr.get_arc_tzif() };
            {
                let tzif2 = unsafe { other.get_arc_tzif() };
                is_tzif_eq(tzif1, tzif2)
            }
        }Repr::ARC_POSIX => {
            let posix = unsafe { repr.get_arc_posix() };
            posix == unsafe { other.get_arc_posix() }
        }
        _ => {
            if true {
                if !false {
                    {
                        ::core::panicking::panic_fmt(format_args!("each: invalid time zone repr tag!"));
                    }
                };
            };
            unsafe { core::hint::unreachable_unchecked(); }
        }
    }
}each! {
2779                self,
2780                UTC => true,
2781                UNKNOWN => true,
2782                // SAFETY: OK, because we know the tags are equivalent and
2783                // `self` has a `FIXED` tag.
2784                FIXED(offset) => offset == unsafe { other.get_fixed() },
2785                STATIC_TZIF(tzif1) => {
2786                    // SAFETY: OK, because we know the tags are equivalent and
2787                    // `self` has a `STATIC_TZIF` tag.
2788                    let tzif2 = unsafe { other.get_static_tzif() };
2789                    is_tzif_eq(tzif1, tzif2)
2790                },
2791                ARC_TZIF(tzif1) => {
2792                    // SAFETY: OK, because we know the tags are equivalent and
2793                    // `self` has an `ARC_TZIF` tag.
2794                    let tzif2 = unsafe { other.get_arc_tzif() };
2795                    is_tzif_eq(tzif1, tzif2)
2796                },
2797                // SAFETY: OK, because we know the tags are equivalent and
2798                // `self` has an `ARC_POSIX` tag.
2799                ARC_POSIX(posix) => posix == unsafe { other.get_arc_posix() },
2800            }
2801        }
2802    }
2803
2804    #[cfg(feature = "defmt")]
2805    impl defmt::Format for Repr {
2806        fn format(&self, f: defmt::Formatter) {
2807            each! {
2808                self,
2809                UTC => defmt::write!(f, "UTC"),
2810                UNKNOWN => defmt::write!(f, "Etc/Unknown"),
2811                FIXED(offset) => defmt::write!(f, "{}", offset),
2812                STATIC_TZIF(tzif) => {
2813                    // The full debug output is a bit much, so constrain it.
2814                    let field = tzif.name().unwrap_or("Local");
2815                    defmt::write!(f, "TZif({=str})", field)
2816                },
2817                ARC_TZIF(tzif) => {
2818                    // The full debug output is a bit much, so constrain it.
2819                    let field = tzif.name().unwrap_or("Local");
2820                    defmt::write!(f, "TZif({=str})", field)
2821                },
2822                ARC_POSIX(posix) => {
2823                    defmt::write!(
2824                        f,
2825                        "Posix({})",
2826                        crate::tz::posix::TimeZoneFormatter(&posix),
2827                    )
2828                },
2829            }
2830        }
2831    }
2832}
2833
2834#[cfg(test)]
2835mod tests {
2836    #[cfg(feature = "alloc")]
2837    use crate::tz::testdata::TzifTestFile;
2838    use crate::{civil::date, tz::offset};
2839
2840    use super::*;
2841
2842    fn unambiguous(offset_hours: i8) -> AmbiguousOffset {
2843        let offset = offset(offset_hours);
2844        o_unambiguous(offset)
2845    }
2846
2847    fn gap(
2848        earlier_offset_hours: i8,
2849        later_offset_hours: i8,
2850    ) -> AmbiguousOffset {
2851        let earlier = offset(earlier_offset_hours);
2852        let later = offset(later_offset_hours);
2853        o_gap(earlier, later)
2854    }
2855
2856    fn fold(
2857        earlier_offset_hours: i8,
2858        later_offset_hours: i8,
2859    ) -> AmbiguousOffset {
2860        let earlier = offset(earlier_offset_hours);
2861        let later = offset(later_offset_hours);
2862        o_fold(earlier, later)
2863    }
2864
2865    fn o_unambiguous(offset: Offset) -> AmbiguousOffset {
2866        AmbiguousOffset::Unambiguous { offset }
2867    }
2868
2869    fn o_gap(earlier: Offset, later: Offset) -> AmbiguousOffset {
2870        AmbiguousOffset::Gap { before: earlier, after: later }
2871    }
2872
2873    fn o_fold(earlier: Offset, later: Offset) -> AmbiguousOffset {
2874        AmbiguousOffset::Fold { before: earlier, after: later }
2875    }
2876
2877    #[cfg(feature = "alloc")]
2878    #[test]
2879    fn time_zone_tzif_to_ambiguous_timestamp() {
2880        let tests: &[(&str, &[_])] = &[
2881            (
2882                "America/New_York",
2883                &[
2884                    ((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
2885                    ((2024, 3, 10, 1, 59, 59, 999_999_999), unambiguous(-5)),
2886                    ((2024, 3, 10, 2, 0, 0, 0), gap(-5, -4)),
2887                    ((2024, 3, 10, 2, 59, 59, 999_999_999), gap(-5, -4)),
2888                    ((2024, 3, 10, 3, 0, 0, 0), unambiguous(-4)),
2889                    ((2024, 11, 3, 0, 59, 59, 999_999_999), unambiguous(-4)),
2890                    ((2024, 11, 3, 1, 0, 0, 0), fold(-4, -5)),
2891                    ((2024, 11, 3, 1, 59, 59, 999_999_999), fold(-4, -5)),
2892                    ((2024, 11, 3, 2, 0, 0, 0), unambiguous(-5)),
2893                ],
2894            ),
2895            (
2896                "Europe/Dublin",
2897                &[
2898                    ((1970, 1, 1, 0, 0, 0, 0), unambiguous(1)),
2899                    ((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
2900                    ((2024, 3, 31, 1, 0, 0, 0), gap(0, 1)),
2901                    ((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 1)),
2902                    ((2024, 3, 31, 2, 0, 0, 0), unambiguous(1)),
2903                    ((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(1)),
2904                    ((2024, 10, 27, 1, 0, 0, 0), fold(1, 0)),
2905                    ((2024, 10, 27, 1, 59, 59, 999_999_999), fold(1, 0)),
2906                    ((2024, 10, 27, 2, 0, 0, 0), unambiguous(0)),
2907                ],
2908            ),
2909            (
2910                "Australia/Tasmania",
2911                &[
2912                    ((1970, 1, 1, 11, 0, 0, 0), unambiguous(11)),
2913                    ((2024, 4, 7, 1, 59, 59, 999_999_999), unambiguous(11)),
2914                    ((2024, 4, 7, 2, 0, 0, 0), fold(11, 10)),
2915                    ((2024, 4, 7, 2, 59, 59, 999_999_999), fold(11, 10)),
2916                    ((2024, 4, 7, 3, 0, 0, 0), unambiguous(10)),
2917                    ((2024, 10, 6, 1, 59, 59, 999_999_999), unambiguous(10)),
2918                    ((2024, 10, 6, 2, 0, 0, 0), gap(10, 11)),
2919                    ((2024, 10, 6, 2, 59, 59, 999_999_999), gap(10, 11)),
2920                    ((2024, 10, 6, 3, 0, 0, 0), unambiguous(11)),
2921                ],
2922            ),
2923            (
2924                "Antarctica/Troll",
2925                &[
2926                    ((1970, 1, 1, 0, 0, 0, 0), unambiguous(0)),
2927                    // test the gap
2928                    ((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
2929                    ((2024, 3, 31, 1, 0, 0, 0), gap(0, 2)),
2930                    ((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 2)),
2931                    // still in the gap!
2932                    ((2024, 3, 31, 2, 0, 0, 0), gap(0, 2)),
2933                    ((2024, 3, 31, 2, 59, 59, 999_999_999), gap(0, 2)),
2934                    // finally out
2935                    ((2024, 3, 31, 3, 0, 0, 0), unambiguous(2)),
2936                    // test the fold
2937                    ((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(2)),
2938                    ((2024, 10, 27, 1, 0, 0, 0), fold(2, 0)),
2939                    ((2024, 10, 27, 1, 59, 59, 999_999_999), fold(2, 0)),
2940                    // still in the fold!
2941                    ((2024, 10, 27, 2, 0, 0, 0), fold(2, 0)),
2942                    ((2024, 10, 27, 2, 59, 59, 999_999_999), fold(2, 0)),
2943                    // finally out
2944                    ((2024, 10, 27, 3, 0, 0, 0), unambiguous(0)),
2945                ],
2946            ),
2947            (
2948                "America/St_Johns",
2949                &[
2950                    (
2951                        (1969, 12, 31, 20, 30, 0, 0),
2952                        o_unambiguous(-Offset::hms(3, 30, 0)),
2953                    ),
2954                    (
2955                        (2024, 3, 10, 1, 59, 59, 999_999_999),
2956                        o_unambiguous(-Offset::hms(3, 30, 0)),
2957                    ),
2958                    (
2959                        (2024, 3, 10, 2, 0, 0, 0),
2960                        o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
2961                    ),
2962                    (
2963                        (2024, 3, 10, 2, 59, 59, 999_999_999),
2964                        o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
2965                    ),
2966                    (
2967                        (2024, 3, 10, 3, 0, 0, 0),
2968                        o_unambiguous(-Offset::hms(2, 30, 0)),
2969                    ),
2970                    (
2971                        (2024, 11, 3, 0, 59, 59, 999_999_999),
2972                        o_unambiguous(-Offset::hms(2, 30, 0)),
2973                    ),
2974                    (
2975                        (2024, 11, 3, 1, 0, 0, 0),
2976                        o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
2977                    ),
2978                    (
2979                        (2024, 11, 3, 1, 59, 59, 999_999_999),
2980                        o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
2981                    ),
2982                    (
2983                        (2024, 11, 3, 2, 0, 0, 0),
2984                        o_unambiguous(-Offset::hms(3, 30, 0)),
2985                    ),
2986                ],
2987            ),
2988            // This time zone has an interesting transition where it jumps
2989            // backwards a full day at 1867-10-19T15:30:00.
2990            (
2991                "America/Sitka",
2992                &[
2993                    ((1969, 12, 31, 16, 0, 0, 0), unambiguous(-8)),
2994                    (
2995                        (-9999, 1, 2, 16, 58, 46, 0),
2996                        o_unambiguous(Offset::hms(14, 58, 47)),
2997                    ),
2998                    (
2999                        (1867, 10, 18, 15, 29, 59, 0),
3000                        o_unambiguous(Offset::hms(14, 58, 47)),
3001                    ),
3002                    (
3003                        (1867, 10, 18, 15, 30, 0, 0),
3004                        // A fold of 24 hours!!!
3005                        o_fold(
3006                            Offset::hms(14, 58, 47),
3007                            -Offset::hms(9, 1, 13),
3008                        ),
3009                    ),
3010                    (
3011                        (1867, 10, 19, 15, 29, 59, 999_999_999),
3012                        // Still in the fold...
3013                        o_fold(
3014                            Offset::hms(14, 58, 47),
3015                            -Offset::hms(9, 1, 13),
3016                        ),
3017                    ),
3018                    (
3019                        (1867, 10, 19, 15, 30, 0, 0),
3020                        // Finally out.
3021                        o_unambiguous(-Offset::hms(9, 1, 13)),
3022                    ),
3023                ],
3024            ),
3025            // As with to_datetime, we test every possible transition
3026            // point here since this time zone has a small number of them.
3027            (
3028                "Pacific/Honolulu",
3029                &[
3030                    (
3031                        (1896, 1, 13, 11, 59, 59, 0),
3032                        o_unambiguous(-Offset::hms(10, 31, 26)),
3033                    ),
3034                    (
3035                        (1896, 1, 13, 12, 0, 0, 0),
3036                        o_gap(
3037                            -Offset::hms(10, 31, 26),
3038                            -Offset::hms(10, 30, 0),
3039                        ),
3040                    ),
3041                    (
3042                        (1896, 1, 13, 12, 1, 25, 0),
3043                        o_gap(
3044                            -Offset::hms(10, 31, 26),
3045                            -Offset::hms(10, 30, 0),
3046                        ),
3047                    ),
3048                    (
3049                        (1896, 1, 13, 12, 1, 26, 0),
3050                        o_unambiguous(-Offset::hms(10, 30, 0)),
3051                    ),
3052                    (
3053                        (1933, 4, 30, 1, 59, 59, 0),
3054                        o_unambiguous(-Offset::hms(10, 30, 0)),
3055                    ),
3056                    (
3057                        (1933, 4, 30, 2, 0, 0, 0),
3058                        o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
3059                    ),
3060                    (
3061                        (1933, 4, 30, 2, 59, 59, 0),
3062                        o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
3063                    ),
3064                    (
3065                        (1933, 4, 30, 3, 0, 0, 0),
3066                        o_unambiguous(-Offset::hms(9, 30, 0)),
3067                    ),
3068                    (
3069                        (1933, 5, 21, 10, 59, 59, 0),
3070                        o_unambiguous(-Offset::hms(9, 30, 0)),
3071                    ),
3072                    (
3073                        (1933, 5, 21, 11, 0, 0, 0),
3074                        o_fold(
3075                            -Offset::hms(9, 30, 0),
3076                            -Offset::hms(10, 30, 0),
3077                        ),
3078                    ),
3079                    (
3080                        (1933, 5, 21, 11, 59, 59, 0),
3081                        o_fold(
3082                            -Offset::hms(9, 30, 0),
3083                            -Offset::hms(10, 30, 0),
3084                        ),
3085                    ),
3086                    (
3087                        (1933, 5, 21, 12, 0, 0, 0),
3088                        o_unambiguous(-Offset::hms(10, 30, 0)),
3089                    ),
3090                    (
3091                        (1942, 2, 9, 1, 59, 59, 0),
3092                        o_unambiguous(-Offset::hms(10, 30, 0)),
3093                    ),
3094                    (
3095                        (1942, 2, 9, 2, 0, 0, 0),
3096                        o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
3097                    ),
3098                    (
3099                        (1942, 2, 9, 2, 59, 59, 0),
3100                        o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
3101                    ),
3102                    (
3103                        (1942, 2, 9, 3, 0, 0, 0),
3104                        o_unambiguous(-Offset::hms(9, 30, 0)),
3105                    ),
3106                    (
3107                        (1945, 8, 14, 13, 29, 59, 0),
3108                        o_unambiguous(-Offset::hms(9, 30, 0)),
3109                    ),
3110                    (
3111                        (1945, 8, 14, 13, 30, 0, 0),
3112                        o_unambiguous(-Offset::hms(9, 30, 0)),
3113                    ),
3114                    (
3115                        (1945, 8, 14, 13, 30, 1, 0),
3116                        o_unambiguous(-Offset::hms(9, 30, 0)),
3117                    ),
3118                    (
3119                        (1945, 9, 30, 0, 59, 59, 0),
3120                        o_unambiguous(-Offset::hms(9, 30, 0)),
3121                    ),
3122                    (
3123                        (1945, 9, 30, 1, 0, 0, 0),
3124                        o_fold(
3125                            -Offset::hms(9, 30, 0),
3126                            -Offset::hms(10, 30, 0),
3127                        ),
3128                    ),
3129                    (
3130                        (1945, 9, 30, 1, 59, 59, 0),
3131                        o_fold(
3132                            -Offset::hms(9, 30, 0),
3133                            -Offset::hms(10, 30, 0),
3134                        ),
3135                    ),
3136                    (
3137                        (1945, 9, 30, 2, 0, 0, 0),
3138                        o_unambiguous(-Offset::hms(10, 30, 0)),
3139                    ),
3140                    (
3141                        (1947, 6, 8, 1, 59, 59, 0),
3142                        o_unambiguous(-Offset::hms(10, 30, 0)),
3143                    ),
3144                    (
3145                        (1947, 6, 8, 2, 0, 0, 0),
3146                        o_gap(-Offset::hms(10, 30, 0), -offset(10)),
3147                    ),
3148                    (
3149                        (1947, 6, 8, 2, 29, 59, 0),
3150                        o_gap(-Offset::hms(10, 30, 0), -offset(10)),
3151                    ),
3152                    ((1947, 6, 8, 2, 30, 0, 0), unambiguous(-10)),
3153                ],
3154            ),
3155        ];
3156        for &(tzname, datetimes_to_ambiguous) in tests {
3157            let test_file = TzifTestFile::get(tzname);
3158            let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
3159            for &(datetime, ambiguous_kind) in datetimes_to_ambiguous {
3160                let (year, month, day, hour, min, sec, nano) = datetime;
3161                let dt = date(year, month, day).at(hour, min, sec, nano);
3162                let got = tz.to_ambiguous_zoned_datetime(dt);
3163                assert_eq!(
3164                    got.offset(),
3165                    ambiguous_kind,
3166                    "\nTZ: {tzname}\ndatetime: \
3167                     {year:04}-{month:02}-{day:02}T\
3168                     {hour:02}:{min:02}:{sec:02}.{nano:09}",
3169                );
3170            }
3171        }
3172    }
3173
3174    #[cfg(feature = "alloc")]
3175    #[test]
3176    fn time_zone_tzif_to_datetime() {
3177        let o = |hours| offset(hours);
3178        let tests: &[(&str, &[_])] = &[
3179            (
3180                "America/New_York",
3181                &[
3182                    ((0, 0), o(-5), "EST", (1969, 12, 31, 19, 0, 0, 0)),
3183                    (
3184                        (1710052200, 0),
3185                        o(-5),
3186                        "EST",
3187                        (2024, 3, 10, 1, 30, 0, 0),
3188                    ),
3189                    (
3190                        (1710053999, 999_999_999),
3191                        o(-5),
3192                        "EST",
3193                        (2024, 3, 10, 1, 59, 59, 999_999_999),
3194                    ),
3195                    ((1710054000, 0), o(-4), "EDT", (2024, 3, 10, 3, 0, 0, 0)),
3196                    (
3197                        (1710055800, 0),
3198                        o(-4),
3199                        "EDT",
3200                        (2024, 3, 10, 3, 30, 0, 0),
3201                    ),
3202                    ((1730610000, 0), o(-4), "EDT", (2024, 11, 3, 1, 0, 0, 0)),
3203                    (
3204                        (1730611800, 0),
3205                        o(-4),
3206                        "EDT",
3207                        (2024, 11, 3, 1, 30, 0, 0),
3208                    ),
3209                    (
3210                        (1730613599, 999_999_999),
3211                        o(-4),
3212                        "EDT",
3213                        (2024, 11, 3, 1, 59, 59, 999_999_999),
3214                    ),
3215                    ((1730613600, 0), o(-5), "EST", (2024, 11, 3, 1, 0, 0, 0)),
3216                    (
3217                        (1730615400, 0),
3218                        o(-5),
3219                        "EST",
3220                        (2024, 11, 3, 1, 30, 0, 0),
3221                    ),
3222                ],
3223            ),
3224            (
3225                "Australia/Tasmania",
3226                &[
3227                    ((0, 0), o(11), "AEDT", (1970, 1, 1, 11, 0, 0, 0)),
3228                    (
3229                        (1728142200, 0),
3230                        o(10),
3231                        "AEST",
3232                        (2024, 10, 6, 1, 30, 0, 0),
3233                    ),
3234                    (
3235                        (1728143999, 999_999_999),
3236                        o(10),
3237                        "AEST",
3238                        (2024, 10, 6, 1, 59, 59, 999_999_999),
3239                    ),
3240                    (
3241                        (1728144000, 0),
3242                        o(11),
3243                        "AEDT",
3244                        (2024, 10, 6, 3, 0, 0, 0),
3245                    ),
3246                    (
3247                        (1728145800, 0),
3248                        o(11),
3249                        "AEDT",
3250                        (2024, 10, 6, 3, 30, 0, 0),
3251                    ),
3252                    ((1712415600, 0), o(11), "AEDT", (2024, 4, 7, 2, 0, 0, 0)),
3253                    (
3254                        (1712417400, 0),
3255                        o(11),
3256                        "AEDT",
3257                        (2024, 4, 7, 2, 30, 0, 0),
3258                    ),
3259                    (
3260                        (1712419199, 999_999_999),
3261                        o(11),
3262                        "AEDT",
3263                        (2024, 4, 7, 2, 59, 59, 999_999_999),
3264                    ),
3265                    ((1712419200, 0), o(10), "AEST", (2024, 4, 7, 2, 0, 0, 0)),
3266                    (
3267                        (1712421000, 0),
3268                        o(10),
3269                        "AEST",
3270                        (2024, 4, 7, 2, 30, 0, 0),
3271                    ),
3272                ],
3273            ),
3274            // Pacific/Honolulu is small eough that we just test every
3275            // possible instant before, at and after each transition.
3276            (
3277                "Pacific/Honolulu",
3278                &[
3279                    (
3280                        (-2334101315, 0),
3281                        -Offset::hms(10, 31, 26),
3282                        "LMT",
3283                        (1896, 1, 13, 11, 59, 59, 0),
3284                    ),
3285                    (
3286                        (-2334101314, 0),
3287                        -Offset::hms(10, 30, 0),
3288                        "HST",
3289                        (1896, 1, 13, 12, 1, 26, 0),
3290                    ),
3291                    (
3292                        (-2334101313, 0),
3293                        -Offset::hms(10, 30, 0),
3294                        "HST",
3295                        (1896, 1, 13, 12, 1, 27, 0),
3296                    ),
3297                    (
3298                        (-1157283001, 0),
3299                        -Offset::hms(10, 30, 0),
3300                        "HST",
3301                        (1933, 4, 30, 1, 59, 59, 0),
3302                    ),
3303                    (
3304                        (-1157283000, 0),
3305                        -Offset::hms(9, 30, 0),
3306                        "HDT",
3307                        (1933, 4, 30, 3, 0, 0, 0),
3308                    ),
3309                    (
3310                        (-1157282999, 0),
3311                        -Offset::hms(9, 30, 0),
3312                        "HDT",
3313                        (1933, 4, 30, 3, 0, 1, 0),
3314                    ),
3315                    (
3316                        (-1155436201, 0),
3317                        -Offset::hms(9, 30, 0),
3318                        "HDT",
3319                        (1933, 5, 21, 11, 59, 59, 0),
3320                    ),
3321                    (
3322                        (-1155436200, 0),
3323                        -Offset::hms(10, 30, 0),
3324                        "HST",
3325                        (1933, 5, 21, 11, 0, 0, 0),
3326                    ),
3327                    (
3328                        (-1155436199, 0),
3329                        -Offset::hms(10, 30, 0),
3330                        "HST",
3331                        (1933, 5, 21, 11, 0, 1, 0),
3332                    ),
3333                    (
3334                        (-880198201, 0),
3335                        -Offset::hms(10, 30, 0),
3336                        "HST",
3337                        (1942, 2, 9, 1, 59, 59, 0),
3338                    ),
3339                    (
3340                        (-880198200, 0),
3341                        -Offset::hms(9, 30, 0),
3342                        "HWT",
3343                        (1942, 2, 9, 3, 0, 0, 0),
3344                    ),
3345                    (
3346                        (-880198199, 0),
3347                        -Offset::hms(9, 30, 0),
3348                        "HWT",
3349                        (1942, 2, 9, 3, 0, 1, 0),
3350                    ),
3351                    (
3352                        (-769395601, 0),
3353                        -Offset::hms(9, 30, 0),
3354                        "HWT",
3355                        (1945, 8, 14, 13, 29, 59, 0),
3356                    ),
3357                    (
3358                        (-769395600, 0),
3359                        -Offset::hms(9, 30, 0),
3360                        "HPT",
3361                        (1945, 8, 14, 13, 30, 0, 0),
3362                    ),
3363                    (
3364                        (-769395599, 0),
3365                        -Offset::hms(9, 30, 0),
3366                        "HPT",
3367                        (1945, 8, 14, 13, 30, 1, 0),
3368                    ),
3369                    (
3370                        (-765376201, 0),
3371                        -Offset::hms(9, 30, 0),
3372                        "HPT",
3373                        (1945, 9, 30, 1, 59, 59, 0),
3374                    ),
3375                    (
3376                        (-765376200, 0),
3377                        -Offset::hms(10, 30, 0),
3378                        "HST",
3379                        (1945, 9, 30, 1, 0, 0, 0),
3380                    ),
3381                    (
3382                        (-765376199, 0),
3383                        -Offset::hms(10, 30, 0),
3384                        "HST",
3385                        (1945, 9, 30, 1, 0, 1, 0),
3386                    ),
3387                    (
3388                        (-712150201, 0),
3389                        -Offset::hms(10, 30, 0),
3390                        "HST",
3391                        (1947, 6, 8, 1, 59, 59, 0),
3392                    ),
3393                    // At this point, we hit the last transition and the POSIX
3394                    // TZ string takes over.
3395                    (
3396                        (-712150200, 0),
3397                        -Offset::hms(10, 0, 0),
3398                        "HST",
3399                        (1947, 6, 8, 2, 30, 0, 0),
3400                    ),
3401                    (
3402                        (-712150199, 0),
3403                        -Offset::hms(10, 0, 0),
3404                        "HST",
3405                        (1947, 6, 8, 2, 30, 1, 0),
3406                    ),
3407                ],
3408            ),
3409            // This time zone has an interesting transition where it jumps
3410            // backwards a full day at 1867-10-19T15:30:00.
3411            (
3412                "America/Sitka",
3413                &[
3414                    ((0, 0), o(-8), "PST", (1969, 12, 31, 16, 0, 0, 0)),
3415                    (
3416                        (-377705023201, 0),
3417                        Offset::hms(14, 58, 47),
3418                        "LMT",
3419                        (-9999, 1, 2, 16, 58, 46, 0),
3420                    ),
3421                    (
3422                        (-3225223728, 0),
3423                        Offset::hms(14, 58, 47),
3424                        "LMT",
3425                        (1867, 10, 19, 15, 29, 59, 0),
3426                    ),
3427                    // Notice the 24 hour time jump backwards a whole day!
3428                    (
3429                        (-3225223727, 0),
3430                        -Offset::hms(9, 1, 13),
3431                        "LMT",
3432                        (1867, 10, 18, 15, 30, 0, 0),
3433                    ),
3434                    (
3435                        (-3225223726, 0),
3436                        -Offset::hms(9, 1, 13),
3437                        "LMT",
3438                        (1867, 10, 18, 15, 30, 1, 0),
3439                    ),
3440                ],
3441            ),
3442        ];
3443        for &(tzname, timestamps_to_datetimes) in tests {
3444            let test_file = TzifTestFile::get(tzname);
3445            let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
3446            for &((unix_sec, unix_nano), offset, abbrev, datetime) in
3447                timestamps_to_datetimes
3448            {
3449                let (year, month, day, hour, min, sec, nano) = datetime;
3450                let timestamp = Timestamp::new(unix_sec, unix_nano).unwrap();
3451                let info = tz.to_offset_info(timestamp);
3452                assert_eq!(
3453                    info.offset(),
3454                    offset,
3455                    "\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
3456                );
3457                assert_eq!(
3458                    info.abbreviation(),
3459                    abbrev,
3460                    "\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
3461                );
3462                assert_eq!(
3463                    info.offset().to_datetime(timestamp),
3464                    date(year, month, day).at(hour, min, sec, nano),
3465                    "\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
3466                );
3467            }
3468        }
3469    }
3470
3471    #[cfg(feature = "alloc")]
3472    #[test]
3473    fn time_zone_posix_to_ambiguous_timestamp() {
3474        let tests: &[(&str, &[_])] = &[
3475            // America/New_York, but a utopia in which DST is abolished.
3476            (
3477                "EST5",
3478                &[
3479                    ((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
3480                    ((2024, 3, 10, 2, 0, 0, 0), unambiguous(-5)),
3481                ],
3482            ),
3483            // The standard DST rule for America/New_York.
3484            (
3485                "EST5EDT,M3.2.0,M11.1.0",
3486                &[
3487                    ((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
3488                    ((2024, 3, 10, 1, 59, 59, 999_999_999), unambiguous(-5)),
3489                    ((2024, 3, 10, 2, 0, 0, 0), gap(-5, -4)),
3490                    ((2024, 3, 10, 2, 59, 59, 999_999_999), gap(-5, -4)),
3491                    ((2024, 3, 10, 3, 0, 0, 0), unambiguous(-4)),
3492                    ((2024, 11, 3, 0, 59, 59, 999_999_999), unambiguous(-4)),
3493                    ((2024, 11, 3, 1, 0, 0, 0), fold(-4, -5)),
3494                    ((2024, 11, 3, 1, 59, 59, 999_999_999), fold(-4, -5)),
3495                    ((2024, 11, 3, 2, 0, 0, 0), unambiguous(-5)),
3496                ],
3497            ),
3498            // A bit of a nonsensical America/New_York that has DST, but whose
3499            // offset is equivalent to standard time. Having the same offset
3500            // means there's never any ambiguity.
3501            (
3502                "EST5EDT5,M3.2.0,M11.1.0",
3503                &[
3504                    ((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
3505                    ((2024, 3, 10, 1, 59, 59, 999_999_999), unambiguous(-5)),
3506                    ((2024, 3, 10, 2, 0, 0, 0), unambiguous(-5)),
3507                    ((2024, 3, 10, 2, 59, 59, 999_999_999), unambiguous(-5)),
3508                    ((2024, 3, 10, 3, 0, 0, 0), unambiguous(-5)),
3509                    ((2024, 11, 3, 0, 59, 59, 999_999_999), unambiguous(-5)),
3510                    ((2024, 11, 3, 1, 0, 0, 0), unambiguous(-5)),
3511                    ((2024, 11, 3, 1, 59, 59, 999_999_999), unambiguous(-5)),
3512                    ((2024, 11, 3, 2, 0, 0, 0), unambiguous(-5)),
3513                ],
3514            ),
3515            // This is Europe/Dublin's rule. It's interesting because its
3516            // DST is an offset behind standard time. (DST is usually one hour
3517            // ahead of standard time.)
3518            (
3519                "IST-1GMT0,M10.5.0,M3.5.0/1",
3520                &[
3521                    ((1970, 1, 1, 0, 0, 0, 0), unambiguous(0)),
3522                    ((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
3523                    ((2024, 3, 31, 1, 0, 0, 0), gap(0, 1)),
3524                    ((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 1)),
3525                    ((2024, 3, 31, 2, 0, 0, 0), unambiguous(1)),
3526                    ((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(1)),
3527                    ((2024, 10, 27, 1, 0, 0, 0), fold(1, 0)),
3528                    ((2024, 10, 27, 1, 59, 59, 999_999_999), fold(1, 0)),
3529                    ((2024, 10, 27, 2, 0, 0, 0), unambiguous(0)),
3530                ],
3531            ),
3532            // This is Australia/Tasmania's rule. We chose this because it's
3533            // in the southern hemisphere where DST still skips ahead one hour,
3534            // but it usually starts in the fall and ends in the spring.
3535            (
3536                "AEST-10AEDT,M10.1.0,M4.1.0/3",
3537                &[
3538                    ((1970, 1, 1, 11, 0, 0, 0), unambiguous(11)),
3539                    ((2024, 4, 7, 1, 59, 59, 999_999_999), unambiguous(11)),
3540                    ((2024, 4, 7, 2, 0, 0, 0), fold(11, 10)),
3541                    ((2024, 4, 7, 2, 59, 59, 999_999_999), fold(11, 10)),
3542                    ((2024, 4, 7, 3, 0, 0, 0), unambiguous(10)),
3543                    ((2024, 10, 6, 1, 59, 59, 999_999_999), unambiguous(10)),
3544                    ((2024, 10, 6, 2, 0, 0, 0), gap(10, 11)),
3545                    ((2024, 10, 6, 2, 59, 59, 999_999_999), gap(10, 11)),
3546                    ((2024, 10, 6, 3, 0, 0, 0), unambiguous(11)),
3547                ],
3548            ),
3549            // This is Antarctica/Troll's rule. We chose this one because its
3550            // DST transition is 2 hours instead of the standard 1 hour. This
3551            // means gaps and folds are twice as long as they usually are. And
3552            // it means there are 22 hour and 26 hour days, respectively. Wow!
3553            (
3554                "<+00>0<+02>-2,M3.5.0/1,M10.5.0/3",
3555                &[
3556                    ((1970, 1, 1, 0, 0, 0, 0), unambiguous(0)),
3557                    // test the gap
3558                    ((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
3559                    ((2024, 3, 31, 1, 0, 0, 0), gap(0, 2)),
3560                    ((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 2)),
3561                    // still in the gap!
3562                    ((2024, 3, 31, 2, 0, 0, 0), gap(0, 2)),
3563                    ((2024, 3, 31, 2, 59, 59, 999_999_999), gap(0, 2)),
3564                    // finally out
3565                    ((2024, 3, 31, 3, 0, 0, 0), unambiguous(2)),
3566                    // test the fold
3567                    ((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(2)),
3568                    ((2024, 10, 27, 1, 0, 0, 0), fold(2, 0)),
3569                    ((2024, 10, 27, 1, 59, 59, 999_999_999), fold(2, 0)),
3570                    // still in the fold!
3571                    ((2024, 10, 27, 2, 0, 0, 0), fold(2, 0)),
3572                    ((2024, 10, 27, 2, 59, 59, 999_999_999), fold(2, 0)),
3573                    // finally out
3574                    ((2024, 10, 27, 3, 0, 0, 0), unambiguous(0)),
3575                ],
3576            ),
3577            // This is America/St_Johns' rule, which has an offset with
3578            // non-zero minutes *and* a DST transition rule. (Indian Standard
3579            // Time is the one I'm more familiar with, but it turns out IST
3580            // does not have DST!)
3581            (
3582                "NST3:30NDT,M3.2.0,M11.1.0",
3583                &[
3584                    (
3585                        (1969, 12, 31, 20, 30, 0, 0),
3586                        o_unambiguous(-Offset::hms(3, 30, 0)),
3587                    ),
3588                    (
3589                        (2024, 3, 10, 1, 59, 59, 999_999_999),
3590                        o_unambiguous(-Offset::hms(3, 30, 0)),
3591                    ),
3592                    (
3593                        (2024, 3, 10, 2, 0, 0, 0),
3594                        o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
3595                    ),
3596                    (
3597                        (2024, 3, 10, 2, 59, 59, 999_999_999),
3598                        o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
3599                    ),
3600                    (
3601                        (2024, 3, 10, 3, 0, 0, 0),
3602                        o_unambiguous(-Offset::hms(2, 30, 0)),
3603                    ),
3604                    (
3605                        (2024, 11, 3, 0, 59, 59, 999_999_999),
3606                        o_unambiguous(-Offset::hms(2, 30, 0)),
3607                    ),
3608                    (
3609                        (2024, 11, 3, 1, 0, 0, 0),
3610                        o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
3611                    ),
3612                    (
3613                        (2024, 11, 3, 1, 59, 59, 999_999_999),
3614                        o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
3615                    ),
3616                    (
3617                        (2024, 11, 3, 2, 0, 0, 0),
3618                        o_unambiguous(-Offset::hms(3, 30, 0)),
3619                    ),
3620                ],
3621            ),
3622        ];
3623        for &(posix_tz, datetimes_to_ambiguous) in tests {
3624            let tz = TimeZone::posix(posix_tz).unwrap();
3625            for &(datetime, ambiguous_kind) in datetimes_to_ambiguous {
3626                let (year, month, day, hour, min, sec, nano) = datetime;
3627                let dt = date(year, month, day).at(hour, min, sec, nano);
3628                let got = tz.to_ambiguous_zoned_datetime(dt);
3629                assert_eq!(
3630                    got.offset(),
3631                    ambiguous_kind,
3632                    "\nTZ: {posix_tz}\ndatetime: \
3633                     {year:04}-{month:02}-{day:02}T\
3634                     {hour:02}:{min:02}:{sec:02}.{nano:09}",
3635                );
3636            }
3637        }
3638    }
3639
3640    #[cfg(feature = "alloc")]
3641    #[test]
3642    fn time_zone_posix_to_datetime() {
3643        let o = |hours| offset(hours);
3644        let tests: &[(&str, &[_])] = &[
3645            ("EST5", &[((0, 0), o(-5), (1969, 12, 31, 19, 0, 0, 0))]),
3646            (
3647                // From America/New_York
3648                "EST5EDT,M3.2.0,M11.1.0",
3649                &[
3650                    ((0, 0), o(-5), (1969, 12, 31, 19, 0, 0, 0)),
3651                    ((1710052200, 0), o(-5), (2024, 3, 10, 1, 30, 0, 0)),
3652                    (
3653                        (1710053999, 999_999_999),
3654                        o(-5),
3655                        (2024, 3, 10, 1, 59, 59, 999_999_999),
3656                    ),
3657                    ((1710054000, 0), o(-4), (2024, 3, 10, 3, 0, 0, 0)),
3658                    ((1710055800, 0), o(-4), (2024, 3, 10, 3, 30, 0, 0)),
3659                    ((1730610000, 0), o(-4), (2024, 11, 3, 1, 0, 0, 0)),
3660                    ((1730611800, 0), o(-4), (2024, 11, 3, 1, 30, 0, 0)),
3661                    (
3662                        (1730613599, 999_999_999),
3663                        o(-4),
3664                        (2024, 11, 3, 1, 59, 59, 999_999_999),
3665                    ),
3666                    ((1730613600, 0), o(-5), (2024, 11, 3, 1, 0, 0, 0)),
3667                    ((1730615400, 0), o(-5), (2024, 11, 3, 1, 30, 0, 0)),
3668                ],
3669            ),
3670            (
3671                // From Australia/Tasmania
3672                //
3673                // We chose this because it's a time zone in the southern
3674                // hemisphere with DST. Unlike the northern hemisphere, its DST
3675                // starts in the fall and ends in the spring. In the northern
3676                // hemisphere, we typically start DST in the spring and end it
3677                // in the fall.
3678                "AEST-10AEDT,M10.1.0,M4.1.0/3",
3679                &[
3680                    ((0, 0), o(11), (1970, 1, 1, 11, 0, 0, 0)),
3681                    ((1728142200, 0), o(10), (2024, 10, 6, 1, 30, 0, 0)),
3682                    (
3683                        (1728143999, 999_999_999),
3684                        o(10),
3685                        (2024, 10, 6, 1, 59, 59, 999_999_999),
3686                    ),
3687                    ((1728144000, 0), o(11), (2024, 10, 6, 3, 0, 0, 0)),
3688                    ((1728145800, 0), o(11), (2024, 10, 6, 3, 30, 0, 0)),
3689                    ((1712415600, 0), o(11), (2024, 4, 7, 2, 0, 0, 0)),
3690                    ((1712417400, 0), o(11), (2024, 4, 7, 2, 30, 0, 0)),
3691                    (
3692                        (1712419199, 999_999_999),
3693                        o(11),
3694                        (2024, 4, 7, 2, 59, 59, 999_999_999),
3695                    ),
3696                    ((1712419200, 0), o(10), (2024, 4, 7, 2, 0, 0, 0)),
3697                    ((1712421000, 0), o(10), (2024, 4, 7, 2, 30, 0, 0)),
3698                ],
3699            ),
3700            (
3701                // Uses the maximum possible offset. A sloppy read of POSIX
3702                // seems to indicate the maximum offset is 24:59:59, but since
3703                // DST defaults to 1 hour ahead of standard time, it's possible
3704                // to use 24:59:59 for standard time, omit the DST offset, and
3705                // thus get a DST offset of 25:59:59.
3706                "XXX-24:59:59YYY,M3.2.0,M11.1.0",
3707                &[
3708                    // 2024-01-05T00:00:00+00
3709                    (
3710                        (1704412800, 0),
3711                        Offset::hms(24, 59, 59),
3712                        (2024, 1, 6, 0, 59, 59, 0),
3713                    ),
3714                    // 2024-06-05T00:00:00+00 (DST)
3715                    (
3716                        (1717545600, 0),
3717                        Offset::hms(25, 59, 59),
3718                        (2024, 6, 6, 1, 59, 59, 0),
3719                    ),
3720                ],
3721            ),
3722        ];
3723        for &(posix_tz, timestamps_to_datetimes) in tests {
3724            let tz = TimeZone::posix(posix_tz).unwrap();
3725            for &((unix_sec, unix_nano), offset, datetime) in
3726                timestamps_to_datetimes
3727            {
3728                let (year, month, day, hour, min, sec, nano) = datetime;
3729                let timestamp = Timestamp::new(unix_sec, unix_nano).unwrap();
3730                assert_eq!(
3731                    tz.to_offset(timestamp),
3732                    offset,
3733                    "\ntimestamp({unix_sec}, {unix_nano})",
3734                );
3735                assert_eq!(
3736                    tz.to_datetime(timestamp),
3737                    date(year, month, day).at(hour, min, sec, nano),
3738                    "\ntimestamp({unix_sec}, {unix_nano})",
3739                );
3740            }
3741        }
3742    }
3743
3744    #[test]
3745    fn time_zone_fixed_to_datetime() {
3746        let tz = offset(-5).to_time_zone();
3747        let unix_epoch = Timestamp::new(0, 0).unwrap();
3748        assert_eq!(
3749            tz.to_datetime(unix_epoch),
3750            date(1969, 12, 31).at(19, 0, 0, 0),
3751        );
3752
3753        let tz = Offset::from_seconds(93_599).unwrap().to_time_zone();
3754        let timestamp = Timestamp::new(253402207200, 999_999_999).unwrap();
3755        assert_eq!(
3756            tz.to_datetime(timestamp),
3757            date(9999, 12, 31).at(23, 59, 59, 999_999_999),
3758        );
3759
3760        let tz = Offset::from_seconds(-93_599).unwrap().to_time_zone();
3761        let timestamp = Timestamp::new(-377705023201, 0).unwrap();
3762        assert_eq!(
3763            tz.to_datetime(timestamp),
3764            date(-9999, 1, 1).at(0, 0, 0, 0),
3765        );
3766    }
3767
3768    #[test]
3769    fn time_zone_fixed_to_timestamp() {
3770        let tz = offset(-5).to_time_zone();
3771        let dt = date(1969, 12, 31).at(19, 0, 0, 0);
3772        assert_eq!(
3773            tz.to_zoned_datetime(dt).unwrap().timestamp(),
3774            Timestamp::new(0, 0).unwrap()
3775        );
3776
3777        let tz = Offset::from_seconds(93_599).unwrap().to_time_zone();
3778        let dt = date(9999, 12, 31).at(23, 59, 59, 999_999_999);
3779        assert_eq!(
3780            tz.to_zoned_datetime(dt).unwrap().timestamp(),
3781            Timestamp::new(253402207200, 999_999_999).unwrap(),
3782        );
3783        let tz = Offset::from_seconds(93_598).unwrap().to_time_zone();
3784        assert!(tz.to_zoned_datetime(dt).is_err());
3785
3786        let tz = Offset::from_seconds(-93_599).unwrap().to_time_zone();
3787        let dt = date(-9999, 1, 1).at(0, 0, 0, 0);
3788        assert_eq!(
3789            tz.to_zoned_datetime(dt).unwrap().timestamp(),
3790            Timestamp::new(-377705023201, 0).unwrap(),
3791        );
3792        let tz = Offset::from_seconds(-93_598).unwrap().to_time_zone();
3793        assert!(tz.to_zoned_datetime(dt).is_err());
3794    }
3795
3796    #[cfg(feature = "alloc")]
3797    #[test]
3798    fn time_zone_tzif_previous_transition() {
3799        let tests: &[(&str, &[(&str, Option<&str>)])] = &[
3800            (
3801                "UTC",
3802                &[
3803                    ("1969-12-31T19Z", None),
3804                    ("2024-03-10T02Z", None),
3805                    ("-009999-12-01 00Z", None),
3806                    ("9999-12-01 00Z", None),
3807                ],
3808            ),
3809            (
3810                "America/New_York",
3811                &[
3812                    ("2024-03-10 08Z", Some("2024-03-10 07Z")),
3813                    ("2024-03-10 07:00:00.000000001Z", Some("2024-03-10 07Z")),
3814                    ("2024-03-10 07Z", Some("2023-11-05 06Z")),
3815                    ("2023-11-05 06Z", Some("2023-03-12 07Z")),
3816                    ("-009999-01-31 00Z", None),
3817                    ("9999-12-01 00Z", Some("9999-11-07 06Z")),
3818                    // While at present we have "fat" TZif files for our
3819                    // testdata, it's conceivable they could be swapped to
3820                    // "slim." In which case, the tests above will mostly just
3821                    // be testing POSIX TZ strings and not the TZif logic. So
3822                    // below, we include times that will be in slim (i.e.,
3823                    // historical times the precede the current DST rule).
3824                    ("1969-12-31 19Z", Some("1969-10-26 06Z")),
3825                    ("2000-04-02 08Z", Some("2000-04-02 07Z")),
3826                    ("2000-04-02 07:00:00.000000001Z", Some("2000-04-02 07Z")),
3827                    ("2000-04-02 07Z", Some("1999-10-31 06Z")),
3828                    ("1999-10-31 06Z", Some("1999-04-04 07Z")),
3829                ],
3830            ),
3831            (
3832                "Australia/Tasmania",
3833                &[
3834                    ("2010-04-03 17Z", Some("2010-04-03 16Z")),
3835                    ("2010-04-03 16:00:00.000000001Z", Some("2010-04-03 16Z")),
3836                    ("2010-04-03 16Z", Some("2009-10-03 16Z")),
3837                    ("2009-10-03 16Z", Some("2009-04-04 16Z")),
3838                    ("-009999-01-31 00Z", None),
3839                    ("9999-12-01 00Z", Some("9999-10-02 16Z")),
3840                    // Tests for historical data from tzdb. No POSIX TZ.
3841                    ("2000-03-25 17Z", Some("2000-03-25 16Z")),
3842                    ("2000-03-25 16:00:00.000000001Z", Some("2000-03-25 16Z")),
3843                    ("2000-03-25 16Z", Some("1999-10-02 16Z")),
3844                    ("1999-10-02 16Z", Some("1999-03-27 16Z")),
3845                ],
3846            ),
3847            // This is Europe/Dublin's rule. It's interesting because its
3848            // DST is an offset behind standard time. (DST is usually one hour
3849            // ahead of standard time.)
3850            (
3851                "Europe/Dublin",
3852                &[
3853                    ("2010-03-28 02Z", Some("2010-03-28 01Z")),
3854                    ("2010-03-28 01:00:00.000000001Z", Some("2010-03-28 01Z")),
3855                    ("2010-03-28 01Z", Some("2009-10-25 01Z")),
3856                    ("2009-10-25 01Z", Some("2009-03-29 01Z")),
3857                    ("-009999-01-31 00Z", None),
3858                    ("9999-12-01 00Z", Some("9999-10-31 01Z")),
3859                    // Tests for historical data from tzdb. No POSIX TZ.
3860                    ("1990-03-25 02Z", Some("1990-03-25 01Z")),
3861                    ("1990-03-25 01:00:00.000000001Z", Some("1990-03-25 01Z")),
3862                    ("1990-03-25 01Z", Some("1989-10-29 01Z")),
3863                    ("1989-10-25 01Z", Some("1989-03-26 01Z")),
3864                ],
3865            ),
3866            (
3867                // Sao Paulo eliminated DST in 2019, so the previous transition
3868                // from 2024 is several years back.
3869                "America/Sao_Paulo",
3870                &[("2024-03-10 08Z", Some("2019-02-17 02Z"))],
3871            ),
3872        ];
3873        for &(tzname, prev_trans) in tests {
3874            if tzname != "America/Sao_Paulo" {
3875                continue;
3876            }
3877            let test_file = TzifTestFile::get(tzname);
3878            let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
3879            for (given, expected) in prev_trans {
3880                let given: Timestamp = given.parse().unwrap();
3881                let expected =
3882                    expected.map(|s| s.parse::<Timestamp>().unwrap());
3883                let got = tz.previous_transition(given).map(|t| t.timestamp());
3884                assert_eq!(got, expected, "\nTZ: {tzname}\ngiven: {given}");
3885            }
3886        }
3887    }
3888
3889    #[cfg(feature = "alloc")]
3890    #[test]
3891    fn time_zone_tzif_next_transition() {
3892        let tests: &[(&str, &[(&str, Option<&str>)])] = &[
3893            (
3894                "UTC",
3895                &[
3896                    ("1969-12-31T19Z", None),
3897                    ("2024-03-10T02Z", None),
3898                    ("-009999-12-01 00Z", None),
3899                    ("9999-12-01 00Z", None),
3900                ],
3901            ),
3902            (
3903                "America/New_York",
3904                &[
3905                    ("2024-03-10 06Z", Some("2024-03-10 07Z")),
3906                    ("2024-03-10 06:59:59.999999999Z", Some("2024-03-10 07Z")),
3907                    ("2024-03-10 07Z", Some("2024-11-03 06Z")),
3908                    ("2024-11-03 06Z", Some("2025-03-09 07Z")),
3909                    ("-009999-12-01 00Z", Some("1883-11-18 17Z")),
3910                    ("9999-12-01 00Z", None),
3911                    // While at present we have "fat" TZif files for our
3912                    // testdata, it's conceivable they could be swapped to
3913                    // "slim." In which case, the tests above will mostly just
3914                    // be testing POSIX TZ strings and not the TZif logic. So
3915                    // below, we include times that will be in slim (i.e.,
3916                    // historical times the precede the current DST rule).
3917                    ("1969-12-31 19Z", Some("1970-04-26 07Z")),
3918                    ("2000-04-02 06Z", Some("2000-04-02 07Z")),
3919                    ("2000-04-02 06:59:59.999999999Z", Some("2000-04-02 07Z")),
3920                    ("2000-04-02 07Z", Some("2000-10-29 06Z")),
3921                    ("2000-10-29 06Z", Some("2001-04-01 07Z")),
3922                ],
3923            ),
3924            (
3925                "Australia/Tasmania",
3926                &[
3927                    ("2010-04-03 15Z", Some("2010-04-03 16Z")),
3928                    ("2010-04-03 15:59:59.999999999Z", Some("2010-04-03 16Z")),
3929                    ("2010-04-03 16Z", Some("2010-10-02 16Z")),
3930                    ("2010-10-02 16Z", Some("2011-04-02 16Z")),
3931                    ("-009999-12-01 00Z", Some("1895-08-31 14:10:44Z")),
3932                    ("9999-12-01 00Z", None),
3933                    // Tests for historical data from tzdb. No POSIX TZ.
3934                    ("2000-03-25 15Z", Some("2000-03-25 16Z")),
3935                    ("2000-03-25 15:59:59.999999999Z", Some("2000-03-25 16Z")),
3936                    ("2000-03-25 16Z", Some("2000-08-26 16Z")),
3937                    ("2000-08-26 16Z", Some("2001-03-24 16Z")),
3938                ],
3939            ),
3940            (
3941                "Europe/Dublin",
3942                &[
3943                    ("2010-03-28 00Z", Some("2010-03-28 01Z")),
3944                    ("2010-03-28 00:59:59.999999999Z", Some("2010-03-28 01Z")),
3945                    ("2010-03-28 01Z", Some("2010-10-31 01Z")),
3946                    ("2010-10-31 01Z", Some("2011-03-27 01Z")),
3947                    ("-009999-12-01 00Z", Some("1880-08-02 00:25:21Z")),
3948                    ("9999-12-01 00Z", None),
3949                    // Tests for historical data from tzdb. No POSIX TZ.
3950                    ("1990-03-25 00Z", Some("1990-03-25 01Z")),
3951                    ("1990-03-25 00:59:59.999999999Z", Some("1990-03-25 01Z")),
3952                    ("1990-03-25 01Z", Some("1990-10-28 01Z")),
3953                    ("1990-10-28 01Z", Some("1991-03-31 01Z")),
3954                ],
3955            ),
3956            (
3957                // Sao Paulo eliminated DST in 2019, so the next transition
3958                // from 2024 no longer exists.
3959                "America/Sao_Paulo",
3960                &[("2024-03-10 08Z", None)],
3961            ),
3962        ];
3963        for &(tzname, next_trans) in tests {
3964            let test_file = TzifTestFile::get(tzname);
3965            let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
3966            for (given, expected) in next_trans {
3967                let given: Timestamp = given.parse().unwrap();
3968                let expected =
3969                    expected.map(|s| s.parse::<Timestamp>().unwrap());
3970                let got = tz.next_transition(given).map(|t| t.timestamp());
3971                assert_eq!(got, expected, "\nTZ: {tzname}\ngiven: {given}");
3972            }
3973        }
3974    }
3975
3976    #[cfg(feature = "alloc")]
3977    #[test]
3978    fn time_zone_posix_previous_transition() {
3979        let tests: &[(&str, &[(&str, Option<&str>)])] = &[
3980            // America/New_York, but a utopia in which DST is abolished. There
3981            // are no time zone transitions, so next_transition always returns
3982            // None.
3983            (
3984                "EST5",
3985                &[
3986                    ("1969-12-31T19Z", None),
3987                    ("2024-03-10T02Z", None),
3988                    ("-009999-12-01 00Z", None),
3989                    ("9999-12-01 00Z", None),
3990                ],
3991            ),
3992            // The standard DST rule for America/New_York.
3993            (
3994                "EST5EDT,M3.2.0,M11.1.0",
3995                &[
3996                    ("1969-12-31 19Z", Some("1969-11-02 06Z")),
3997                    ("2024-03-10 08Z", Some("2024-03-10 07Z")),
3998                    ("2024-03-10 07:00:00.000000001Z", Some("2024-03-10 07Z")),
3999                    ("2024-03-10 07Z", Some("2023-11-05 06Z")),
4000                    ("2023-11-05 06Z", Some("2023-03-12 07Z")),
4001                    ("-009999-01-31 00Z", None),
4002                    ("9999-12-01 00Z", Some("9999-11-07 06Z")),
4003                ],
4004            ),
4005            (
4006                // From Australia/Tasmania
4007                "AEST-10AEDT,M10.1.0,M4.1.0/3",
4008                &[
4009                    ("2010-04-03 17Z", Some("2010-04-03 16Z")),
4010                    ("2010-04-03 16:00:00.000000001Z", Some("2010-04-03 16Z")),
4011                    ("2010-04-03 16Z", Some("2009-10-03 16Z")),
4012                    ("2009-10-03 16Z", Some("2009-04-04 16Z")),
4013                    ("-009999-01-31 00Z", None),
4014                    ("9999-12-01 00Z", Some("9999-10-02 16Z")),
4015                ],
4016            ),
4017            // This is Europe/Dublin's rule. It's interesting because its
4018            // DST is an offset behind standard time. (DST is usually one hour
4019            // ahead of standard time.)
4020            (
4021                "IST-1GMT0,M10.5.0,M3.5.0/1",
4022                &[
4023                    ("2010-03-28 02Z", Some("2010-03-28 01Z")),
4024                    ("2010-03-28 01:00:00.000000001Z", Some("2010-03-28 01Z")),
4025                    ("2010-03-28 01Z", Some("2009-10-25 01Z")),
4026                    ("2009-10-25 01Z", Some("2009-03-29 01Z")),
4027                    ("-009999-01-31 00Z", None),
4028                    ("9999-12-01 00Z", Some("9999-10-31 01Z")),
4029                ],
4030            ),
4031        ];
4032        for &(posix_tz, prev_trans) in tests {
4033            let tz = TimeZone::posix(posix_tz).unwrap();
4034            for (given, expected) in prev_trans {
4035                let given: Timestamp = given.parse().unwrap();
4036                let expected =
4037                    expected.map(|s| s.parse::<Timestamp>().unwrap());
4038                let got = tz.previous_transition(given).map(|t| t.timestamp());
4039                assert_eq!(got, expected, "\nTZ: {posix_tz}\ngiven: {given}");
4040            }
4041        }
4042    }
4043
4044    #[cfg(feature = "alloc")]
4045    #[test]
4046    fn time_zone_posix_next_transition() {
4047        let tests: &[(&str, &[(&str, Option<&str>)])] = &[
4048            // America/New_York, but a utopia in which DST is abolished. There
4049            // are no time zone transitions, so next_transition always returns
4050            // None.
4051            (
4052                "EST5",
4053                &[
4054                    ("1969-12-31T19Z", None),
4055                    ("2024-03-10T02Z", None),
4056                    ("-009999-12-01 00Z", None),
4057                    ("9999-12-01 00Z", None),
4058                ],
4059            ),
4060            // The standard DST rule for America/New_York.
4061            (
4062                "EST5EDT,M3.2.0,M11.1.0",
4063                &[
4064                    ("1969-12-31 19Z", Some("1970-03-08 07Z")),
4065                    ("2024-03-10 06Z", Some("2024-03-10 07Z")),
4066                    ("2024-03-10 06:59:59.999999999Z", Some("2024-03-10 07Z")),
4067                    ("2024-03-10 07Z", Some("2024-11-03 06Z")),
4068                    ("2024-11-03 06Z", Some("2025-03-09 07Z")),
4069                    ("-009999-12-01 00Z", Some("-009998-03-10 07Z")),
4070                    ("9999-12-01 00Z", None),
4071                ],
4072            ),
4073            (
4074                // From Australia/Tasmania
4075                "AEST-10AEDT,M10.1.0,M4.1.0/3",
4076                &[
4077                    ("2010-04-03 15Z", Some("2010-04-03 16Z")),
4078                    ("2010-04-03 15:59:59.999999999Z", Some("2010-04-03 16Z")),
4079                    ("2010-04-03 16Z", Some("2010-10-02 16Z")),
4080                    ("2010-10-02 16Z", Some("2011-04-02 16Z")),
4081                    ("-009999-12-01 00Z", Some("-009998-04-06 16Z")),
4082                    ("9999-12-01 00Z", None),
4083                ],
4084            ),
4085            // This is Europe/Dublin's rule. It's interesting because its
4086            // DST is an offset behind standard time. (DST is usually one hour
4087            // ahead of standard time.)
4088            (
4089                "IST-1GMT0,M10.5.0,M3.5.0/1",
4090                &[
4091                    ("2010-03-28 00Z", Some("2010-03-28 01Z")),
4092                    ("2010-03-28 00:59:59.999999999Z", Some("2010-03-28 01Z")),
4093                    ("2010-03-28 01Z", Some("2010-10-31 01Z")),
4094                    ("2010-10-31 01Z", Some("2011-03-27 01Z")),
4095                    ("-009999-12-01 00Z", Some("-009998-03-31 01Z")),
4096                    ("9999-12-01 00Z", None),
4097                ],
4098            ),
4099        ];
4100        for &(posix_tz, next_trans) in tests {
4101            let tz = TimeZone::posix(posix_tz).unwrap();
4102            for (given, expected) in next_trans {
4103                let given: Timestamp = given.parse().unwrap();
4104                let expected =
4105                    expected.map(|s| s.parse::<Timestamp>().unwrap());
4106                let got = tz.next_transition(given).map(|t| t.timestamp());
4107                assert_eq!(got, expected, "\nTZ: {posix_tz}\ngiven: {given}");
4108            }
4109        }
4110    }
4111
4112    /// This tests that the size of a time zone is kept at a single word.
4113    ///
4114    /// This is important because every jiff::ZonedDateTime has a TimeZone
4115    /// inside of it, and we want to keep its size as small as we can.
4116    #[test]
4117    fn time_zone_size() {
4118        #[cfg(feature = "alloc")]
4119        {
4120            let word = core::mem::size_of::<usize>();
4121            assert_eq!(word, core::mem::size_of::<TimeZone>());
4122        }
4123        #[cfg(all(target_pointer_width = "64", not(feature = "alloc")))]
4124        {
4125            #[cfg(debug_assertions)]
4126            {
4127                assert_eq!(8, core::mem::size_of::<TimeZone>());
4128            }
4129            #[cfg(not(debug_assertions))]
4130            {
4131                // This asserts the same value as the alloc value above, but
4132                // it wasn't always this way, which is why it's written out
4133                // separately. Moreover, in theory, I'd be open to regressing
4134                // this value if it led to an improvement in alloc-mode. But
4135                // more likely, it would be nice to decrease this size in
4136                // non-alloc modes.
4137                assert_eq!(8, core::mem::size_of::<TimeZone>());
4138            }
4139        }
4140    }
4141
4142    /// This tests a few other cases for `TimeZone::to_offset` that
4143    /// probably aren't worth showing in doctest examples.
4144    #[test]
4145    fn time_zone_to_offset() {
4146        let ts = Timestamp::from_second(123456789).unwrap();
4147
4148        let tz = TimeZone::fixed(offset(-5));
4149        let info = tz.to_offset_info(ts);
4150        assert_eq!(info.offset(), offset(-5));
4151        assert_eq!(info.dst(), Dst::No);
4152        assert_eq!(info.abbreviation(), "-05");
4153
4154        let tz = TimeZone::fixed(offset(5));
4155        let info = tz.to_offset_info(ts);
4156        assert_eq!(info.offset(), offset(5));
4157        assert_eq!(info.dst(), Dst::No);
4158        assert_eq!(info.abbreviation(), "+05");
4159
4160        let tz = TimeZone::fixed(offset(-12));
4161        let info = tz.to_offset_info(ts);
4162        assert_eq!(info.offset(), offset(-12));
4163        assert_eq!(info.dst(), Dst::No);
4164        assert_eq!(info.abbreviation(), "-12");
4165
4166        let tz = TimeZone::fixed(offset(12));
4167        let info = tz.to_offset_info(ts);
4168        assert_eq!(info.offset(), offset(12));
4169        assert_eq!(info.dst(), Dst::No);
4170        assert_eq!(info.abbreviation(), "+12");
4171
4172        let tz = TimeZone::fixed(offset(0));
4173        let info = tz.to_offset_info(ts);
4174        assert_eq!(info.offset(), offset(0));
4175        assert_eq!(info.dst(), Dst::No);
4176        assert_eq!(info.abbreviation(), "UTC");
4177    }
4178
4179    /// This tests a few other cases for `TimeZone::to_fixed_offset` that
4180    /// probably aren't worth showing in doctest examples.
4181    #[test]
4182    fn time_zone_to_fixed_offset() {
4183        let tz = TimeZone::UTC;
4184        assert_eq!(tz.to_fixed_offset().unwrap(), Offset::UTC);
4185
4186        let offset = Offset::from_hours(1).unwrap();
4187        let tz = TimeZone::fixed(offset);
4188        assert_eq!(tz.to_fixed_offset().unwrap(), offset);
4189
4190        #[cfg(feature = "alloc")]
4191        {
4192            let tz = TimeZone::posix("EST5").unwrap();
4193            assert!(tz.to_fixed_offset().is_err());
4194
4195            let test_file = TzifTestFile::get("America/New_York");
4196            let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
4197            assert!(tz.to_fixed_offset().is_err());
4198        }
4199    }
4200
4201    /// This tests that `TimeZone::following` correctly returns a final time
4202    /// zone transition.
4203    #[cfg(feature = "alloc")]
4204    #[test]
4205    fn time_zone_following_boa_vista() {
4206        use alloc::{vec, vec::Vec};
4207
4208        let test_file = TzifTestFile::get("America/Boa_Vista");
4209        let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
4210        let last4: Vec<Timestamp> = vec![
4211            "1999-10-03T04Z".parse().unwrap(),
4212            "2000-02-27T03Z".parse().unwrap(),
4213            "2000-10-08T04Z".parse().unwrap(),
4214            "2000-10-15T03Z".parse().unwrap(),
4215        ];
4216
4217        let start: Timestamp = "2001-01-01T00Z".parse().unwrap();
4218        let mut transitions: Vec<Timestamp> =
4219            tz.preceding(start).take(4).map(|t| t.timestamp()).collect();
4220        transitions.reverse();
4221        assert_eq!(transitions, last4);
4222
4223        let start: Timestamp = "1990-01-01T00Z".parse().unwrap();
4224        let transitions: Vec<Timestamp> =
4225            tz.following(start).map(|t| t.timestamp()).collect();
4226        // The regression here was that the 2000-10-15 transition wasn't
4227        // being found here, despite the fact that it existed and was found
4228        // by `preceding`.
4229        assert_eq!(transitions, last4);
4230    }
4231
4232    #[cfg(feature = "alloc")]
4233    #[test]
4234    fn regression_tzif_parse_panic() {
4235        _ = TimeZone::tzif(
4236            "",
4237            &[
4238                84, 90, 105, 102, 6, 0, 5, 35, 84, 10, 77, 0, 0, 0, 84, 82,
4239                105, 102, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4240                0, 0, 0, 0, 2, 0, 0, 0, 5, 0, 0, 82, 28, 77, 0, 0, 90, 105,
4241                78, 0, 0, 0, 0, 0, 0, 0, 84, 90, 105, 102, 0, 0, 5, 0, 84, 90,
4242                105, 84, 77, 10, 0, 0, 0, 15, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4243                0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 5, 0, 0, 0, 82, 0, 64, 1, 0,
4244                0, 2, 0, 0, 0, 0, 0, 0, 126, 1, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0,
4245                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 126, 0, 0, 0, 0, 0,
4246                0, 160, 109, 1, 0, 90, 105, 102, 0, 0, 5, 0, 87, 90, 105, 84,
4247                77, 10, 0, 0, 0, 0, 0, 122, 102, 105, 0, 0, 0, 0, 0, 0, 0, 0,
4248                2, 0, 0, 0, 0, 0, 0, 5, 82, 0, 0, 0, 0, 0, 2, 0, 0, 90, 105,
4249                102, 0, 0, 5, 0, 84, 90, 105, 84, 77, 10, 0, 0, 0, 102, 0, 0,
4250                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 90, 195, 190, 10, 84,
4251                90, 77, 49, 84, 90, 105, 102, 49, 44, 74, 51, 44, 50, 10,
4252            ],
4253        );
4254    }
4255
4256    /// A regression test where a TZ lookup for the minimum civil datetime
4257    /// resulted in a panic in the TZif handling.
4258    #[cfg(feature = "alloc")]
4259    #[test]
4260    fn regression_tz_lookup_datetime_min() {
4261        use alloc::string::ToString;
4262
4263        let test_file = TzifTestFile::get("America/Boa_Vista");
4264        let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
4265        let err = tz.to_timestamp(DateTime::MIN).unwrap_err();
4266        assert_eq!(
4267            err.to_string(),
4268            "converting datetime with time zone offset `-04:02:40` to timestamp overflowed: parameter 'Unix timestamp seconds' is not in the required range of -377705023201..=253402207200",
4269        );
4270    }
4271}