Skip to main content

jiff/tz/
timezone.rs

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