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    /// Returns the heap memory usage, in bytes, of this timezone.
1400    ///
1401    /// This does **not** include the stack size used up by this timezone.
1402    /// To compute that, use `std::mem::size_of::<TimeZone>()`.
1403    pub fn memory_usage(&self) -> usize {
1404        repr::each! {
1405            &self.repr,
1406            UTC => 0,
1407            UNKNOWN => 0,
1408            FIXED(_offset) => 0,
1409            STATIC_TZIF(_tzif) => 0,
1410            ARC_TZIF(_tzif) => {
1411                core::mem::size_of::<crate::tz::tzif::TzifOwned>() +
1412                (core::mem::size_of::<core::sync::atomic::AtomicUsize>() * 2)
1413            },
1414            ARC_POSIX(_posix) => {
1415                core::mem::size_of::<crate::tz::posix::PosixTimeZoneOwned>() +
1416                (core::mem::size_of::<core::sync::atomic::AtomicUsize>() * 2)
1417            },
1418        }
1419    }
1420}
1421
1422// Exposed APIs for Jiff's time zone proc macro.
1423//
1424// These are NOT part of Jiff's public API. There are *zero* semver guarantees
1425// for them.
1426#[doc(hidden)]
1427impl TimeZone {
1428    pub const fn __internal_from_tzif(
1429        tzif: &'static crate::tz::tzif::TzifStatic,
1430    ) -> TimeZone {
1431        let repr = Repr::static_tzif(tzif);
1432        TimeZone { repr }
1433    }
1434
1435    /// Returns a dumb copy of this `TimeZone`.
1436    ///
1437    /// # Safety
1438    ///
1439    /// Callers must ensure that this time zone is UTC, unknown, a fixed
1440    /// offset or created with `TimeZone::__internal_from_tzif`.
1441    ///
1442    /// Namely, this specifically does not increment the ref count for
1443    /// the `Arc` pointers when the tag is `ARC_TZIF` or `ARC_POSIX`.
1444    /// This means that incorrect usage of this routine can lead to
1445    /// use-after-free.
1446    #[inline]
1447    pub const unsafe fn copy(&self) -> TimeZone {
1448        // SAFETY: Requirements are forwarded to the caller.
1449        unsafe { TimeZone { repr: self.repr.copy() } }
1450    }
1451}
1452
1453impl core::fmt::Debug for TimeZone {
1454    #[inline]
1455    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1456        f.debug_tuple("TimeZone").field(&self.repr).finish()
1457    }
1458}
1459
1460/// A representation a single time zone transition.
1461///
1462/// A time zone transition is an instant in time the marks the beginning of
1463/// a change in the offset from UTC that civil time is computed from in a
1464/// particular time zone. For example, when daylight saving time comes into
1465/// effect (or goes away). Another example is when a geographic region changes
1466/// its permanent offset from UTC.
1467///
1468/// This is a low level type that you generally shouldn't need. It's useful in
1469/// cases where you need to know something about the specific instants at which
1470/// time zone transitions occur. For example, an embedded device might need to
1471/// be explicitly programmed with daylight saving time transitions. APIs like
1472/// this enable callers to explore those transitions.
1473///
1474/// This type is yielded by the iterators
1475/// [`TimeZonePrecedingTransitions`] and
1476/// [`TimeZoneFollowingTransitions`]. The iterators are created by
1477/// [`TimeZone::preceding`] and [`TimeZone::following`], respectively.
1478///
1479/// # Example
1480///
1481/// This shows a somewhat silly example that finds all of the unique civil
1482/// (or "clock" or "local") times at which a time zone transition has occurred
1483/// in a particular time zone:
1484///
1485/// ```
1486/// use std::collections::BTreeSet;
1487/// use jiff::{civil, tz::TimeZone};
1488///
1489/// let tz = TimeZone::get("America/New_York")?;
1490/// let now = civil::date(2024, 12, 31).at(18, 25, 0, 0).to_zoned(tz.clone())?;
1491/// let mut set = BTreeSet::new();
1492/// for trans in tz.preceding(now.timestamp()) {
1493///     let time = tz.to_datetime(trans.timestamp()).time();
1494///     set.insert(time);
1495/// }
1496/// assert_eq!(Vec::from_iter(set), vec![
1497///     civil::time(1, 0, 0, 0),  // typical transition out of DST
1498///     civil::time(3, 0, 0, 0),  // typical transition into DST
1499///     civil::time(12, 0, 0, 0), // from when IANA starts keeping track
1500///     civil::time(19, 0, 0, 0), // from World War 2
1501/// ]);
1502///
1503/// # Ok::<(), Box<dyn std::error::Error>>(())
1504/// ```
1505#[derive(Clone, Debug)]
1506pub struct TimeZoneTransition<'t> {
1507    // We don't currently do anything smart to make iterating over
1508    // transitions faster. We could if we pushed the iterator impl down into
1509    // the respective modules (`posix` and `tzif`), but it's not clear such
1510    // optimization is really worth it. However, this API should permit that
1511    // kind of optimization in the future.
1512    pub(crate) timestamp: Timestamp,
1513    pub(crate) offset: Offset,
1514    pub(crate) abbrev: &'t str,
1515    pub(crate) dst: Dst,
1516}
1517
1518impl<'t> TimeZoneTransition<'t> {
1519    /// Returns the timestamp at which this transition began.
1520    ///
1521    /// # Example
1522    ///
1523    /// ```
1524    /// use jiff::{civil, tz::TimeZone};
1525    ///
1526    /// let tz = TimeZone::get("US/Eastern")?;
1527    /// // Look for the first time zone transition in `US/Eastern` following
1528    /// // 2023-03-09 00:00:00.
1529    /// let start = civil::date(2024, 3, 9).to_zoned(tz.clone())?.timestamp();
1530    /// let next = tz.following(start).next().unwrap();
1531    /// assert_eq!(
1532    ///     next.timestamp().to_zoned(tz.clone()).to_string(),
1533    ///     "2024-03-10T03:00:00-04:00[US/Eastern]",
1534    /// );
1535    ///
1536    /// # Ok::<(), Box<dyn std::error::Error>>(())
1537    /// ```
1538    #[inline]
1539    pub fn timestamp(&self) -> Timestamp {
1540        self.timestamp
1541    }
1542
1543    /// Returns the offset corresponding to this time zone transition. All
1544    /// instants at and following this transition's timestamp (and before the
1545    /// next transition's timestamp) need to apply this offset from UTC to get
1546    /// the civil or "local" time in the corresponding time zone.
1547    ///
1548    /// # Example
1549    ///
1550    /// ```
1551    /// use jiff::{civil, tz::{TimeZone, offset}};
1552    ///
1553    /// let tz = TimeZone::get("US/Eastern")?;
1554    /// // Get the offset of the next transition after
1555    /// // 2023-03-09 00:00:00.
1556    /// let start = civil::date(2024, 3, 9).to_zoned(tz.clone())?.timestamp();
1557    /// let next = tz.following(start).next().unwrap();
1558    /// assert_eq!(next.offset(), offset(-4));
1559    /// // Or go backwards to find the previous transition.
1560    /// let prev = tz.preceding(start).next().unwrap();
1561    /// assert_eq!(prev.offset(), offset(-5));
1562    ///
1563    /// # Ok::<(), Box<dyn std::error::Error>>(())
1564    /// ```
1565    #[inline]
1566    pub fn offset(&self) -> Offset {
1567        self.offset
1568    }
1569
1570    /// Returns the time zone abbreviation corresponding to this time
1571    /// zone transition. All instants at and following this transition's
1572    /// timestamp (and before the next transition's timestamp) may use this
1573    /// abbreviation when creating a human readable string. For example,
1574    /// this is the abbreviation used with the `%Z` specifier with Jiff's
1575    /// [`fmt::strtime`](crate::fmt::strtime) module.
1576    ///
1577    /// Note that abbreviations can to be ambiguous. For example, the
1578    /// abbreviation `CST` can be used for the time zones `Asia/Shanghai`,
1579    /// `America/Chicago` and `America/Havana`.
1580    ///
1581    /// The lifetime of the string returned is tied to this
1582    /// `TimeZoneTransition`, which may be shorter than `'t` (the lifetime of
1583    /// the time zone this transition was created from).
1584    ///
1585    /// # Example
1586    ///
1587    /// ```
1588    /// use jiff::{civil, tz::TimeZone};
1589    ///
1590    /// let tz = TimeZone::get("US/Eastern")?;
1591    /// // Get the abbreviation of the next transition after
1592    /// // 2023-03-09 00:00:00.
1593    /// let start = civil::date(2024, 3, 9).to_zoned(tz.clone())?.timestamp();
1594    /// let next = tz.following(start).next().unwrap();
1595    /// assert_eq!(next.abbreviation(), "EDT");
1596    /// // Or go backwards to find the previous transition.
1597    /// let prev = tz.preceding(start).next().unwrap();
1598    /// assert_eq!(prev.abbreviation(), "EST");
1599    ///
1600    /// # Ok::<(), Box<dyn std::error::Error>>(())
1601    /// ```
1602    #[inline]
1603    pub fn abbreviation<'a>(&'a self) -> &'a str {
1604        self.abbrev
1605    }
1606
1607    /// Returns whether daylight saving time is enabled for this time zone
1608    /// transition.
1609    ///
1610    /// Callers should generally treat this as informational only. In
1611    /// particular, not all time zone transitions are related to daylight
1612    /// saving time. For example, some transitions are a result of a region
1613    /// permanently changing their offset from UTC.
1614    ///
1615    /// # Example
1616    ///
1617    /// ```
1618    /// use jiff::{civil, tz::{Dst, TimeZone}};
1619    ///
1620    /// let tz = TimeZone::get("US/Eastern")?;
1621    /// // Get the DST status of the next transition after
1622    /// // 2023-03-09 00:00:00.
1623    /// let start = civil::date(2024, 3, 9).to_zoned(tz.clone())?.timestamp();
1624    /// let next = tz.following(start).next().unwrap();
1625    /// assert_eq!(next.dst(), Dst::Yes);
1626    /// // Or go backwards to find the previous transition.
1627    /// let prev = tz.preceding(start).next().unwrap();
1628    /// assert_eq!(prev.dst(), Dst::No);
1629    ///
1630    /// # Ok::<(), Box<dyn std::error::Error>>(())
1631    /// ```
1632    #[inline]
1633    pub fn dst(&self) -> Dst {
1634        self.dst
1635    }
1636}
1637
1638/// An offset along with DST status and a time zone abbreviation.
1639///
1640/// This information can be computed from a [`TimeZone`] given a [`Timestamp`]
1641/// via [`TimeZone::to_offset_info`].
1642///
1643/// Generally, the extra information associated with the offset is not commonly
1644/// needed. And indeed, inspecting the daylight saving time status of a
1645/// particular instant in a time zone _usually_ leads to bugs. For example, not
1646/// all time zone transitions are the result of daylight saving time. Some are
1647/// the result of permanent changes to the standard UTC offset of a region.
1648///
1649/// This information is available via an API distinct from
1650/// [`TimeZone::to_offset`] because it is not commonly needed and because it
1651/// can sometimes be more expensive to compute.
1652///
1653/// The main use case for daylight saving time status or time zone
1654/// abbreviations is for formatting datetimes in an end user's locale. If you
1655/// want this, consider using the [`icu`] crate via [`jiff-icu`].
1656///
1657/// The lifetime parameter `'t` corresponds to the lifetime of the `TimeZone`
1658/// that this info was extracted from.
1659///
1660/// # Example
1661///
1662/// ```
1663/// use jiff::{tz::{self, Dst, TimeZone}, Timestamp};
1664///
1665/// let tz = TimeZone::get("America/New_York")?;
1666///
1667/// // A timestamp in DST in New York.
1668/// let ts = Timestamp::from_second(1_720_493_204)?;
1669/// let info = tz.to_offset_info(ts);
1670/// assert_eq!(info.offset(), tz::offset(-4));
1671/// assert_eq!(info.dst(), Dst::Yes);
1672/// assert_eq!(info.abbreviation(), "EDT");
1673/// assert_eq!(
1674///     info.offset().to_datetime(ts).to_string(),
1675///     "2024-07-08T22:46:44",
1676/// );
1677///
1678/// // A timestamp *not* in DST in New York.
1679/// let ts = Timestamp::from_second(1_704_941_204)?;
1680/// let info = tz.to_offset_info(ts);
1681/// assert_eq!(info.offset(), tz::offset(-5));
1682/// assert_eq!(info.dst(), Dst::No);
1683/// assert_eq!(info.abbreviation(), "EST");
1684/// assert_eq!(
1685///     info.offset().to_datetime(ts).to_string(),
1686///     "2024-01-10T21:46:44",
1687/// );
1688///
1689/// # Ok::<(), Box<dyn std::error::Error>>(())
1690/// ```
1691///
1692/// [`icu`]: https://docs.rs/icu
1693/// [`jiff-icu`]: https://docs.rs/jiff-icu
1694#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1695pub struct TimeZoneOffsetInfo<'t> {
1696    pub(crate) offset: Offset,
1697    pub(crate) dst: Dst,
1698    pub(crate) abbreviation: TimeZoneAbbreviation<'t>,
1699}
1700
1701impl<'t> TimeZoneOffsetInfo<'t> {
1702    /// Returns the offset.
1703    ///
1704    /// The offset is duration, from UTC, that should be used to offset the
1705    /// civil time in a particular location.
1706    ///
1707    /// # Example
1708    ///
1709    /// ```
1710    /// use jiff::{civil, tz::{TimeZone, offset}};
1711    ///
1712    /// let tz = TimeZone::get("US/Eastern")?;
1713    /// // Get the offset for 2023-03-10 00:00:00.
1714    /// let start = civil::date(2024, 3, 10).to_zoned(tz.clone())?.timestamp();
1715    /// let info = tz.to_offset_info(start);
1716    /// assert_eq!(info.offset(), offset(-5));
1717    /// // Go forward a day and notice the offset changes due to DST!
1718    /// let start = civil::date(2024, 3, 11).to_zoned(tz.clone())?.timestamp();
1719    /// let info = tz.to_offset_info(start);
1720    /// assert_eq!(info.offset(), offset(-4));
1721    ///
1722    /// # Ok::<(), Box<dyn std::error::Error>>(())
1723    /// ```
1724    #[inline]
1725    pub fn offset(&self) -> Offset {
1726        self.offset
1727    }
1728
1729    /// Returns the time zone abbreviation corresponding to this offset info.
1730    ///
1731    /// Note that abbreviations can to be ambiguous. For example, the
1732    /// abbreviation `CST` can be used for the time zones `Asia/Shanghai`,
1733    /// `America/Chicago` and `America/Havana`.
1734    ///
1735    /// The lifetime of the string returned is tied to this
1736    /// `TimeZoneOffsetInfo`, which may be shorter than `'t` (the lifetime of
1737    /// the time zone this transition was created from).
1738    ///
1739    /// # Example
1740    ///
1741    /// ```
1742    /// use jiff::{civil, tz::TimeZone};
1743    ///
1744    /// let tz = TimeZone::get("US/Eastern")?;
1745    /// // Get the time zone abbreviation for 2023-03-10 00:00:00.
1746    /// let start = civil::date(2024, 3, 10).to_zoned(tz.clone())?.timestamp();
1747    /// let info = tz.to_offset_info(start);
1748    /// assert_eq!(info.abbreviation(), "EST");
1749    /// // Go forward a day and notice the abbreviation changes due to DST!
1750    /// let start = civil::date(2024, 3, 11).to_zoned(tz.clone())?.timestamp();
1751    /// let info = tz.to_offset_info(start);
1752    /// assert_eq!(info.abbreviation(), "EDT");
1753    ///
1754    /// # Ok::<(), Box<dyn std::error::Error>>(())
1755    /// ```
1756    #[inline]
1757    pub fn abbreviation(&self) -> &str {
1758        self.abbreviation.as_str()
1759    }
1760
1761    /// Returns whether daylight saving time is enabled for this offset
1762    /// info.
1763    ///
1764    /// Callers should generally treat this as informational only. In
1765    /// particular, not all time zone transitions are related to daylight
1766    /// saving time. For example, some transitions are a result of a region
1767    /// permanently changing their offset from UTC.
1768    ///
1769    /// # Example
1770    ///
1771    /// ```
1772    /// use jiff::{civil, tz::{Dst, TimeZone}};
1773    ///
1774    /// let tz = TimeZone::get("US/Eastern")?;
1775    /// // Get the DST status of 2023-03-11 00:00:00.
1776    /// let start = civil::date(2024, 3, 11).to_zoned(tz.clone())?.timestamp();
1777    /// let info = tz.to_offset_info(start);
1778    /// assert_eq!(info.dst(), Dst::Yes);
1779    ///
1780    /// # Ok::<(), Box<dyn std::error::Error>>(())
1781    /// ```
1782    #[inline]
1783    pub fn dst(&self) -> Dst {
1784        self.dst
1785    }
1786}
1787
1788/// An iterator over time zone transitions going backward in time.
1789///
1790/// This iterator is created by [`TimeZone::preceding`].
1791///
1792/// # Example: show the 5 previous time zone transitions
1793///
1794/// This shows how to find the 5 preceding time zone transitions (from a
1795/// particular datetime) for a particular time zone:
1796///
1797/// ```
1798/// use jiff::{tz::offset, Zoned};
1799///
1800/// let now: Zoned = "2024-12-31 18:25-05[US/Eastern]".parse()?;
1801/// let transitions = now
1802///     .time_zone()
1803///     .preceding(now.timestamp())
1804///     .take(5)
1805///     .map(|t| (
1806///         t.timestamp().to_zoned(now.time_zone().clone()),
1807///         t.offset(),
1808///         t.abbreviation().to_string(),
1809///     ))
1810///     .collect::<Vec<_>>();
1811/// assert_eq!(transitions, vec![
1812///     ("2024-11-03 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
1813///     ("2024-03-10 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
1814///     ("2023-11-05 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
1815///     ("2023-03-12 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
1816///     ("2022-11-06 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
1817/// ]);
1818///
1819/// # Ok::<(), Box<dyn std::error::Error>>(())
1820/// ```
1821#[derive(Clone, Debug)]
1822pub struct TimeZonePrecedingTransitions<'t> {
1823    tz: &'t TimeZone,
1824    cur: Timestamp,
1825}
1826
1827impl<'t> Iterator for TimeZonePrecedingTransitions<'t> {
1828    type Item = TimeZoneTransition<'t>;
1829
1830    fn next(&mut self) -> Option<TimeZoneTransition<'t>> {
1831        let trans = self.tz.previous_transition(self.cur)?;
1832        self.cur = trans.timestamp();
1833        Some(trans)
1834    }
1835}
1836
1837impl<'t> core::iter::FusedIterator for TimeZonePrecedingTransitions<'t> {}
1838
1839/// An iterator over time zone transitions going forward in time.
1840///
1841/// This iterator is created by [`TimeZone::following`].
1842///
1843/// # Example: show the 5 next time zone transitions
1844///
1845/// This shows how to find the 5 following time zone transitions (from a
1846/// particular datetime) for a particular time zone:
1847///
1848/// ```
1849/// use jiff::{tz::offset, Zoned};
1850///
1851/// let now: Zoned = "2024-12-31 18:25-05[US/Eastern]".parse()?;
1852/// let transitions = now
1853///     .time_zone()
1854///     .following(now.timestamp())
1855///     .take(5)
1856///     .map(|t| (
1857///         t.timestamp().to_zoned(now.time_zone().clone()),
1858///         t.offset(),
1859///         t.abbreviation().to_string(),
1860///     ))
1861///     .collect::<Vec<_>>();
1862/// assert_eq!(transitions, vec![
1863///     ("2025-03-09 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
1864///     ("2025-11-02 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
1865///     ("2026-03-08 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
1866///     ("2026-11-01 01:00-05[US/Eastern]".parse()?, offset(-5), "EST".to_string()),
1867///     ("2027-03-14 03:00-04[US/Eastern]".parse()?, offset(-4), "EDT".to_string()),
1868/// ]);
1869///
1870/// # Ok::<(), Box<dyn std::error::Error>>(())
1871/// ```
1872#[derive(Clone, Debug)]
1873pub struct TimeZoneFollowingTransitions<'t> {
1874    tz: &'t TimeZone,
1875    cur: Timestamp,
1876}
1877
1878impl<'t> Iterator for TimeZoneFollowingTransitions<'t> {
1879    type Item = TimeZoneTransition<'t>;
1880
1881    fn next(&mut self) -> Option<TimeZoneTransition<'t>> {
1882        let trans = self.tz.next_transition(self.cur)?;
1883        self.cur = trans.timestamp();
1884        Some(trans)
1885    }
1886}
1887
1888impl<'t> core::iter::FusedIterator for TimeZoneFollowingTransitions<'t> {}
1889
1890/// A helper type for converting a `TimeZone` to a succinct human readable
1891/// description.
1892///
1893/// This is principally used in error messages in various places.
1894///
1895/// A previous iteration of this was just an `as_str() -> &str` method on
1896/// `TimeZone`, but that's difficult to do without relying on dynamic memory
1897/// allocation (or chunky arrays).
1898pub(crate) struct DiagnosticName<'a>(&'a TimeZone);
1899
1900impl<'a> core::fmt::Display for DiagnosticName<'a> {
1901    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1902        repr::each! {
1903            &self.0.repr,
1904            UTC => f.write_str("UTC"),
1905            UNKNOWN => f.write_str("Etc/Unknown"),
1906            FIXED(offset) => offset.fmt(f),
1907            STATIC_TZIF(tzif) => f.write_str(tzif.name().unwrap_or("Local")),
1908            ARC_TZIF(tzif) => f.write_str(tzif.name().unwrap_or("Local")),
1909            ARC_POSIX(posix) => posix.fmt(f),
1910        }
1911    }
1912}
1913
1914/// A light abstraction over different representations of a time zone
1915/// abbreviation.
1916///
1917/// The lifetime parameter `'t` corresponds to the lifetime of the time zone
1918/// that produced this abbreviation.
1919#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
1920pub(crate) enum TimeZoneAbbreviation<'t> {
1921    /// For when the abbreviation is borrowed directly from other data. For
1922    /// example, from TZif or from POSIX TZ strings.
1923    Borrowed(&'t str),
1924    /// For when the abbreviation has to be derived from other data. For
1925    /// example, from a fixed offset.
1926    ///
1927    /// The idea here is that a `TimeZone` shouldn't need to store the
1928    /// string representation of a fixed offset. Particularly in core-only
1929    /// environments, this is quite wasteful. So we make the string on-demand
1930    /// only when it's requested.
1931    ///
1932    /// An alternative design is to just implement `Display` and reuse
1933    /// `Offset`'s `Display` impl, but then we couldn't offer a `-> &str` API.
1934    /// I feel like that's just a bit overkill, and really just comes from the
1935    /// core-only straight-jacket.
1936    Owned(ArrayStr<9>),
1937}
1938
1939impl<'t> TimeZoneAbbreviation<'t> {
1940    /// Returns this abbreviation as a string borrowed from `self`.
1941    ///
1942    /// Notice that, like `Cow`, the lifetime of the string returned is
1943    /// tied to `self` and thus may be shorter than `'t`.
1944    fn as_str<'a>(&'a self) -> &'a str {
1945        match *self {
1946            TimeZoneAbbreviation::Borrowed(s) => s,
1947            TimeZoneAbbreviation::Owned(ref s) => s.as_str(),
1948        }
1949    }
1950}
1951
1952/// This module defines the internal representation of a `TimeZone`.
1953///
1954/// This module exists to _encapsulate_ the representation rigorously and
1955/// expose a safe and sound API.
1956// To squash warnings on older versions of Rust. Our polyfill below should
1957// match what std does on newer versions of Rust, so the confusability should
1958// be fine. ---AG
1959#[allow(unstable_name_collisions)]
1960mod repr {
1961    use core::mem::ManuallyDrop;
1962
1963    use crate::{tz::tzif::TzifStatic, util::constant::unwrap};
1964    #[cfg(feature = "alloc")]
1965    use crate::{
1966        tz::{posix::PosixTimeZoneOwned, tzif::TzifOwned},
1967        util::sync::Arc,
1968    };
1969
1970    use super::Offset;
1971
1972    // On Rust 1.84+, `StrictProvenancePolyfill` isn't actually used.
1973    #[allow(unused_imports)]
1974    use self::polyfill::{without_provenance, StrictProvenancePolyfill};
1975
1976    /// A macro for "matching" over the time zone representation variants.
1977    ///
1978    /// This macro is safe to use.
1979    ///
1980    /// Note that the `ARC_TZIF` and `ARC_POSIX` branches are automatically
1981    /// removed when `alloc` isn't enabled. Users of this macro needn't handle
1982    /// the `cfg` themselves.
1983    macro_rules! each {
1984        (
1985            $repr:expr,
1986            UTC => $utc:expr,
1987            UNKNOWN => $unknown:expr,
1988            FIXED($offset:ident) => $fixed:expr,
1989            STATIC_TZIF($static_tzif:ident) => $static_tzif_block:expr,
1990            ARC_TZIF($arc_tzif:ident) => $arc_tzif_block:expr,
1991            ARC_POSIX($arc_posix:ident) => $arc_posix_block:expr,
1992        ) => {{
1993            let repr = $repr;
1994            match repr.tag() {
1995                Repr::UTC => $utc,
1996                Repr::UNKNOWN => $unknown,
1997                Repr::FIXED => {
1998                    // SAFETY: We've ensured our pointer tag is correct.
1999                    let $offset = unsafe { repr.get_fixed() };
2000                    $fixed
2001                }
2002                Repr::STATIC_TZIF => {
2003                    // SAFETY: We've ensured our pointer tag is correct.
2004                    let $static_tzif = unsafe { repr.get_static_tzif() };
2005                    $static_tzif_block
2006                }
2007                #[cfg(feature = "alloc")]
2008                Repr::ARC_TZIF => {
2009                    // SAFETY: We've ensured our pointer tag is correct.
2010                    let $arc_tzif = unsafe { repr.get_arc_tzif() };
2011                    $arc_tzif_block
2012                }
2013                #[cfg(feature = "alloc")]
2014                Repr::ARC_POSIX => {
2015                    // SAFETY: We've ensured our pointer tag is correct.
2016                    let $arc_posix = unsafe { repr.get_arc_posix() };
2017                    $arc_posix_block
2018                }
2019                _ => {
2020                    debug_assert!(false, "each: invalid time zone repr tag!");
2021                    // SAFETY: The constructors for `Repr` guarantee that the
2022                    // tag is always one of the values matched above.
2023                    unsafe {
2024                        core::hint::unreachable_unchecked();
2025                    }
2026                }
2027            }
2028        }};
2029    }
2030    pub(super) use each;
2031
2032    /// The internal representation of a `TimeZone`.
2033    ///
2034    /// It has 6 different possible variants: `UTC`, `Etc/Unknown`, fixed
2035    /// offset, `static` TZif, `Arc` TZif or `Arc` POSIX time zone.
2036    ///
2037    /// This design uses pointer tagging so that:
2038    ///
2039    /// * The size of a `TimeZone` stays no bigger than a single word.
2040    /// * In core-only environments, a `TimeZone` can be created from
2041    ///   compile-time TZif data without allocating.
2042    /// * UTC, unknown and fixed offset time zone does not require allocating.
2043    /// * We can still alloc for TZif and POSIX time zones created at runtime.
2044    ///   (Allocating for TZif at runtime is the intended common case, and
2045    ///   corresponds to reading `/usr/share/zoneinfo` entries.)
2046    ///
2047    /// We achieve this through pointer tagging and careful use of a strict
2048    /// provenance polyfill (because of MSRV). We use the lower 4 bits of a
2049    /// pointer to indicate which variant we have. This is sound because we
2050    /// require all types that we allocate for to have a minimum alignment of
2051    /// 8 bytes.
2052    pub(super) struct Repr {
2053        ptr: *const u8,
2054    }
2055
2056    impl Repr {
2057        const BITS: usize = 0b111;
2058        pub(super) const UTC: usize = 1;
2059        pub(super) const UNKNOWN: usize = 2;
2060        pub(super) const FIXED: usize = 3;
2061        pub(super) const STATIC_TZIF: usize = 0;
2062        pub(super) const ARC_TZIF: usize = 4;
2063        pub(super) const ARC_POSIX: usize = 5;
2064
2065        // The minimum alignment required for any heap allocated time zone
2066        // variants. This is related to the number of tags. We have 6 distinct
2067        // values above, which means we need an alignment of at least 6. Since
2068        // alignment must be a power of 2, the smallest possible alignment
2069        // is 8.
2070        const ALIGN: usize = 8;
2071
2072        /// Creates a representation for a `UTC` time zone.
2073        #[inline]
2074        pub(super) const fn utc() -> Repr {
2075            let ptr = without_provenance(Repr::UTC);
2076            Repr { ptr }
2077        }
2078
2079        /// Creates a representation for a `Etc/Unknown` time zone.
2080        #[inline]
2081        pub(super) const fn unknown() -> Repr {
2082            let ptr = without_provenance(Repr::UNKNOWN);
2083            Repr { ptr }
2084        }
2085
2086        /// Creates a representation for a fixed offset time zone.
2087        #[inline]
2088        pub(super) const fn fixed(offset: Offset) -> Repr {
2089            let seconds = offset.seconds();
2090            // OK because offset is in -93599..=93599.
2091            let shifted = unwrap!(
2092                seconds.checked_shl(4),
2093                "offset small enough for left shift by 4 bits",
2094            );
2095            assert!(usize::MAX >= 4_294_967_295);
2096            // usize cast is okay because Jiff requires 32-bit.
2097            let ptr = without_provenance((shifted as usize) | Repr::FIXED);
2098            Repr { ptr }
2099        }
2100
2101        /// Creates a representation for a created-at-compile-time TZif time
2102        /// zone.
2103        ///
2104        /// This can only be correctly called by the `jiff-static` proc macro.
2105        #[inline]
2106        pub(super) const fn static_tzif(tzif: &'static TzifStatic) -> Repr {
2107            assert!(core::mem::align_of::<TzifStatic>() >= Repr::ALIGN);
2108            let tzif = (tzif as *const TzifStatic).cast::<u8>();
2109            // We very specifically do no materialize the pointer address here
2110            // because 1) it's UB and 2) the compiler generally prevents. This
2111            // is because in a const context, the specific pointer address
2112            // cannot be relied upon. Yet, we still want to do pointer tagging.
2113            //
2114            // Thankfully, this is the only variant that is a pointer that
2115            // we want to create in a const context. So we just make this
2116            // variant's tag `0`, and thus, no explicit pointer tagging is
2117            // required. (Because we ensure the alignment is at least 4, and
2118            // thus the least significant 3 bits are 0.)
2119            //
2120            // If this ends up not working out or if we need to support
2121            // another `static` variant, then we could perhaps to pointer
2122            // tagging with pointer arithmetic (like what the `tagged-pointer`
2123            // crate does). I haven't tried it though and I'm unclear if it
2124            // work.
2125            Repr { ptr: tzif }
2126        }
2127
2128        /// Creates a representation for a TZif time zone.
2129        #[cfg(feature = "alloc")]
2130        #[inline]
2131        pub(super) fn arc_tzif(tzif: Arc<TzifOwned>) -> Repr {
2132            assert!(core::mem::align_of::<TzifOwned>() >= Repr::ALIGN);
2133            let tzif = Arc::into_raw(tzif).cast::<u8>();
2134            assert!(tzif.addr() % 4 == 0);
2135            let ptr = tzif.map_addr(|addr| addr | Repr::ARC_TZIF);
2136            Repr { ptr }
2137        }
2138
2139        /// Creates a representation for a POSIX time zone.
2140        #[cfg(feature = "alloc")]
2141        #[inline]
2142        pub(super) fn arc_posix(posix_tz: Arc<PosixTimeZoneOwned>) -> Repr {
2143            assert!(
2144                core::mem::align_of::<PosixTimeZoneOwned>() >= Repr::ALIGN
2145            );
2146            let posix_tz = Arc::into_raw(posix_tz).cast::<u8>();
2147            assert!(posix_tz.addr() % 4 == 0);
2148            let ptr = posix_tz.map_addr(|addr| addr | Repr::ARC_POSIX);
2149            Repr { ptr }
2150        }
2151
2152        /// Gets the offset representation.
2153        ///
2154        /// # Safety
2155        ///
2156        /// Callers must ensure that the pointer tag is `FIXED`.
2157        #[inline]
2158        pub(super) unsafe fn get_fixed(&self) -> Offset {
2159            #[allow(unstable_name_collisions)]
2160            let addr = self.ptr.addr();
2161            // NOTE: Because of sign extension, we need to cast to `i32`
2162            // before shifting.
2163            Offset::from_seconds_unchecked((addr as i32) >> 4)
2164        }
2165
2166        /// Returns true if and only if this representation corresponds to the
2167        /// `Etc/Unknown` time zone.
2168        #[inline]
2169        pub(super) fn is_unknown(&self) -> bool {
2170            self.tag() == Repr::UNKNOWN
2171        }
2172
2173        /// Gets the static TZif representation.
2174        ///
2175        /// # Safety
2176        ///
2177        /// Callers must ensure that the pointer tag is `STATIC_TZIF`.
2178        #[inline]
2179        pub(super) unsafe fn get_static_tzif(&self) -> &'static TzifStatic {
2180            #[allow(unstable_name_collisions)]
2181            let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2182            // SAFETY: Getting a `STATIC_TZIF` tag is only possible when
2183            // `self.ptr` was constructed from a valid and aligned (to at least
2184            // 4 bytes) `&TzifStatic` borrow. Which must be guaranteed by the
2185            // caller. We've also removed the tag bits above, so we must now
2186            // have the original pointer.
2187            unsafe { &*ptr.cast::<TzifStatic>() }
2188        }
2189
2190        /// Gets the `Arc` TZif representation.
2191        ///
2192        /// # Safety
2193        ///
2194        /// Callers must ensure that the pointer tag is `ARC_TZIF`.
2195        #[cfg(feature = "alloc")]
2196        #[inline]
2197        pub(super) unsafe fn get_arc_tzif<'a>(&'a self) -> &'a TzifOwned {
2198            let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2199            // SAFETY: Getting a `ARC_TZIF` tag is only possible when
2200            // `self.ptr` was constructed from a valid and aligned
2201            // (to at least 4 bytes) `Arc<TzifOwned>`. We've removed
2202            // the tag bits above, so we must now have the original
2203            // pointer.
2204            let arc = ManuallyDrop::new(unsafe {
2205                Arc::from_raw(ptr.cast::<TzifOwned>())
2206            });
2207            // SAFETY: The lifetime of the pointer returned is always
2208            // valid as long as the strong count on `arc` is at least
2209            // 1. Since the lifetime is no longer than `Repr` itself,
2210            // and a `Repr` being alive implies there is at least 1
2211            // for the strong `Arc` count, it follows that the lifetime
2212            // returned here is correct.
2213            unsafe { &*Arc::as_ptr(&arc) }
2214        }
2215
2216        /// Gets the `Arc` POSIX time zone representation.
2217        ///
2218        /// # Safety
2219        ///
2220        /// Callers must ensure that the pointer tag is `ARC_POSIX`.
2221        #[cfg(feature = "alloc")]
2222        #[inline]
2223        pub(super) unsafe fn get_arc_posix<'a>(
2224            &'a self,
2225        ) -> &'a PosixTimeZoneOwned {
2226            let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2227            // SAFETY: Getting a `ARC_POSIX` tag is only possible when
2228            // `self.ptr` was constructed from a valid and aligned (to at least
2229            // 4 bytes) `Arc<PosixTimeZoneOwned>`. We've removed the tag
2230            // bits above, so we must now have the original pointer.
2231            let arc = ManuallyDrop::new(unsafe {
2232                Arc::from_raw(ptr.cast::<PosixTimeZoneOwned>())
2233            });
2234            // SAFETY: The lifetime of the pointer returned is always
2235            // valid as long as the strong count on `arc` is at least
2236            // 1. Since the lifetime is no longer than `Repr` itself,
2237            // and a `Repr` being alive implies there is at least 1
2238            // for the strong `Arc` count, it follows that the lifetime
2239            // returned here is correct.
2240            unsafe { &*Arc::as_ptr(&arc) }
2241        }
2242
2243        /// Returns the tag on the representation's pointer.
2244        ///
2245        /// The value is guaranteed to be one of the constant tag values.
2246        #[inline]
2247        pub(super) fn tag(&self) -> usize {
2248            #[allow(unstable_name_collisions)]
2249            {
2250                self.ptr.addr() & Repr::BITS
2251            }
2252        }
2253
2254        /// Returns a dumb copy of this representation.
2255        ///
2256        /// # Safety
2257        ///
2258        /// Callers must ensure that this representation's tag is UTC,
2259        /// UNKNOWN, FIXED or STATIC_TZIF.
2260        ///
2261        /// Namely, this specifically does not increment the ref count for
2262        /// the `Arc` pointers when the tag is `ARC_TZIF` or `ARC_POSIX`.
2263        /// This means that incorrect usage of this routine can lead to
2264        /// use-after-free.
2265        ///
2266        /// NOTE: It would be nice if we could make this `copy` routine safe,
2267        /// or at least panic if it's misused. But to do that, you need to know
2268        /// the time zone variant. And to know the time zone variant, you need
2269        /// to "look" at the tag in the pointer. And looking at the address of
2270        /// a pointer in a `const` context is precarious.
2271        #[inline]
2272        pub(super) const unsafe fn copy(&self) -> Repr {
2273            Repr { ptr: self.ptr }
2274        }
2275    }
2276
2277    // SAFETY: We use automatic reference counting.
2278    unsafe impl Send for Repr {}
2279    // SAFETY: We don't use an interior mutability and otherwise don't permit
2280    // any kind of mutation (other than for an `Arc` managing its ref counts)
2281    // of a `Repr`.
2282    unsafe impl Sync for Repr {}
2283
2284    impl core::fmt::Debug for Repr {
2285        fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2286            each! {
2287                self,
2288                UTC => f.write_str("UTC"),
2289                UNKNOWN => f.write_str("Etc/Unknown"),
2290                FIXED(offset) => core::fmt::Debug::fmt(&offset, f),
2291                STATIC_TZIF(tzif) => {
2292                    // The full debug output is a bit much, so constrain it.
2293                    let field = tzif.name().unwrap_or("Local");
2294                    f.debug_tuple("TZif").field(&field).finish()
2295                },
2296                ARC_TZIF(tzif) => {
2297                    // The full debug output is a bit much, so constrain it.
2298                    let field = tzif.name().unwrap_or("Local");
2299                    f.debug_tuple("TZif").field(&field).finish()
2300                },
2301                ARC_POSIX(posix) => {
2302                    f.write_str("Posix(")?;
2303                    core::fmt::Display::fmt(&posix, f)?;
2304                    f.write_str(")")
2305                },
2306            }
2307        }
2308    }
2309
2310    impl Clone for Repr {
2311        #[inline]
2312        fn clone(&self) -> Repr {
2313            // This `match` is written in an exhaustive fashion so that if
2314            // a new tag is added, it should be explicitly considered here.
2315            match self.tag() {
2316                // These are all `Copy` and can just be memcpy'd as-is.
2317                Repr::UTC
2318                | Repr::UNKNOWN
2319                | Repr::FIXED
2320                | Repr::STATIC_TZIF => Repr { ptr: self.ptr },
2321                #[cfg(feature = "alloc")]
2322                Repr::ARC_TZIF => {
2323                    let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2324                    // SAFETY: Getting a `ARC_TZIF` tag is only possible when
2325                    // `self.ptr` was constructed from a valid and aligned
2326                    // (to at least 4 bytes) `Arc<TzifOwned>`. We've removed
2327                    // the tag bits above, so we must now have the original
2328                    // pointer.
2329                    unsafe {
2330                        Arc::increment_strong_count(ptr.cast::<TzifOwned>());
2331                    }
2332                    Repr { ptr: self.ptr }
2333                }
2334                #[cfg(feature = "alloc")]
2335                Repr::ARC_POSIX => {
2336                    let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2337                    // SAFETY: Getting a `ARC_POSIX` tag is only possible when
2338                    // `self.ptr` was constructed from a valid and aligned (to
2339                    // at least 4 bytes) `Arc<PosixTimeZoneOwned>`. We've
2340                    // removed the tag bits above, so we must now have the
2341                    // original pointer.
2342                    unsafe {
2343                        Arc::increment_strong_count(
2344                            ptr.cast::<PosixTimeZoneOwned>(),
2345                        );
2346                    }
2347                    Repr { ptr: self.ptr }
2348                }
2349                _ => {
2350                    debug_assert!(false, "clone: invalid time zone repr tag!");
2351                    // SAFETY: The constructors for `Repr` guarantee that the
2352                    // tag is always one of the values matched above.
2353                    unsafe {
2354                        core::hint::unreachable_unchecked();
2355                    }
2356                }
2357            }
2358        }
2359    }
2360
2361    impl Drop for Repr {
2362        #[inline]
2363        fn drop(&mut self) {
2364            // This `match` is written in an exhaustive fashion so that if
2365            // a new tag is added, it should be explicitly considered here.
2366            match self.tag() {
2367                // These are all `Copy` and have no destructor.
2368                Repr::UTC
2369                | Repr::UNKNOWN
2370                | Repr::FIXED
2371                | Repr::STATIC_TZIF => {}
2372                #[cfg(feature = "alloc")]
2373                Repr::ARC_TZIF => {
2374                    let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2375                    // SAFETY: Getting a `ARC_TZIF` tag is only possible when
2376                    // `self.ptr` was constructed from a valid and aligned
2377                    // (to at least 4 bytes) `Arc<TzifOwned>`. We've removed
2378                    // the tag bits above, so we must now have the original
2379                    // pointer.
2380                    unsafe {
2381                        Arc::decrement_strong_count(ptr.cast::<TzifOwned>());
2382                    }
2383                }
2384                #[cfg(feature = "alloc")]
2385                Repr::ARC_POSIX => {
2386                    let ptr = self.ptr.map_addr(|addr| addr & !Repr::BITS);
2387                    // SAFETY: Getting a `ARC_POSIX` tag is only possible when
2388                    // `self.ptr` was constructed from a valid and aligned (to
2389                    // at least 4 bytes) `Arc<PosixTimeZoneOwned>`. We've
2390                    // removed the tag bits above, so we must now have the
2391                    // original pointer.
2392                    unsafe {
2393                        Arc::decrement_strong_count(
2394                            ptr.cast::<PosixTimeZoneOwned>(),
2395                        );
2396                    }
2397                }
2398                _ => {
2399                    debug_assert!(false, "drop: invalid time zone repr tag!");
2400                    // SAFETY: The constructors for `Repr` guarantee that the
2401                    // tag is always one of the values matched above.
2402                    unsafe {
2403                        core::hint::unreachable_unchecked();
2404                    }
2405                }
2406            }
2407        }
2408    }
2409
2410    impl Eq for Repr {}
2411
2412    impl PartialEq for Repr {
2413        fn eq(&self, other: &Repr) -> bool {
2414            if self.tag() != other.tag() {
2415                return false;
2416            }
2417            each! {
2418                self,
2419                UTC => true,
2420                UNKNOWN => true,
2421                // SAFETY: OK, because we know the tags are equivalent and
2422                // `self` has a `FIXED` tag.
2423                FIXED(offset) => offset == unsafe { other.get_fixed() },
2424                // SAFETY: OK, because we know the tags are equivalent and
2425                // `self` has a `STATIC_TZIF` tag.
2426                STATIC_TZIF(tzif) => tzif == unsafe { other.get_static_tzif() },
2427                // SAFETY: OK, because we know the tags are equivalent and
2428                // `self` has an `ARC_TZIF` tag.
2429                ARC_TZIF(tzif) => tzif == unsafe { other.get_arc_tzif() },
2430                // SAFETY: OK, because we know the tags are equivalent and
2431                // `self` has an `ARC_POSIX` tag.
2432                ARC_POSIX(posix) => posix == unsafe { other.get_arc_posix() },
2433            }
2434        }
2435    }
2436
2437    /// This is a polyfill for a small subset of std's strict provenance APIs.
2438    ///
2439    /// The strict provenance APIs in `core` were stabilized in Rust 1.84,
2440    /// but it will likely be a while before Jiff can use them. (At time of
2441    /// writing, 2025-02-24, Jiff's MSRV is Rust 1.70.)
2442    mod polyfill {
2443        pub(super) const fn without_provenance(addr: usize) -> *const u8 {
2444            // SAFETY: Every valid `usize` is also a valid pointer (but not
2445            // necessarily legal to dereference).
2446            //
2447            // MSRV(1.84): We *really* ought to be using
2448            // `core::ptr::without_provenance` here, but Jiff's MSRV prevents
2449            // us.
2450            #[allow(integer_to_ptr_transmutes)]
2451            unsafe {
2452                core::mem::transmute(addr)
2453            }
2454        }
2455
2456        // On Rust 1.84+, `StrictProvenancePolyfill` isn't actually used.
2457        #[allow(dead_code)]
2458        pub(super) trait StrictProvenancePolyfill:
2459            Sized + Clone + Copy
2460        {
2461            fn addr(&self) -> usize;
2462            fn with_addr(&self, addr: usize) -> Self;
2463            fn map_addr(&self, map: impl FnOnce(usize) -> usize) -> Self {
2464                self.with_addr(map(self.addr()))
2465            }
2466        }
2467
2468        impl StrictProvenancePolyfill for *const u8 {
2469            fn addr(&self) -> usize {
2470                // SAFETY: Pointer-to-integer transmutes are valid (if you are
2471                // okay with losing the provenance).
2472                //
2473                // The implementation in std says that this isn't guaranteed to
2474                // be sound outside of std, but I'm not sure how else to do it.
2475                // In practice, this seems likely fine?
2476                unsafe { core::mem::transmute(self.cast::<()>()) }
2477            }
2478
2479            fn with_addr(&self, address: usize) -> Self {
2480                let self_addr = self.addr() as isize;
2481                let dest_addr = address as isize;
2482                let offset = dest_addr.wrapping_sub(self_addr);
2483                self.wrapping_offset(offset)
2484            }
2485        }
2486    }
2487}
2488
2489#[cfg(test)]
2490mod tests {
2491    #[cfg(feature = "alloc")]
2492    use crate::tz::testdata::TzifTestFile;
2493    use crate::{civil::date, tz::offset};
2494
2495    use super::*;
2496
2497    fn unambiguous(offset_hours: i8) -> AmbiguousOffset {
2498        let offset = offset(offset_hours);
2499        o_unambiguous(offset)
2500    }
2501
2502    fn gap(
2503        earlier_offset_hours: i8,
2504        later_offset_hours: i8,
2505    ) -> AmbiguousOffset {
2506        let earlier = offset(earlier_offset_hours);
2507        let later = offset(later_offset_hours);
2508        o_gap(earlier, later)
2509    }
2510
2511    fn fold(
2512        earlier_offset_hours: i8,
2513        later_offset_hours: i8,
2514    ) -> AmbiguousOffset {
2515        let earlier = offset(earlier_offset_hours);
2516        let later = offset(later_offset_hours);
2517        o_fold(earlier, later)
2518    }
2519
2520    fn o_unambiguous(offset: Offset) -> AmbiguousOffset {
2521        AmbiguousOffset::Unambiguous { offset }
2522    }
2523
2524    fn o_gap(earlier: Offset, later: Offset) -> AmbiguousOffset {
2525        AmbiguousOffset::Gap { before: earlier, after: later }
2526    }
2527
2528    fn o_fold(earlier: Offset, later: Offset) -> AmbiguousOffset {
2529        AmbiguousOffset::Fold { before: earlier, after: later }
2530    }
2531
2532    #[cfg(feature = "alloc")]
2533    #[test]
2534    fn time_zone_tzif_to_ambiguous_timestamp() {
2535        let tests: &[(&str, &[_])] = &[
2536            (
2537                "America/New_York",
2538                &[
2539                    ((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
2540                    ((2024, 3, 10, 1, 59, 59, 999_999_999), unambiguous(-5)),
2541                    ((2024, 3, 10, 2, 0, 0, 0), gap(-5, -4)),
2542                    ((2024, 3, 10, 2, 59, 59, 999_999_999), gap(-5, -4)),
2543                    ((2024, 3, 10, 3, 0, 0, 0), unambiguous(-4)),
2544                    ((2024, 11, 3, 0, 59, 59, 999_999_999), unambiguous(-4)),
2545                    ((2024, 11, 3, 1, 0, 0, 0), fold(-4, -5)),
2546                    ((2024, 11, 3, 1, 59, 59, 999_999_999), fold(-4, -5)),
2547                    ((2024, 11, 3, 2, 0, 0, 0), unambiguous(-5)),
2548                ],
2549            ),
2550            (
2551                "Europe/Dublin",
2552                &[
2553                    ((1970, 1, 1, 0, 0, 0, 0), unambiguous(1)),
2554                    ((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
2555                    ((2024, 3, 31, 1, 0, 0, 0), gap(0, 1)),
2556                    ((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 1)),
2557                    ((2024, 3, 31, 2, 0, 0, 0), unambiguous(1)),
2558                    ((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(1)),
2559                    ((2024, 10, 27, 1, 0, 0, 0), fold(1, 0)),
2560                    ((2024, 10, 27, 1, 59, 59, 999_999_999), fold(1, 0)),
2561                    ((2024, 10, 27, 2, 0, 0, 0), unambiguous(0)),
2562                ],
2563            ),
2564            (
2565                "Australia/Tasmania",
2566                &[
2567                    ((1970, 1, 1, 11, 0, 0, 0), unambiguous(11)),
2568                    ((2024, 4, 7, 1, 59, 59, 999_999_999), unambiguous(11)),
2569                    ((2024, 4, 7, 2, 0, 0, 0), fold(11, 10)),
2570                    ((2024, 4, 7, 2, 59, 59, 999_999_999), fold(11, 10)),
2571                    ((2024, 4, 7, 3, 0, 0, 0), unambiguous(10)),
2572                    ((2024, 10, 6, 1, 59, 59, 999_999_999), unambiguous(10)),
2573                    ((2024, 10, 6, 2, 0, 0, 0), gap(10, 11)),
2574                    ((2024, 10, 6, 2, 59, 59, 999_999_999), gap(10, 11)),
2575                    ((2024, 10, 6, 3, 0, 0, 0), unambiguous(11)),
2576                ],
2577            ),
2578            (
2579                "Antarctica/Troll",
2580                &[
2581                    ((1970, 1, 1, 0, 0, 0, 0), unambiguous(0)),
2582                    // test the gap
2583                    ((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
2584                    ((2024, 3, 31, 1, 0, 0, 0), gap(0, 2)),
2585                    ((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 2)),
2586                    // still in the gap!
2587                    ((2024, 3, 31, 2, 0, 0, 0), gap(0, 2)),
2588                    ((2024, 3, 31, 2, 59, 59, 999_999_999), gap(0, 2)),
2589                    // finally out
2590                    ((2024, 3, 31, 3, 0, 0, 0), unambiguous(2)),
2591                    // test the fold
2592                    ((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(2)),
2593                    ((2024, 10, 27, 1, 0, 0, 0), fold(2, 0)),
2594                    ((2024, 10, 27, 1, 59, 59, 999_999_999), fold(2, 0)),
2595                    // still in the fold!
2596                    ((2024, 10, 27, 2, 0, 0, 0), fold(2, 0)),
2597                    ((2024, 10, 27, 2, 59, 59, 999_999_999), fold(2, 0)),
2598                    // finally out
2599                    ((2024, 10, 27, 3, 0, 0, 0), unambiguous(0)),
2600                ],
2601            ),
2602            (
2603                "America/St_Johns",
2604                &[
2605                    (
2606                        (1969, 12, 31, 20, 30, 0, 0),
2607                        o_unambiguous(-Offset::hms(3, 30, 0)),
2608                    ),
2609                    (
2610                        (2024, 3, 10, 1, 59, 59, 999_999_999),
2611                        o_unambiguous(-Offset::hms(3, 30, 0)),
2612                    ),
2613                    (
2614                        (2024, 3, 10, 2, 0, 0, 0),
2615                        o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
2616                    ),
2617                    (
2618                        (2024, 3, 10, 2, 59, 59, 999_999_999),
2619                        o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
2620                    ),
2621                    (
2622                        (2024, 3, 10, 3, 0, 0, 0),
2623                        o_unambiguous(-Offset::hms(2, 30, 0)),
2624                    ),
2625                    (
2626                        (2024, 11, 3, 0, 59, 59, 999_999_999),
2627                        o_unambiguous(-Offset::hms(2, 30, 0)),
2628                    ),
2629                    (
2630                        (2024, 11, 3, 1, 0, 0, 0),
2631                        o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
2632                    ),
2633                    (
2634                        (2024, 11, 3, 1, 59, 59, 999_999_999),
2635                        o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
2636                    ),
2637                    (
2638                        (2024, 11, 3, 2, 0, 0, 0),
2639                        o_unambiguous(-Offset::hms(3, 30, 0)),
2640                    ),
2641                ],
2642            ),
2643            // This time zone has an interesting transition where it jumps
2644            // backwards a full day at 1867-10-19T15:30:00.
2645            (
2646                "America/Sitka",
2647                &[
2648                    ((1969, 12, 31, 16, 0, 0, 0), unambiguous(-8)),
2649                    (
2650                        (-9999, 1, 2, 16, 58, 46, 0),
2651                        o_unambiguous(Offset::hms(14, 58, 47)),
2652                    ),
2653                    (
2654                        (1867, 10, 18, 15, 29, 59, 0),
2655                        o_unambiguous(Offset::hms(14, 58, 47)),
2656                    ),
2657                    (
2658                        (1867, 10, 18, 15, 30, 0, 0),
2659                        // A fold of 24 hours!!!
2660                        o_fold(
2661                            Offset::hms(14, 58, 47),
2662                            -Offset::hms(9, 1, 13),
2663                        ),
2664                    ),
2665                    (
2666                        (1867, 10, 19, 15, 29, 59, 999_999_999),
2667                        // Still in the fold...
2668                        o_fold(
2669                            Offset::hms(14, 58, 47),
2670                            -Offset::hms(9, 1, 13),
2671                        ),
2672                    ),
2673                    (
2674                        (1867, 10, 19, 15, 30, 0, 0),
2675                        // Finally out.
2676                        o_unambiguous(-Offset::hms(9, 1, 13)),
2677                    ),
2678                ],
2679            ),
2680            // As with to_datetime, we test every possible transition
2681            // point here since this time zone has a small number of them.
2682            (
2683                "Pacific/Honolulu",
2684                &[
2685                    (
2686                        (1896, 1, 13, 11, 59, 59, 0),
2687                        o_unambiguous(-Offset::hms(10, 31, 26)),
2688                    ),
2689                    (
2690                        (1896, 1, 13, 12, 0, 0, 0),
2691                        o_gap(
2692                            -Offset::hms(10, 31, 26),
2693                            -Offset::hms(10, 30, 0),
2694                        ),
2695                    ),
2696                    (
2697                        (1896, 1, 13, 12, 1, 25, 0),
2698                        o_gap(
2699                            -Offset::hms(10, 31, 26),
2700                            -Offset::hms(10, 30, 0),
2701                        ),
2702                    ),
2703                    (
2704                        (1896, 1, 13, 12, 1, 26, 0),
2705                        o_unambiguous(-Offset::hms(10, 30, 0)),
2706                    ),
2707                    (
2708                        (1933, 4, 30, 1, 59, 59, 0),
2709                        o_unambiguous(-Offset::hms(10, 30, 0)),
2710                    ),
2711                    (
2712                        (1933, 4, 30, 2, 0, 0, 0),
2713                        o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
2714                    ),
2715                    (
2716                        (1933, 4, 30, 2, 59, 59, 0),
2717                        o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
2718                    ),
2719                    (
2720                        (1933, 4, 30, 3, 0, 0, 0),
2721                        o_unambiguous(-Offset::hms(9, 30, 0)),
2722                    ),
2723                    (
2724                        (1933, 5, 21, 10, 59, 59, 0),
2725                        o_unambiguous(-Offset::hms(9, 30, 0)),
2726                    ),
2727                    (
2728                        (1933, 5, 21, 11, 0, 0, 0),
2729                        o_fold(
2730                            -Offset::hms(9, 30, 0),
2731                            -Offset::hms(10, 30, 0),
2732                        ),
2733                    ),
2734                    (
2735                        (1933, 5, 21, 11, 59, 59, 0),
2736                        o_fold(
2737                            -Offset::hms(9, 30, 0),
2738                            -Offset::hms(10, 30, 0),
2739                        ),
2740                    ),
2741                    (
2742                        (1933, 5, 21, 12, 0, 0, 0),
2743                        o_unambiguous(-Offset::hms(10, 30, 0)),
2744                    ),
2745                    (
2746                        (1942, 2, 9, 1, 59, 59, 0),
2747                        o_unambiguous(-Offset::hms(10, 30, 0)),
2748                    ),
2749                    (
2750                        (1942, 2, 9, 2, 0, 0, 0),
2751                        o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
2752                    ),
2753                    (
2754                        (1942, 2, 9, 2, 59, 59, 0),
2755                        o_gap(-Offset::hms(10, 30, 0), -Offset::hms(9, 30, 0)),
2756                    ),
2757                    (
2758                        (1942, 2, 9, 3, 0, 0, 0),
2759                        o_unambiguous(-Offset::hms(9, 30, 0)),
2760                    ),
2761                    (
2762                        (1945, 8, 14, 13, 29, 59, 0),
2763                        o_unambiguous(-Offset::hms(9, 30, 0)),
2764                    ),
2765                    (
2766                        (1945, 8, 14, 13, 30, 0, 0),
2767                        o_unambiguous(-Offset::hms(9, 30, 0)),
2768                    ),
2769                    (
2770                        (1945, 8, 14, 13, 30, 1, 0),
2771                        o_unambiguous(-Offset::hms(9, 30, 0)),
2772                    ),
2773                    (
2774                        (1945, 9, 30, 0, 59, 59, 0),
2775                        o_unambiguous(-Offset::hms(9, 30, 0)),
2776                    ),
2777                    (
2778                        (1945, 9, 30, 1, 0, 0, 0),
2779                        o_fold(
2780                            -Offset::hms(9, 30, 0),
2781                            -Offset::hms(10, 30, 0),
2782                        ),
2783                    ),
2784                    (
2785                        (1945, 9, 30, 1, 59, 59, 0),
2786                        o_fold(
2787                            -Offset::hms(9, 30, 0),
2788                            -Offset::hms(10, 30, 0),
2789                        ),
2790                    ),
2791                    (
2792                        (1945, 9, 30, 2, 0, 0, 0),
2793                        o_unambiguous(-Offset::hms(10, 30, 0)),
2794                    ),
2795                    (
2796                        (1947, 6, 8, 1, 59, 59, 0),
2797                        o_unambiguous(-Offset::hms(10, 30, 0)),
2798                    ),
2799                    (
2800                        (1947, 6, 8, 2, 0, 0, 0),
2801                        o_gap(-Offset::hms(10, 30, 0), -offset(10)),
2802                    ),
2803                    (
2804                        (1947, 6, 8, 2, 29, 59, 0),
2805                        o_gap(-Offset::hms(10, 30, 0), -offset(10)),
2806                    ),
2807                    ((1947, 6, 8, 2, 30, 0, 0), unambiguous(-10)),
2808                ],
2809            ),
2810        ];
2811        for &(tzname, datetimes_to_ambiguous) in tests {
2812            let test_file = TzifTestFile::get(tzname);
2813            let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
2814            for &(datetime, ambiguous_kind) in datetimes_to_ambiguous {
2815                let (year, month, day, hour, min, sec, nano) = datetime;
2816                let dt = date(year, month, day).at(hour, min, sec, nano);
2817                let got = tz.to_ambiguous_zoned(dt);
2818                assert_eq!(
2819                    got.offset(),
2820                    ambiguous_kind,
2821                    "\nTZ: {tzname}\ndatetime: \
2822                     {year:04}-{month:02}-{day:02}T\
2823                     {hour:02}:{min:02}:{sec:02}.{nano:09}",
2824                );
2825            }
2826        }
2827    }
2828
2829    #[cfg(feature = "alloc")]
2830    #[test]
2831    fn time_zone_tzif_to_datetime() {
2832        let o = |hours| offset(hours);
2833        let tests: &[(&str, &[_])] = &[
2834            (
2835                "America/New_York",
2836                &[
2837                    ((0, 0), o(-5), "EST", (1969, 12, 31, 19, 0, 0, 0)),
2838                    (
2839                        (1710052200, 0),
2840                        o(-5),
2841                        "EST",
2842                        (2024, 3, 10, 1, 30, 0, 0),
2843                    ),
2844                    (
2845                        (1710053999, 999_999_999),
2846                        o(-5),
2847                        "EST",
2848                        (2024, 3, 10, 1, 59, 59, 999_999_999),
2849                    ),
2850                    ((1710054000, 0), o(-4), "EDT", (2024, 3, 10, 3, 0, 0, 0)),
2851                    (
2852                        (1710055800, 0),
2853                        o(-4),
2854                        "EDT",
2855                        (2024, 3, 10, 3, 30, 0, 0),
2856                    ),
2857                    ((1730610000, 0), o(-4), "EDT", (2024, 11, 3, 1, 0, 0, 0)),
2858                    (
2859                        (1730611800, 0),
2860                        o(-4),
2861                        "EDT",
2862                        (2024, 11, 3, 1, 30, 0, 0),
2863                    ),
2864                    (
2865                        (1730613599, 999_999_999),
2866                        o(-4),
2867                        "EDT",
2868                        (2024, 11, 3, 1, 59, 59, 999_999_999),
2869                    ),
2870                    ((1730613600, 0), o(-5), "EST", (2024, 11, 3, 1, 0, 0, 0)),
2871                    (
2872                        (1730615400, 0),
2873                        o(-5),
2874                        "EST",
2875                        (2024, 11, 3, 1, 30, 0, 0),
2876                    ),
2877                ],
2878            ),
2879            (
2880                "Australia/Tasmania",
2881                &[
2882                    ((0, 0), o(11), "AEDT", (1970, 1, 1, 11, 0, 0, 0)),
2883                    (
2884                        (1728142200, 0),
2885                        o(10),
2886                        "AEST",
2887                        (2024, 10, 6, 1, 30, 0, 0),
2888                    ),
2889                    (
2890                        (1728143999, 999_999_999),
2891                        o(10),
2892                        "AEST",
2893                        (2024, 10, 6, 1, 59, 59, 999_999_999),
2894                    ),
2895                    (
2896                        (1728144000, 0),
2897                        o(11),
2898                        "AEDT",
2899                        (2024, 10, 6, 3, 0, 0, 0),
2900                    ),
2901                    (
2902                        (1728145800, 0),
2903                        o(11),
2904                        "AEDT",
2905                        (2024, 10, 6, 3, 30, 0, 0),
2906                    ),
2907                    ((1712415600, 0), o(11), "AEDT", (2024, 4, 7, 2, 0, 0, 0)),
2908                    (
2909                        (1712417400, 0),
2910                        o(11),
2911                        "AEDT",
2912                        (2024, 4, 7, 2, 30, 0, 0),
2913                    ),
2914                    (
2915                        (1712419199, 999_999_999),
2916                        o(11),
2917                        "AEDT",
2918                        (2024, 4, 7, 2, 59, 59, 999_999_999),
2919                    ),
2920                    ((1712419200, 0), o(10), "AEST", (2024, 4, 7, 2, 0, 0, 0)),
2921                    (
2922                        (1712421000, 0),
2923                        o(10),
2924                        "AEST",
2925                        (2024, 4, 7, 2, 30, 0, 0),
2926                    ),
2927                ],
2928            ),
2929            // Pacific/Honolulu is small eough that we just test every
2930            // possible instant before, at and after each transition.
2931            (
2932                "Pacific/Honolulu",
2933                &[
2934                    (
2935                        (-2334101315, 0),
2936                        -Offset::hms(10, 31, 26),
2937                        "LMT",
2938                        (1896, 1, 13, 11, 59, 59, 0),
2939                    ),
2940                    (
2941                        (-2334101314, 0),
2942                        -Offset::hms(10, 30, 0),
2943                        "HST",
2944                        (1896, 1, 13, 12, 1, 26, 0),
2945                    ),
2946                    (
2947                        (-2334101313, 0),
2948                        -Offset::hms(10, 30, 0),
2949                        "HST",
2950                        (1896, 1, 13, 12, 1, 27, 0),
2951                    ),
2952                    (
2953                        (-1157283001, 0),
2954                        -Offset::hms(10, 30, 0),
2955                        "HST",
2956                        (1933, 4, 30, 1, 59, 59, 0),
2957                    ),
2958                    (
2959                        (-1157283000, 0),
2960                        -Offset::hms(9, 30, 0),
2961                        "HDT",
2962                        (1933, 4, 30, 3, 0, 0, 0),
2963                    ),
2964                    (
2965                        (-1157282999, 0),
2966                        -Offset::hms(9, 30, 0),
2967                        "HDT",
2968                        (1933, 4, 30, 3, 0, 1, 0),
2969                    ),
2970                    (
2971                        (-1155436201, 0),
2972                        -Offset::hms(9, 30, 0),
2973                        "HDT",
2974                        (1933, 5, 21, 11, 59, 59, 0),
2975                    ),
2976                    (
2977                        (-1155436200, 0),
2978                        -Offset::hms(10, 30, 0),
2979                        "HST",
2980                        (1933, 5, 21, 11, 0, 0, 0),
2981                    ),
2982                    (
2983                        (-1155436199, 0),
2984                        -Offset::hms(10, 30, 0),
2985                        "HST",
2986                        (1933, 5, 21, 11, 0, 1, 0),
2987                    ),
2988                    (
2989                        (-880198201, 0),
2990                        -Offset::hms(10, 30, 0),
2991                        "HST",
2992                        (1942, 2, 9, 1, 59, 59, 0),
2993                    ),
2994                    (
2995                        (-880198200, 0),
2996                        -Offset::hms(9, 30, 0),
2997                        "HWT",
2998                        (1942, 2, 9, 3, 0, 0, 0),
2999                    ),
3000                    (
3001                        (-880198199, 0),
3002                        -Offset::hms(9, 30, 0),
3003                        "HWT",
3004                        (1942, 2, 9, 3, 0, 1, 0),
3005                    ),
3006                    (
3007                        (-769395601, 0),
3008                        -Offset::hms(9, 30, 0),
3009                        "HWT",
3010                        (1945, 8, 14, 13, 29, 59, 0),
3011                    ),
3012                    (
3013                        (-769395600, 0),
3014                        -Offset::hms(9, 30, 0),
3015                        "HPT",
3016                        (1945, 8, 14, 13, 30, 0, 0),
3017                    ),
3018                    (
3019                        (-769395599, 0),
3020                        -Offset::hms(9, 30, 0),
3021                        "HPT",
3022                        (1945, 8, 14, 13, 30, 1, 0),
3023                    ),
3024                    (
3025                        (-765376201, 0),
3026                        -Offset::hms(9, 30, 0),
3027                        "HPT",
3028                        (1945, 9, 30, 1, 59, 59, 0),
3029                    ),
3030                    (
3031                        (-765376200, 0),
3032                        -Offset::hms(10, 30, 0),
3033                        "HST",
3034                        (1945, 9, 30, 1, 0, 0, 0),
3035                    ),
3036                    (
3037                        (-765376199, 0),
3038                        -Offset::hms(10, 30, 0),
3039                        "HST",
3040                        (1945, 9, 30, 1, 0, 1, 0),
3041                    ),
3042                    (
3043                        (-712150201, 0),
3044                        -Offset::hms(10, 30, 0),
3045                        "HST",
3046                        (1947, 6, 8, 1, 59, 59, 0),
3047                    ),
3048                    // At this point, we hit the last transition and the POSIX
3049                    // TZ string takes over.
3050                    (
3051                        (-712150200, 0),
3052                        -Offset::hms(10, 0, 0),
3053                        "HST",
3054                        (1947, 6, 8, 2, 30, 0, 0),
3055                    ),
3056                    (
3057                        (-712150199, 0),
3058                        -Offset::hms(10, 0, 0),
3059                        "HST",
3060                        (1947, 6, 8, 2, 30, 1, 0),
3061                    ),
3062                ],
3063            ),
3064            // This time zone has an interesting transition where it jumps
3065            // backwards a full day at 1867-10-19T15:30:00.
3066            (
3067                "America/Sitka",
3068                &[
3069                    ((0, 0), o(-8), "PST", (1969, 12, 31, 16, 0, 0, 0)),
3070                    (
3071                        (-377705023201, 0),
3072                        Offset::hms(14, 58, 47),
3073                        "LMT",
3074                        (-9999, 1, 2, 16, 58, 46, 0),
3075                    ),
3076                    (
3077                        (-3225223728, 0),
3078                        Offset::hms(14, 58, 47),
3079                        "LMT",
3080                        (1867, 10, 19, 15, 29, 59, 0),
3081                    ),
3082                    // Notice the 24 hour time jump backwards a whole day!
3083                    (
3084                        (-3225223727, 0),
3085                        -Offset::hms(9, 1, 13),
3086                        "LMT",
3087                        (1867, 10, 18, 15, 30, 0, 0),
3088                    ),
3089                    (
3090                        (-3225223726, 0),
3091                        -Offset::hms(9, 1, 13),
3092                        "LMT",
3093                        (1867, 10, 18, 15, 30, 1, 0),
3094                    ),
3095                ],
3096            ),
3097        ];
3098        for &(tzname, timestamps_to_datetimes) in tests {
3099            let test_file = TzifTestFile::get(tzname);
3100            let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
3101            for &((unix_sec, unix_nano), offset, abbrev, datetime) in
3102                timestamps_to_datetimes
3103            {
3104                let (year, month, day, hour, min, sec, nano) = datetime;
3105                let timestamp = Timestamp::new(unix_sec, unix_nano).unwrap();
3106                let info = tz.to_offset_info(timestamp);
3107                assert_eq!(
3108                    info.offset(),
3109                    offset,
3110                    "\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
3111                );
3112                assert_eq!(
3113                    info.abbreviation(),
3114                    abbrev,
3115                    "\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
3116                );
3117                assert_eq!(
3118                    info.offset().to_datetime(timestamp),
3119                    date(year, month, day).at(hour, min, sec, nano),
3120                    "\nTZ={tzname}, timestamp({unix_sec}, {unix_nano})",
3121                );
3122            }
3123        }
3124    }
3125
3126    #[cfg(feature = "alloc")]
3127    #[test]
3128    fn time_zone_posix_to_ambiguous_timestamp() {
3129        let tests: &[(&str, &[_])] = &[
3130            // America/New_York, but a utopia in which DST is abolished.
3131            (
3132                "EST5",
3133                &[
3134                    ((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
3135                    ((2024, 3, 10, 2, 0, 0, 0), unambiguous(-5)),
3136                ],
3137            ),
3138            // The standard DST rule for America/New_York.
3139            (
3140                "EST5EDT,M3.2.0,M11.1.0",
3141                &[
3142                    ((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
3143                    ((2024, 3, 10, 1, 59, 59, 999_999_999), unambiguous(-5)),
3144                    ((2024, 3, 10, 2, 0, 0, 0), gap(-5, -4)),
3145                    ((2024, 3, 10, 2, 59, 59, 999_999_999), gap(-5, -4)),
3146                    ((2024, 3, 10, 3, 0, 0, 0), unambiguous(-4)),
3147                    ((2024, 11, 3, 0, 59, 59, 999_999_999), unambiguous(-4)),
3148                    ((2024, 11, 3, 1, 0, 0, 0), fold(-4, -5)),
3149                    ((2024, 11, 3, 1, 59, 59, 999_999_999), fold(-4, -5)),
3150                    ((2024, 11, 3, 2, 0, 0, 0), unambiguous(-5)),
3151                ],
3152            ),
3153            // A bit of a nonsensical America/New_York that has DST, but whose
3154            // offset is equivalent to standard time. Having the same offset
3155            // means there's never any ambiguity.
3156            (
3157                "EST5EDT5,M3.2.0,M11.1.0",
3158                &[
3159                    ((1969, 12, 31, 19, 0, 0, 0), unambiguous(-5)),
3160                    ((2024, 3, 10, 1, 59, 59, 999_999_999), unambiguous(-5)),
3161                    ((2024, 3, 10, 2, 0, 0, 0), unambiguous(-5)),
3162                    ((2024, 3, 10, 2, 59, 59, 999_999_999), unambiguous(-5)),
3163                    ((2024, 3, 10, 3, 0, 0, 0), unambiguous(-5)),
3164                    ((2024, 11, 3, 0, 59, 59, 999_999_999), unambiguous(-5)),
3165                    ((2024, 11, 3, 1, 0, 0, 0), unambiguous(-5)),
3166                    ((2024, 11, 3, 1, 59, 59, 999_999_999), unambiguous(-5)),
3167                    ((2024, 11, 3, 2, 0, 0, 0), unambiguous(-5)),
3168                ],
3169            ),
3170            // This is Europe/Dublin's rule. It's interesting because its
3171            // DST is an offset behind standard time. (DST is usually one hour
3172            // ahead of standard time.)
3173            (
3174                "IST-1GMT0,M10.5.0,M3.5.0/1",
3175                &[
3176                    ((1970, 1, 1, 0, 0, 0, 0), unambiguous(0)),
3177                    ((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
3178                    ((2024, 3, 31, 1, 0, 0, 0), gap(0, 1)),
3179                    ((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 1)),
3180                    ((2024, 3, 31, 2, 0, 0, 0), unambiguous(1)),
3181                    ((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(1)),
3182                    ((2024, 10, 27, 1, 0, 0, 0), fold(1, 0)),
3183                    ((2024, 10, 27, 1, 59, 59, 999_999_999), fold(1, 0)),
3184                    ((2024, 10, 27, 2, 0, 0, 0), unambiguous(0)),
3185                ],
3186            ),
3187            // This is Australia/Tasmania's rule. We chose this because it's
3188            // in the southern hemisphere where DST still skips ahead one hour,
3189            // but it usually starts in the fall and ends in the spring.
3190            (
3191                "AEST-10AEDT,M10.1.0,M4.1.0/3",
3192                &[
3193                    ((1970, 1, 1, 11, 0, 0, 0), unambiguous(11)),
3194                    ((2024, 4, 7, 1, 59, 59, 999_999_999), unambiguous(11)),
3195                    ((2024, 4, 7, 2, 0, 0, 0), fold(11, 10)),
3196                    ((2024, 4, 7, 2, 59, 59, 999_999_999), fold(11, 10)),
3197                    ((2024, 4, 7, 3, 0, 0, 0), unambiguous(10)),
3198                    ((2024, 10, 6, 1, 59, 59, 999_999_999), unambiguous(10)),
3199                    ((2024, 10, 6, 2, 0, 0, 0), gap(10, 11)),
3200                    ((2024, 10, 6, 2, 59, 59, 999_999_999), gap(10, 11)),
3201                    ((2024, 10, 6, 3, 0, 0, 0), unambiguous(11)),
3202                ],
3203            ),
3204            // This is Antarctica/Troll's rule. We chose this one because its
3205            // DST transition is 2 hours instead of the standard 1 hour. This
3206            // means gaps and folds are twice as long as they usually are. And
3207            // it means there are 22 hour and 26 hour days, respectively. Wow!
3208            (
3209                "<+00>0<+02>-2,M3.5.0/1,M10.5.0/3",
3210                &[
3211                    ((1970, 1, 1, 0, 0, 0, 0), unambiguous(0)),
3212                    // test the gap
3213                    ((2024, 3, 31, 0, 59, 59, 999_999_999), unambiguous(0)),
3214                    ((2024, 3, 31, 1, 0, 0, 0), gap(0, 2)),
3215                    ((2024, 3, 31, 1, 59, 59, 999_999_999), gap(0, 2)),
3216                    // still in the gap!
3217                    ((2024, 3, 31, 2, 0, 0, 0), gap(0, 2)),
3218                    ((2024, 3, 31, 2, 59, 59, 999_999_999), gap(0, 2)),
3219                    // finally out
3220                    ((2024, 3, 31, 3, 0, 0, 0), unambiguous(2)),
3221                    // test the fold
3222                    ((2024, 10, 27, 0, 59, 59, 999_999_999), unambiguous(2)),
3223                    ((2024, 10, 27, 1, 0, 0, 0), fold(2, 0)),
3224                    ((2024, 10, 27, 1, 59, 59, 999_999_999), fold(2, 0)),
3225                    // still in the fold!
3226                    ((2024, 10, 27, 2, 0, 0, 0), fold(2, 0)),
3227                    ((2024, 10, 27, 2, 59, 59, 999_999_999), fold(2, 0)),
3228                    // finally out
3229                    ((2024, 10, 27, 3, 0, 0, 0), unambiguous(0)),
3230                ],
3231            ),
3232            // This is America/St_Johns' rule, which has an offset with
3233            // non-zero minutes *and* a DST transition rule. (Indian Standard
3234            // Time is the one I'm more familiar with, but it turns out IST
3235            // does not have DST!)
3236            (
3237                "NST3:30NDT,M3.2.0,M11.1.0",
3238                &[
3239                    (
3240                        (1969, 12, 31, 20, 30, 0, 0),
3241                        o_unambiguous(-Offset::hms(3, 30, 0)),
3242                    ),
3243                    (
3244                        (2024, 3, 10, 1, 59, 59, 999_999_999),
3245                        o_unambiguous(-Offset::hms(3, 30, 0)),
3246                    ),
3247                    (
3248                        (2024, 3, 10, 2, 0, 0, 0),
3249                        o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
3250                    ),
3251                    (
3252                        (2024, 3, 10, 2, 59, 59, 999_999_999),
3253                        o_gap(-Offset::hms(3, 30, 0), -Offset::hms(2, 30, 0)),
3254                    ),
3255                    (
3256                        (2024, 3, 10, 3, 0, 0, 0),
3257                        o_unambiguous(-Offset::hms(2, 30, 0)),
3258                    ),
3259                    (
3260                        (2024, 11, 3, 0, 59, 59, 999_999_999),
3261                        o_unambiguous(-Offset::hms(2, 30, 0)),
3262                    ),
3263                    (
3264                        (2024, 11, 3, 1, 0, 0, 0),
3265                        o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
3266                    ),
3267                    (
3268                        (2024, 11, 3, 1, 59, 59, 999_999_999),
3269                        o_fold(-Offset::hms(2, 30, 0), -Offset::hms(3, 30, 0)),
3270                    ),
3271                    (
3272                        (2024, 11, 3, 2, 0, 0, 0),
3273                        o_unambiguous(-Offset::hms(3, 30, 0)),
3274                    ),
3275                ],
3276            ),
3277        ];
3278        for &(posix_tz, datetimes_to_ambiguous) in tests {
3279            let tz = TimeZone::posix(posix_tz).unwrap();
3280            for &(datetime, ambiguous_kind) in datetimes_to_ambiguous {
3281                let (year, month, day, hour, min, sec, nano) = datetime;
3282                let dt = date(year, month, day).at(hour, min, sec, nano);
3283                let got = tz.to_ambiguous_zoned(dt);
3284                assert_eq!(
3285                    got.offset(),
3286                    ambiguous_kind,
3287                    "\nTZ: {posix_tz}\ndatetime: \
3288                     {year:04}-{month:02}-{day:02}T\
3289                     {hour:02}:{min:02}:{sec:02}.{nano:09}",
3290                );
3291            }
3292        }
3293    }
3294
3295    #[cfg(feature = "alloc")]
3296    #[test]
3297    fn time_zone_posix_to_datetime() {
3298        let o = |hours| offset(hours);
3299        let tests: &[(&str, &[_])] = &[
3300            ("EST5", &[((0, 0), o(-5), (1969, 12, 31, 19, 0, 0, 0))]),
3301            (
3302                // From America/New_York
3303                "EST5EDT,M3.2.0,M11.1.0",
3304                &[
3305                    ((0, 0), o(-5), (1969, 12, 31, 19, 0, 0, 0)),
3306                    ((1710052200, 0), o(-5), (2024, 3, 10, 1, 30, 0, 0)),
3307                    (
3308                        (1710053999, 999_999_999),
3309                        o(-5),
3310                        (2024, 3, 10, 1, 59, 59, 999_999_999),
3311                    ),
3312                    ((1710054000, 0), o(-4), (2024, 3, 10, 3, 0, 0, 0)),
3313                    ((1710055800, 0), o(-4), (2024, 3, 10, 3, 30, 0, 0)),
3314                    ((1730610000, 0), o(-4), (2024, 11, 3, 1, 0, 0, 0)),
3315                    ((1730611800, 0), o(-4), (2024, 11, 3, 1, 30, 0, 0)),
3316                    (
3317                        (1730613599, 999_999_999),
3318                        o(-4),
3319                        (2024, 11, 3, 1, 59, 59, 999_999_999),
3320                    ),
3321                    ((1730613600, 0), o(-5), (2024, 11, 3, 1, 0, 0, 0)),
3322                    ((1730615400, 0), o(-5), (2024, 11, 3, 1, 30, 0, 0)),
3323                ],
3324            ),
3325            (
3326                // From Australia/Tasmania
3327                //
3328                // We chose this because it's a time zone in the southern
3329                // hemisphere with DST. Unlike the northern hemisphere, its DST
3330                // starts in the fall and ends in the spring. In the northern
3331                // hemisphere, we typically start DST in the spring and end it
3332                // in the fall.
3333                "AEST-10AEDT,M10.1.0,M4.1.0/3",
3334                &[
3335                    ((0, 0), o(11), (1970, 1, 1, 11, 0, 0, 0)),
3336                    ((1728142200, 0), o(10), (2024, 10, 6, 1, 30, 0, 0)),
3337                    (
3338                        (1728143999, 999_999_999),
3339                        o(10),
3340                        (2024, 10, 6, 1, 59, 59, 999_999_999),
3341                    ),
3342                    ((1728144000, 0), o(11), (2024, 10, 6, 3, 0, 0, 0)),
3343                    ((1728145800, 0), o(11), (2024, 10, 6, 3, 30, 0, 0)),
3344                    ((1712415600, 0), o(11), (2024, 4, 7, 2, 0, 0, 0)),
3345                    ((1712417400, 0), o(11), (2024, 4, 7, 2, 30, 0, 0)),
3346                    (
3347                        (1712419199, 999_999_999),
3348                        o(11),
3349                        (2024, 4, 7, 2, 59, 59, 999_999_999),
3350                    ),
3351                    ((1712419200, 0), o(10), (2024, 4, 7, 2, 0, 0, 0)),
3352                    ((1712421000, 0), o(10), (2024, 4, 7, 2, 30, 0, 0)),
3353                ],
3354            ),
3355            (
3356                // Uses the maximum possible offset. A sloppy read of POSIX
3357                // seems to indicate the maximum offset is 24:59:59, but since
3358                // DST defaults to 1 hour ahead of standard time, it's possible
3359                // to use 24:59:59 for standard time, omit the DST offset, and
3360                // thus get a DST offset of 25:59:59.
3361                "XXX-24:59:59YYY,M3.2.0,M11.1.0",
3362                &[
3363                    // 2024-01-05T00:00:00+00
3364                    (
3365                        (1704412800, 0),
3366                        Offset::hms(24, 59, 59),
3367                        (2024, 1, 6, 0, 59, 59, 0),
3368                    ),
3369                    // 2024-06-05T00:00:00+00 (DST)
3370                    (
3371                        (1717545600, 0),
3372                        Offset::hms(25, 59, 59),
3373                        (2024, 6, 6, 1, 59, 59, 0),
3374                    ),
3375                ],
3376            ),
3377        ];
3378        for &(posix_tz, timestamps_to_datetimes) in tests {
3379            let tz = TimeZone::posix(posix_tz).unwrap();
3380            for &((unix_sec, unix_nano), offset, datetime) in
3381                timestamps_to_datetimes
3382            {
3383                let (year, month, day, hour, min, sec, nano) = datetime;
3384                let timestamp = Timestamp::new(unix_sec, unix_nano).unwrap();
3385                assert_eq!(
3386                    tz.to_offset(timestamp),
3387                    offset,
3388                    "\ntimestamp({unix_sec}, {unix_nano})",
3389                );
3390                assert_eq!(
3391                    tz.to_datetime(timestamp),
3392                    date(year, month, day).at(hour, min, sec, nano),
3393                    "\ntimestamp({unix_sec}, {unix_nano})",
3394                );
3395            }
3396        }
3397    }
3398
3399    #[test]
3400    fn time_zone_fixed_to_datetime() {
3401        let tz = offset(-5).to_time_zone();
3402        let unix_epoch = Timestamp::new(0, 0).unwrap();
3403        assert_eq!(
3404            tz.to_datetime(unix_epoch),
3405            date(1969, 12, 31).at(19, 0, 0, 0),
3406        );
3407
3408        let tz = Offset::from_seconds(93_599).unwrap().to_time_zone();
3409        let timestamp = Timestamp::new(253402207200, 999_999_999).unwrap();
3410        assert_eq!(
3411            tz.to_datetime(timestamp),
3412            date(9999, 12, 31).at(23, 59, 59, 999_999_999),
3413        );
3414
3415        let tz = Offset::from_seconds(-93_599).unwrap().to_time_zone();
3416        let timestamp = Timestamp::new(-377705023201, 0).unwrap();
3417        assert_eq!(
3418            tz.to_datetime(timestamp),
3419            date(-9999, 1, 1).at(0, 0, 0, 0),
3420        );
3421    }
3422
3423    #[test]
3424    fn time_zone_fixed_to_timestamp() {
3425        let tz = offset(-5).to_time_zone();
3426        let dt = date(1969, 12, 31).at(19, 0, 0, 0);
3427        assert_eq!(
3428            tz.to_zoned(dt).unwrap().timestamp(),
3429            Timestamp::new(0, 0).unwrap()
3430        );
3431
3432        let tz = Offset::from_seconds(93_599).unwrap().to_time_zone();
3433        let dt = date(9999, 12, 31).at(23, 59, 59, 999_999_999);
3434        assert_eq!(
3435            tz.to_zoned(dt).unwrap().timestamp(),
3436            Timestamp::new(253402207200, 999_999_999).unwrap(),
3437        );
3438        let tz = Offset::from_seconds(93_598).unwrap().to_time_zone();
3439        assert!(tz.to_zoned(dt).is_err());
3440
3441        let tz = Offset::from_seconds(-93_599).unwrap().to_time_zone();
3442        let dt = date(-9999, 1, 1).at(0, 0, 0, 0);
3443        assert_eq!(
3444            tz.to_zoned(dt).unwrap().timestamp(),
3445            Timestamp::new(-377705023201, 0).unwrap(),
3446        );
3447        let tz = Offset::from_seconds(-93_598).unwrap().to_time_zone();
3448        assert!(tz.to_zoned(dt).is_err());
3449    }
3450
3451    #[cfg(feature = "alloc")]
3452    #[test]
3453    fn time_zone_tzif_previous_transition() {
3454        let tests: &[(&str, &[(&str, Option<&str>)])] = &[
3455            (
3456                "UTC",
3457                &[
3458                    ("1969-12-31T19Z", None),
3459                    ("2024-03-10T02Z", None),
3460                    ("-009999-12-01 00Z", None),
3461                    ("9999-12-01 00Z", None),
3462                ],
3463            ),
3464            (
3465                "America/New_York",
3466                &[
3467                    ("2024-03-10 08Z", Some("2024-03-10 07Z")),
3468                    ("2024-03-10 07:00:00.000000001Z", Some("2024-03-10 07Z")),
3469                    ("2024-03-10 07Z", Some("2023-11-05 06Z")),
3470                    ("2023-11-05 06Z", Some("2023-03-12 07Z")),
3471                    ("-009999-01-31 00Z", None),
3472                    ("9999-12-01 00Z", Some("9999-11-07 06Z")),
3473                    // While at present we have "fat" TZif files for our
3474                    // testdata, it's conceivable they could be swapped to
3475                    // "slim." In which case, the tests above will mostly just
3476                    // be testing POSIX TZ strings and not the TZif logic. So
3477                    // below, we include times that will be in slim (i.e.,
3478                    // historical times the precede the current DST rule).
3479                    ("1969-12-31 19Z", Some("1969-10-26 06Z")),
3480                    ("2000-04-02 08Z", Some("2000-04-02 07Z")),
3481                    ("2000-04-02 07:00:00.000000001Z", Some("2000-04-02 07Z")),
3482                    ("2000-04-02 07Z", Some("1999-10-31 06Z")),
3483                    ("1999-10-31 06Z", Some("1999-04-04 07Z")),
3484                ],
3485            ),
3486            (
3487                "Australia/Tasmania",
3488                &[
3489                    ("2010-04-03 17Z", Some("2010-04-03 16Z")),
3490                    ("2010-04-03 16:00:00.000000001Z", Some("2010-04-03 16Z")),
3491                    ("2010-04-03 16Z", Some("2009-10-03 16Z")),
3492                    ("2009-10-03 16Z", Some("2009-04-04 16Z")),
3493                    ("-009999-01-31 00Z", None),
3494                    ("9999-12-01 00Z", Some("9999-10-02 16Z")),
3495                    // Tests for historical data from tzdb. No POSIX TZ.
3496                    ("2000-03-25 17Z", Some("2000-03-25 16Z")),
3497                    ("2000-03-25 16:00:00.000000001Z", Some("2000-03-25 16Z")),
3498                    ("2000-03-25 16Z", Some("1999-10-02 16Z")),
3499                    ("1999-10-02 16Z", Some("1999-03-27 16Z")),
3500                ],
3501            ),
3502            // This is Europe/Dublin's rule. It's interesting because its
3503            // DST is an offset behind standard time. (DST is usually one hour
3504            // ahead of standard time.)
3505            (
3506                "Europe/Dublin",
3507                &[
3508                    ("2010-03-28 02Z", Some("2010-03-28 01Z")),
3509                    ("2010-03-28 01:00:00.000000001Z", Some("2010-03-28 01Z")),
3510                    ("2010-03-28 01Z", Some("2009-10-25 01Z")),
3511                    ("2009-10-25 01Z", Some("2009-03-29 01Z")),
3512                    ("-009999-01-31 00Z", None),
3513                    ("9999-12-01 00Z", Some("9999-10-31 01Z")),
3514                    // Tests for historical data from tzdb. No POSIX TZ.
3515                    ("1990-03-25 02Z", Some("1990-03-25 01Z")),
3516                    ("1990-03-25 01:00:00.000000001Z", Some("1990-03-25 01Z")),
3517                    ("1990-03-25 01Z", Some("1989-10-29 01Z")),
3518                    ("1989-10-25 01Z", Some("1989-03-26 01Z")),
3519                ],
3520            ),
3521            (
3522                // Sao Paulo eliminated DST in 2019, so the previous transition
3523                // from 2024 is several years back.
3524                "America/Sao_Paulo",
3525                &[("2024-03-10 08Z", Some("2019-02-17 02Z"))],
3526            ),
3527        ];
3528        for &(tzname, prev_trans) in tests {
3529            if tzname != "America/Sao_Paulo" {
3530                continue;
3531            }
3532            let test_file = TzifTestFile::get(tzname);
3533            let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
3534            for (given, expected) in prev_trans {
3535                let given: Timestamp = given.parse().unwrap();
3536                let expected =
3537                    expected.map(|s| s.parse::<Timestamp>().unwrap());
3538                let got = tz.previous_transition(given).map(|t| t.timestamp());
3539                assert_eq!(got, expected, "\nTZ: {tzname}\ngiven: {given}");
3540            }
3541        }
3542    }
3543
3544    #[cfg(feature = "alloc")]
3545    #[test]
3546    fn time_zone_tzif_next_transition() {
3547        let tests: &[(&str, &[(&str, Option<&str>)])] = &[
3548            (
3549                "UTC",
3550                &[
3551                    ("1969-12-31T19Z", None),
3552                    ("2024-03-10T02Z", None),
3553                    ("-009999-12-01 00Z", None),
3554                    ("9999-12-01 00Z", None),
3555                ],
3556            ),
3557            (
3558                "America/New_York",
3559                &[
3560                    ("2024-03-10 06Z", Some("2024-03-10 07Z")),
3561                    ("2024-03-10 06:59:59.999999999Z", Some("2024-03-10 07Z")),
3562                    ("2024-03-10 07Z", Some("2024-11-03 06Z")),
3563                    ("2024-11-03 06Z", Some("2025-03-09 07Z")),
3564                    ("-009999-12-01 00Z", Some("1883-11-18 17Z")),
3565                    ("9999-12-01 00Z", None),
3566                    // While at present we have "fat" TZif files for our
3567                    // testdata, it's conceivable they could be swapped to
3568                    // "slim." In which case, the tests above will mostly just
3569                    // be testing POSIX TZ strings and not the TZif logic. So
3570                    // below, we include times that will be in slim (i.e.,
3571                    // historical times the precede the current DST rule).
3572                    ("1969-12-31 19Z", Some("1970-04-26 07Z")),
3573                    ("2000-04-02 06Z", Some("2000-04-02 07Z")),
3574                    ("2000-04-02 06:59:59.999999999Z", Some("2000-04-02 07Z")),
3575                    ("2000-04-02 07Z", Some("2000-10-29 06Z")),
3576                    ("2000-10-29 06Z", Some("2001-04-01 07Z")),
3577                ],
3578            ),
3579            (
3580                "Australia/Tasmania",
3581                &[
3582                    ("2010-04-03 15Z", Some("2010-04-03 16Z")),
3583                    ("2010-04-03 15:59:59.999999999Z", Some("2010-04-03 16Z")),
3584                    ("2010-04-03 16Z", Some("2010-10-02 16Z")),
3585                    ("2010-10-02 16Z", Some("2011-04-02 16Z")),
3586                    ("-009999-12-01 00Z", Some("1895-08-31 14:10:44Z")),
3587                    ("9999-12-01 00Z", None),
3588                    // Tests for historical data from tzdb. No POSIX TZ.
3589                    ("2000-03-25 15Z", Some("2000-03-25 16Z")),
3590                    ("2000-03-25 15:59:59.999999999Z", Some("2000-03-25 16Z")),
3591                    ("2000-03-25 16Z", Some("2000-08-26 16Z")),
3592                    ("2000-08-26 16Z", Some("2001-03-24 16Z")),
3593                ],
3594            ),
3595            (
3596                "Europe/Dublin",
3597                &[
3598                    ("2010-03-28 00Z", Some("2010-03-28 01Z")),
3599                    ("2010-03-28 00:59:59.999999999Z", Some("2010-03-28 01Z")),
3600                    ("2010-03-28 01Z", Some("2010-10-31 01Z")),
3601                    ("2010-10-31 01Z", Some("2011-03-27 01Z")),
3602                    ("-009999-12-01 00Z", Some("1880-08-02 00:25:21Z")),
3603                    ("9999-12-01 00Z", None),
3604                    // Tests for historical data from tzdb. No POSIX TZ.
3605                    ("1990-03-25 00Z", Some("1990-03-25 01Z")),
3606                    ("1990-03-25 00:59:59.999999999Z", Some("1990-03-25 01Z")),
3607                    ("1990-03-25 01Z", Some("1990-10-28 01Z")),
3608                    ("1990-10-28 01Z", Some("1991-03-31 01Z")),
3609                ],
3610            ),
3611            (
3612                // Sao Paulo eliminated DST in 2019, so the next transition
3613                // from 2024 no longer exists.
3614                "America/Sao_Paulo",
3615                &[("2024-03-10 08Z", None)],
3616            ),
3617        ];
3618        for &(tzname, next_trans) in tests {
3619            let test_file = TzifTestFile::get(tzname);
3620            let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
3621            for (given, expected) in next_trans {
3622                let given: Timestamp = given.parse().unwrap();
3623                let expected =
3624                    expected.map(|s| s.parse::<Timestamp>().unwrap());
3625                let got = tz.next_transition(given).map(|t| t.timestamp());
3626                assert_eq!(got, expected, "\nTZ: {tzname}\ngiven: {given}");
3627            }
3628        }
3629    }
3630
3631    #[cfg(feature = "alloc")]
3632    #[test]
3633    fn time_zone_posix_previous_transition() {
3634        let tests: &[(&str, &[(&str, Option<&str>)])] = &[
3635            // America/New_York, but a utopia in which DST is abolished. There
3636            // are no time zone transitions, so next_transition always returns
3637            // None.
3638            (
3639                "EST5",
3640                &[
3641                    ("1969-12-31T19Z", None),
3642                    ("2024-03-10T02Z", None),
3643                    ("-009999-12-01 00Z", None),
3644                    ("9999-12-01 00Z", None),
3645                ],
3646            ),
3647            // The standard DST rule for America/New_York.
3648            (
3649                "EST5EDT,M3.2.0,M11.1.0",
3650                &[
3651                    ("1969-12-31 19Z", Some("1969-11-02 06Z")),
3652                    ("2024-03-10 08Z", Some("2024-03-10 07Z")),
3653                    ("2024-03-10 07:00:00.000000001Z", Some("2024-03-10 07Z")),
3654                    ("2024-03-10 07Z", Some("2023-11-05 06Z")),
3655                    ("2023-11-05 06Z", Some("2023-03-12 07Z")),
3656                    ("-009999-01-31 00Z", None),
3657                    ("9999-12-01 00Z", Some("9999-11-07 06Z")),
3658                ],
3659            ),
3660            (
3661                // From Australia/Tasmania
3662                "AEST-10AEDT,M10.1.0,M4.1.0/3",
3663                &[
3664                    ("2010-04-03 17Z", Some("2010-04-03 16Z")),
3665                    ("2010-04-03 16:00:00.000000001Z", Some("2010-04-03 16Z")),
3666                    ("2010-04-03 16Z", Some("2009-10-03 16Z")),
3667                    ("2009-10-03 16Z", Some("2009-04-04 16Z")),
3668                    ("-009999-01-31 00Z", None),
3669                    ("9999-12-01 00Z", Some("9999-10-02 16Z")),
3670                ],
3671            ),
3672            // This is Europe/Dublin's rule. It's interesting because its
3673            // DST is an offset behind standard time. (DST is usually one hour
3674            // ahead of standard time.)
3675            (
3676                "IST-1GMT0,M10.5.0,M3.5.0/1",
3677                &[
3678                    ("2010-03-28 02Z", Some("2010-03-28 01Z")),
3679                    ("2010-03-28 01:00:00.000000001Z", Some("2010-03-28 01Z")),
3680                    ("2010-03-28 01Z", Some("2009-10-25 01Z")),
3681                    ("2009-10-25 01Z", Some("2009-03-29 01Z")),
3682                    ("-009999-01-31 00Z", None),
3683                    ("9999-12-01 00Z", Some("9999-10-31 01Z")),
3684                ],
3685            ),
3686        ];
3687        for &(posix_tz, prev_trans) in tests {
3688            let tz = TimeZone::posix(posix_tz).unwrap();
3689            for (given, expected) in prev_trans {
3690                let given: Timestamp = given.parse().unwrap();
3691                let expected =
3692                    expected.map(|s| s.parse::<Timestamp>().unwrap());
3693                let got = tz.previous_transition(given).map(|t| t.timestamp());
3694                assert_eq!(got, expected, "\nTZ: {posix_tz}\ngiven: {given}");
3695            }
3696        }
3697    }
3698
3699    #[cfg(feature = "alloc")]
3700    #[test]
3701    fn time_zone_posix_next_transition() {
3702        let tests: &[(&str, &[(&str, Option<&str>)])] = &[
3703            // America/New_York, but a utopia in which DST is abolished. There
3704            // are no time zone transitions, so next_transition always returns
3705            // None.
3706            (
3707                "EST5",
3708                &[
3709                    ("1969-12-31T19Z", None),
3710                    ("2024-03-10T02Z", None),
3711                    ("-009999-12-01 00Z", None),
3712                    ("9999-12-01 00Z", None),
3713                ],
3714            ),
3715            // The standard DST rule for America/New_York.
3716            (
3717                "EST5EDT,M3.2.0,M11.1.0",
3718                &[
3719                    ("1969-12-31 19Z", Some("1970-03-08 07Z")),
3720                    ("2024-03-10 06Z", Some("2024-03-10 07Z")),
3721                    ("2024-03-10 06:59:59.999999999Z", Some("2024-03-10 07Z")),
3722                    ("2024-03-10 07Z", Some("2024-11-03 06Z")),
3723                    ("2024-11-03 06Z", Some("2025-03-09 07Z")),
3724                    ("-009999-12-01 00Z", Some("-009998-03-10 07Z")),
3725                    ("9999-12-01 00Z", None),
3726                ],
3727            ),
3728            (
3729                // From Australia/Tasmania
3730                "AEST-10AEDT,M10.1.0,M4.1.0/3",
3731                &[
3732                    ("2010-04-03 15Z", Some("2010-04-03 16Z")),
3733                    ("2010-04-03 15:59:59.999999999Z", Some("2010-04-03 16Z")),
3734                    ("2010-04-03 16Z", Some("2010-10-02 16Z")),
3735                    ("2010-10-02 16Z", Some("2011-04-02 16Z")),
3736                    ("-009999-12-01 00Z", Some("-009998-04-06 16Z")),
3737                    ("9999-12-01 00Z", None),
3738                ],
3739            ),
3740            // This is Europe/Dublin's rule. It's interesting because its
3741            // DST is an offset behind standard time. (DST is usually one hour
3742            // ahead of standard time.)
3743            (
3744                "IST-1GMT0,M10.5.0,M3.5.0/1",
3745                &[
3746                    ("2010-03-28 00Z", Some("2010-03-28 01Z")),
3747                    ("2010-03-28 00:59:59.999999999Z", Some("2010-03-28 01Z")),
3748                    ("2010-03-28 01Z", Some("2010-10-31 01Z")),
3749                    ("2010-10-31 01Z", Some("2011-03-27 01Z")),
3750                    ("-009999-12-01 00Z", Some("-009998-03-31 01Z")),
3751                    ("9999-12-01 00Z", None),
3752                ],
3753            ),
3754        ];
3755        for &(posix_tz, next_trans) in tests {
3756            let tz = TimeZone::posix(posix_tz).unwrap();
3757            for (given, expected) in next_trans {
3758                let given: Timestamp = given.parse().unwrap();
3759                let expected =
3760                    expected.map(|s| s.parse::<Timestamp>().unwrap());
3761                let got = tz.next_transition(given).map(|t| t.timestamp());
3762                assert_eq!(got, expected, "\nTZ: {posix_tz}\ngiven: {given}");
3763            }
3764        }
3765    }
3766
3767    /// This tests that the size of a time zone is kept at a single word.
3768    ///
3769    /// This is important because every jiff::Zoned has a TimeZone inside of
3770    /// it, and we want to keep its size as small as we can.
3771    #[test]
3772    fn time_zone_size() {
3773        #[cfg(feature = "alloc")]
3774        {
3775            let word = core::mem::size_of::<usize>();
3776            assert_eq!(word, core::mem::size_of::<TimeZone>());
3777        }
3778        #[cfg(all(target_pointer_width = "64", not(feature = "alloc")))]
3779        {
3780            #[cfg(debug_assertions)]
3781            {
3782                assert_eq!(8, core::mem::size_of::<TimeZone>());
3783            }
3784            #[cfg(not(debug_assertions))]
3785            {
3786                // This asserts the same value as the alloc value above, but
3787                // it wasn't always this way, which is why it's written out
3788                // separately. Moreover, in theory, I'd be open to regressing
3789                // this value if it led to an improvement in alloc-mode. But
3790                // more likely, it would be nice to decrease this size in
3791                // non-alloc modes.
3792                assert_eq!(8, core::mem::size_of::<TimeZone>());
3793            }
3794        }
3795    }
3796
3797    /// This tests a few other cases for `TimeZone::to_offset` that
3798    /// probably aren't worth showing in doctest examples.
3799    #[test]
3800    fn time_zone_to_offset() {
3801        let ts = Timestamp::from_second(123456789).unwrap();
3802
3803        let tz = TimeZone::fixed(offset(-5));
3804        let info = tz.to_offset_info(ts);
3805        assert_eq!(info.offset(), offset(-5));
3806        assert_eq!(info.dst(), Dst::No);
3807        assert_eq!(info.abbreviation(), "-05");
3808
3809        let tz = TimeZone::fixed(offset(5));
3810        let info = tz.to_offset_info(ts);
3811        assert_eq!(info.offset(), offset(5));
3812        assert_eq!(info.dst(), Dst::No);
3813        assert_eq!(info.abbreviation(), "+05");
3814
3815        let tz = TimeZone::fixed(offset(-12));
3816        let info = tz.to_offset_info(ts);
3817        assert_eq!(info.offset(), offset(-12));
3818        assert_eq!(info.dst(), Dst::No);
3819        assert_eq!(info.abbreviation(), "-12");
3820
3821        let tz = TimeZone::fixed(offset(12));
3822        let info = tz.to_offset_info(ts);
3823        assert_eq!(info.offset(), offset(12));
3824        assert_eq!(info.dst(), Dst::No);
3825        assert_eq!(info.abbreviation(), "+12");
3826
3827        let tz = TimeZone::fixed(offset(0));
3828        let info = tz.to_offset_info(ts);
3829        assert_eq!(info.offset(), offset(0));
3830        assert_eq!(info.dst(), Dst::No);
3831        assert_eq!(info.abbreviation(), "UTC");
3832    }
3833
3834    /// This tests a few other cases for `TimeZone::to_fixed_offset` that
3835    /// probably aren't worth showing in doctest examples.
3836    #[test]
3837    fn time_zone_to_fixed_offset() {
3838        let tz = TimeZone::UTC;
3839        assert_eq!(tz.to_fixed_offset().unwrap(), Offset::UTC);
3840
3841        let offset = Offset::from_hours(1).unwrap();
3842        let tz = TimeZone::fixed(offset);
3843        assert_eq!(tz.to_fixed_offset().unwrap(), offset);
3844
3845        #[cfg(feature = "alloc")]
3846        {
3847            let tz = TimeZone::posix("EST5").unwrap();
3848            assert!(tz.to_fixed_offset().is_err());
3849
3850            let test_file = TzifTestFile::get("America/New_York");
3851            let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
3852            assert!(tz.to_fixed_offset().is_err());
3853        }
3854    }
3855
3856    /// This tests that `TimeZone::following` correctly returns a final time
3857    /// zone transition.
3858    #[cfg(feature = "alloc")]
3859    #[test]
3860    fn time_zone_following_boa_vista() {
3861        use alloc::{vec, vec::Vec};
3862
3863        let test_file = TzifTestFile::get("America/Boa_Vista");
3864        let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
3865        let last4: Vec<Timestamp> = vec![
3866            "1999-10-03T04Z".parse().unwrap(),
3867            "2000-02-27T03Z".parse().unwrap(),
3868            "2000-10-08T04Z".parse().unwrap(),
3869            "2000-10-15T03Z".parse().unwrap(),
3870        ];
3871
3872        let start: Timestamp = "2001-01-01T00Z".parse().unwrap();
3873        let mut transitions: Vec<Timestamp> =
3874            tz.preceding(start).take(4).map(|t| t.timestamp()).collect();
3875        transitions.reverse();
3876        assert_eq!(transitions, last4);
3877
3878        let start: Timestamp = "1990-01-01T00Z".parse().unwrap();
3879        let transitions: Vec<Timestamp> =
3880            tz.following(start).map(|t| t.timestamp()).collect();
3881        // The regression here was that the 2000-10-15 transition wasn't
3882        // being found here, despite the fact that it existed and was found
3883        // by `preceding`.
3884        assert_eq!(transitions, last4);
3885    }
3886
3887    #[cfg(feature = "alloc")]
3888    #[test]
3889    fn regression_tzif_parse_panic() {
3890        _ = TimeZone::tzif(
3891            "",
3892            &[
3893                84, 90, 105, 102, 6, 0, 5, 35, 84, 10, 77, 0, 0, 0, 84, 82,
3894                105, 102, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3895                0, 0, 0, 0, 2, 0, 0, 0, 5, 0, 0, 82, 28, 77, 0, 0, 90, 105,
3896                78, 0, 0, 0, 0, 0, 0, 0, 84, 90, 105, 102, 0, 0, 5, 0, 84, 90,
3897                105, 84, 77, 10, 0, 0, 0, 15, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3898                0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 5, 0, 0, 0, 82, 0, 64, 1, 0,
3899                0, 2, 0, 0, 0, 0, 0, 0, 126, 1, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0,
3900                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 126, 0, 0, 0, 0, 0,
3901                0, 160, 109, 1, 0, 90, 105, 102, 0, 0, 5, 0, 87, 90, 105, 84,
3902                77, 10, 0, 0, 0, 0, 0, 122, 102, 105, 0, 0, 0, 0, 0, 0, 0, 0,
3903                2, 0, 0, 0, 0, 0, 0, 5, 82, 0, 0, 0, 0, 0, 2, 0, 0, 90, 105,
3904                102, 0, 0, 5, 0, 84, 90, 105, 84, 77, 10, 0, 0, 0, 102, 0, 0,
3905                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 90, 195, 190, 10, 84,
3906                90, 77, 49, 84, 90, 105, 102, 49, 44, 74, 51, 44, 50, 10,
3907            ],
3908        );
3909    }
3910
3911    /// A regression test where a TZ lookup for the minimum civil datetime
3912    /// resulted in a panic in the TZif handling.
3913    #[cfg(feature = "alloc")]
3914    #[test]
3915    fn regression_tz_lookup_datetime_min() {
3916        use alloc::string::ToString;
3917
3918        let test_file = TzifTestFile::get("America/Boa_Vista");
3919        let tz = TimeZone::tzif(test_file.name, test_file.data).unwrap();
3920        let err = tz.to_timestamp(DateTime::MIN).unwrap_err();
3921        assert_eq!(
3922            err.to_string(),
3923            "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",
3924        );
3925    }
3926}