Skip to main content

jiff_core/tz/
posix.rs

1/*!
2Implements POSIX time zone string parsing and transition handling.
3
4The `TZ` environment variable is most commonly used to set a time zone. For
5example, `TZ=America/New_York`. But it can also be used to tersely define DST
6transitions. Moreover, the format is not just used as an environment variable,
7but is also included at the end of TZif files (version 2 or greater). The IANA
8Time Zone Database project also [documents the `TZ` variable][iana-env] with
9a little more commentary.
10
11Note that we (along with pretty much everyone else) don't strictly follow
12POSIX here. Namely, `TZ=America/New_York` isn't a POSIX compatible usage,
13and I believe it technically should be `TZ=:America/New_York`. Nevertheless,
14apparently some group of people (IANA folks?) decided `TZ=America/New_York`
15should be fine. From the [IANA `theory.html` documentation][iana-env]:
16
17> It was recognized that allowing the TZ environment variable to take on values
18> such as 'America/New_York' might cause "old" programs (that expect TZ to have
19> a certain form) to operate incorrectly; consideration was given to using
20> some other environment variable (for example, TIMEZONE) to hold the string
21> used to generate the TZif file's name. In the end, however, it was decided
22> to continue using TZ: it is widely used for time zone purposes; separately
23> maintaining both TZ and TIMEZONE seemed a nuisance; and systems where "new"
24> forms of TZ might cause problems can simply use legacy TZ values such as
25> "EST5EDT" which can be used by "new" programs as well as by "old" programs
26> that assume pre-POSIX TZ values.
27
28Indeed, even [musl subscribes to this behavior][musl-env]. So that's what we do
29here too.
30
31Note that a POSIX time zone like `EST5` corresponds to the UTC offset `-05:00`,
32and `GMT-4` corresponds to the UTC offset `+04:00`. Yes, it's backwards. How
33fun.
34
35# IANA v3+ Support
36
37While this module and many of its types are directly associated with POSIX,
38this module also plays a supporting role for `TZ` strings in the IANA TZif
39binary format for versions 2 and greater. Specifically, for versions 3 and
40greater, some minor extensions are supported here via `IanaTz::parse`. But
41using `PosixTz::parse` is limited to parsing what is specified by POSIX.
42Nevertheless, we generally use `IanaTz::parse` everywhere, even when parsing
43the `TZ` environment variable. The reason for this is that it seems to be what
44other programs do in practice (for example, GNU date).
45
46# `no-std` and `no-alloc` support
47
48A big part of this module works fine in core-only environments. But because
49core-only environments provide means of indirection, and embedding a
50`PosixTimeZone` into a `TimeZone` without indirection would use up a lot of
51space (and thereby make `ZonedDateTime` quite chunky), we provide core-only
52support principally through a proc macro. Namely, a `PosixTimeZone` can be
53parsed by the proc macro and then turned into static data.
54
55POSIX time zone support isn't explicitly provided directly as a public API
56for core-only environments, but is implicitly supported via TZif. (Since TZif
57data contains POSIX time zone strings.)
58
59[posix-env]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03
60[iana-env]: https://data.iana.org/time-zones/tzdb-2024a/theory.html#functions
61[musl-env]: https://wiki.musl-libc.org/environment-variables
62*/
63
64use crate::{
65    Timestamp,
66    civil::{Date, DateTime, Time, TimeSecond, Weekday},
67    tz::{
68        Abbreviation, AmbiguousOffset, AmbiguousTimestamp, Offset, OffsetInfo,
69        REASONABLE_ABBREVIATION_MAX, TimeZoneId, Transition,
70    },
71};
72
73/// The result of parsing the POSIX `TZ` environment variable.
74///
75/// A `TZ` variable can either be a POSIX time zone string with an optional DST
76/// transition rule, or it can begin with a `:` followed by an arbitrary set of
77/// bytes that is implementation defined.
78///
79/// In practice, the content following a `:` is treated as an IANA time zone
80/// name. Moreover, even if the `TZ` string doesn't start with a `:` but
81/// corresponds to a IANA time zone name, then it is interpreted as such.
82/// However, this type only encapsulates the choices strictly provided by
83/// POSIX: either a time zone string with an optional DST transition rule,
84/// or an implementation defined string with a `:` prefix. If, for example,
85/// `TZ="America/New_York"`, then that case isn't encapsulated by this type.
86/// Callers needing that functionality will need to handle the error returned
87/// by parsing this type and layer their own semantics on top. In general, any
88/// valid IANA time zone identifier will be an invalid POSIX time zone string.
89#[derive(#[automatically_derived]impl ::core::fmt::Debug for TzEnv {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Rule(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Rule",
                    &__self_0),
            Self::Implementation(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Implementation", &__self_0),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for TzEnv {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<TimeZone>;
        let _: ::core::cmp::AssertParamIsEq<TimeZoneId>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for TzEnv { }
#[automatically_derived]impl ::core::cmp::PartialEq for TzEnv {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Rule(__self_0), Self::Rule(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Implementation(__self_0),
                    Self::Implementation(__arg1_0)) => __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq)]
90pub enum TzEnv {
91    /// A valid POSIX time zone with an optional DST transition rule.
92    Rule(TimeZone),
93    /// An implementation defined string. This occurs when the `TZ` value
94    /// starts with a `:`. The string stored here does not include the `:`.
95    ///
96    /// Typically this is an IANA time zone identifier.
97    Implementation(TimeZoneId),
98}
99
100impl TzEnv {
101    /// Parse a POSIX `TZ` environment variable string from the given bytes.
102    pub fn parse<B: AsRef<[u8]>>(bytes: B) -> Result<TzEnv, ParseError> {
103        let bytes = bytes.as_ref();
104        if bytes.get(0) == Some(&b':') {
105            let Ok(string) = core::str::from_utf8(&bytes[1..]) else {
106                return Err(ParseErrorKind::TzEnvColonInvalidUtf8.into());
107            };
108            let Some(smallstr) = TimeZoneId::new(string) else {
109                return Err(ParseErrorKind::TzEnvColonTooBig.into());
110            };
111            Ok(TzEnv::Implementation(smallstr))
112        } else {
113            TimeZone::parse(bytes).map(TzEnv::Rule)
114        }
115    }
116
117    /// Parse a POSIX `TZ` environment variable string from the given `OsStr`.
118    #[cfg(feature = "std")]
119    pub fn parse_os_str<O: AsRef<std::ffi::OsStr>>(
120        osstr: O,
121    ) -> Result<TzEnv, ParseError> {
122        let bytes = crate::util::os_str_bytes(osstr.as_ref())
123            .ok_or(ParseError::from(ParseErrorKind::TzEnvInvalidUtf8))?;
124        TzEnv::parse(bytes)
125    }
126}
127
128/// A representation of a POSIX time zone transition rule.
129///
130/// POSIX time zones are limited in what they can express. Notably, they can't
131/// handle historic time zone transitions. They generally can only handle
132/// present rules.
133///
134/// Note that the internals of this type are completely exposed to make writing
135/// static data with these types easier.
136///
137/// # On "reasonable" POSIX time zones
138///
139/// Jiff only supports "reasonable" POSIX time zones. A "reasonable" POSIX time
140/// zone is a POSIX time zone that has a DST transition rule _when_ it has a
141/// DST time zone abbreviation. Without the transition rule, it isn't possible
142/// to know when DST starts and stops.
143///
144/// POSIX technically allows a DST time zone abbreviation *without* a
145/// transition rule, but the behavior is literally unspecified. So Jiff just
146/// rejects them.
147///
148/// Note that if you're confused as to why Jiff accepts `TZ=EST5EDT` (where
149/// `EST5EDT` is an example of an _unreasonable_ POSIX time zone), that's
150/// because Jiff rejects `EST5EDT` and instead attempts to use it as an IANA
151/// time zone identifier. And indeed, the IANA Time Zone Database contains an
152/// entry for `EST5EDT` (presumably for legacy reasons).
153///
154/// Also, we expect `TZ` strings parsed from IANA v2+ formatted `tzfile`s to
155/// also be reasonable or parsing fails. This also seems to be consistent with
156/// the [GNU C Library]'s treatment of the `TZ` variable: it only documents
157/// support for reasonable POSIX time zone strings.
158///
159/// Note that a V2 `TZ` string is precisely identical to a POSIX `TZ`
160/// environment variable string. A V3 `TZ` string however supports signed DST
161/// transition times, and hours in the range `0..=167`. The V2 and V3 here
162/// reference how `TZ` strings are defined in the TZif format specified by
163/// [RFC 9636]. V2 is the original version of it straight from POSIX, where as
164/// V3+ corresponds to an extension added to V3 (and newer versions) of the
165/// TZif format. V3 is a superset of V2, so in practice, Jiff just permits
166/// V3 everywhere.
167///
168/// [GNU C Library]: https://www.gnu.org/software/libc/manual/2.25/html_node/TZ-Variable.html
169/// [RFC 9636]: https://datatracker.ietf.org/doc/rfc9636/
170///
171/// # Example
172///
173/// ```
174/// use jiff_core::{tz::{Offset, posix::TimeZone}, Timestamp};
175///
176/// let tz = TimeZone::parse("EST5EDT,M3.2.0,M11.1.0").unwrap();
177///
178/// let ts = Timestamp::from_second(1783100574).unwrap();
179/// let offset = tz.to_offset(ts);
180/// assert_eq!(offset, Offset::from_seconds(-4 * 60 * 60).unwrap());
181///
182/// // Around 6 months later, we should be out of DST.
183/// let ts = Timestamp::from_second(ts.as_second() + 6 * 30 * 86400).unwrap();
184/// let offset = tz.to_offset(ts);
185/// assert_eq!(offset, Offset::from_seconds(-5 * 60 * 60).unwrap());
186/// ```
187#[derive(#[automatically_derived]impl ::core::clone::Clone for TimeZone {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        TimeZone {
            std_abbrev: ::core::clone::Clone::clone(&self.std_abbrev),
            std_offset: ::core::clone::Clone::clone(&self.std_offset),
            dst: ::core::clone::Clone::clone(&self.dst),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for TimeZone {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "TimeZone std_abbrev std_offset dst", &self.std_abbrev,
            &self.std_offset, &&self.dst)
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for TimeZone {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Abbreviation>;
        let _: ::core::cmp::AssertParamIsEq<Offset>;
        let _: ::core::cmp::AssertParamIsEq<Option<Dst>>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for TimeZone
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for TimeZone {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.std_abbrev == other.std_abbrev &&
                self.std_offset == other.std_offset && self.dst == other.dst
    }
}PartialEq)]
188// This ensures the alignment of this type is always *at least* 8 bytes. This
189// is required for the pointer tagging inside of `TimeZone` to be sound. At
190// time of writing (2024-02-24), this explicit `repr` isn't required on 64-bit
191// systems since the type definition is such that it will have an alignment
192// of at least 8 bytes anyway. But this *is* required for 32-bit systems,
193// where the type definition at present only has an alignment of 4 bytes.
194// The alignment can also potentially change depending on whether `alloc` is
195// enabled (since without `alloc` an `Abbreviation` is always just a fixed size
196// array).
197#[repr(align(8))]
198pub struct TimeZone {
199    /// The abbreviation for standard time.
200    pub std_abbrev: Abbreviation,
201    /// The offset for standard time.
202    pub std_offset: Offset,
203    /// Whether there is any daylight saving time for this POSIX time zone.
204    pub dst: Option<Dst>,
205}
206
207/// The time zone transition rule along with its abbreviation and offset.
208#[derive(#[automatically_derived]impl ::core::clone::Clone for Dst {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        Dst {
            abbrev: ::core::clone::Clone::clone(&self.abbrev),
            offset: ::core::clone::Clone::clone(&self.offset),
            rule: ::core::clone::Clone::clone(&self.rule),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Dst {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "Dst abbrev offset rule", &self.abbrev, &self.offset, &&self.rule)
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for Dst {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Abbreviation>;
        let _: ::core::cmp::AssertParamIsEq<Offset>;
        let _: ::core::cmp::AssertParamIsEq<Rule>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Dst { }
#[automatically_derived]impl ::core::cmp::PartialEq for Dst {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.abbrev == other.abbrev && self.offset == other.offset &&
            self.rule == other.rule
    }
}PartialEq)]
209pub struct Dst {
210    /// The abbreviation to assign to civil datetimes when the daylight saving
211    /// time rule is satisfied.
212    pub abbrev: Abbreviation,
213    /// The offset from UTC that civil datetimes get when the daylight saving
214    /// time rule is satisfied.
215    pub offset: Offset,
216    /// The actual rule.
217    pub rule: Rule,
218}
219
220/// A time zone transition rule.
221///
222/// This spells out a "range" of datetimes within a calendar year that should
223/// get a special daylight saving time offset from UTC.
224#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Rule {
}
#[automatically_derived]impl ::core::clone::Clone for Rule {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<DayTime>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Rule { }Copy, #[automatically_derived]impl ::core::fmt::Debug for Rule {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "Rule start end", &self.start, &&self.end)
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for Rule {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DayTime>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Rule { }
#[automatically_derived]impl ::core::cmp::PartialEq for Rule {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.start == other.start && self.end == other.end
    }
}PartialEq)]
225pub struct Rule {
226    /// The start of the time zone transition (e.g., daylight saving time).
227    pub start: DayTime,
228    /// The end of the time zone transition (e.g., daylight saving time).
229    pub end: DayTime,
230}
231
232/// The day of a year and the time from that day on which a time zone
233/// transition occurs.
234#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DayTime {
}
#[automatically_derived]impl ::core::clone::Clone for DayTime {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Day>;
        let _: ::core::clone::AssertParamIsClone<TransitionCivilTime>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for DayTime { }Copy, #[automatically_derived]impl ::core::fmt::Debug for DayTime {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "DayTime date time", &self.date, &&self.time)
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for DayTime {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Day>;
        let _: ::core::cmp::AssertParamIsEq<TransitionCivilTime>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for DayTime {
}
#[automatically_derived]impl ::core::cmp::PartialEq for DayTime {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.date == other.date && self.time == other.time
    }
}PartialEq)]
235pub struct DayTime {
236    /// The way to determine the day of the year.
237    pub date: Day,
238    /// The civil time on the day when the offset for civil time changes.
239    pub time: TransitionCivilTime,
240}
241
242/// Represents a day in particular year on which a time zone transition occurs.
243#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Day {
}
#[automatically_derived]impl ::core::clone::Clone for Day {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<i16>;
        let _: ::core::clone::AssertParamIsClone<i8>;
        let _: ::core::clone::AssertParamIsClone<Weekday>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Day { }Copy, #[automatically_derived]impl ::core::fmt::Debug for Day {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::JulianOne(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "JulianOne", &__self_0),
            Self::JulianZero(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "JulianZero", &__self_0),
            Self::WeekdayOfMonth {
                month: __self_0, week: __self_1, weekday: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "WeekdayOfMonth month week weekday", __self_0, __self_1,
                    &__self_2),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for Day {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<i16>;
        let _: ::core::cmp::AssertParamIsEq<i8>;
        let _: ::core::cmp::AssertParamIsEq<Weekday>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Day { }
#[automatically_derived]impl ::core::cmp::PartialEq for Day {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::JulianOne(__self_0), Self::JulianOne(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::JulianZero(__self_0), Self::JulianZero(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::WeekdayOfMonth {
                    month: __self_0, week: __self_1, weekday: __self_2 },
                    Self::WeekdayOfMonth {
                    month: __arg1_0, week: __arg1_1, weekday: __arg1_2 }) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1 &&
                        __self_2 == __arg1_2,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq)]
244pub enum Day {
245    /// Julian day in a year, no counting for leap days.
246    ///
247    /// Valid range is `1..=365`.
248    JulianOne(i16),
249    /// Julian day in a year, counting for leap days.
250    ///
251    /// Valid range is `0..=365`.
252    JulianZero(i16),
253    /// The nth weekday of a month.
254    WeekdayOfMonth {
255        /// The month.
256        ///
257        /// Valid range is: `1..=12`.
258        month: i8,
259        /// The week.
260        ///
261        /// Valid range is `1..=5`.
262        ///
263        /// One interesting thing to note here (or my interpretation anyway),
264        /// is that a week of `4` means the "4th weekday in a month" where as
265        /// a week of `5` means the "last weekday in a month, even if it's the
266        /// 4th weekday."
267        week: i8,
268        /// The weekday.
269        weekday: Weekday,
270    },
271}
272
273/// Represents the civil time at which a time zone transition occurs.
274///
275/// Note that this does not use `civil::TimeSecond` because this may be longer
276/// than a single civil day (i.e., bigger than 86400). It can also be negative.
277#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for TransitionCivilTime {
}
#[automatically_derived]impl ::core::clone::Clone for TransitionCivilTime {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<i32>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for TransitionCivilTime { }Copy, #[automatically_derived]impl ::core::fmt::Debug for TransitionCivilTime {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "TransitionCivilTime second", &&self.second)
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for TransitionCivilTime {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<i32>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    TransitionCivilTime {
}
#[automatically_derived]impl ::core::cmp::PartialEq for TransitionCivilTime {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.second == other.second }
}PartialEq)]
278pub struct TransitionCivilTime {
279    /// The time in seconds. This may be negative.
280    ///
281    /// Valid range is `[-604_799, 604_799]`.
282    pub second: i32,
283}
284
285impl TimeZone {
286    /// Parse a POSIX `TZ` environment variable, assuming it's a rule and not
287    /// an implementation defined value, from the given byte string.
288    ///
289    /// # Errors
290    ///
291    /// This returns an error if the given byte string is not a valid POSIX
292    /// time zone transition rule.
293    ///
294    /// This also returns an error if, after parsing the POSIX time zone
295    /// transition rule, there are still bytes remaining in the string given.
296    pub fn parse<B: AsRef<[u8]>>(bytes: B) -> Result<TimeZone, ParseError> {
297        let bytes = bytes.as_ref();
298        // We enable the IANA v3+ extensions here. (Namely, that the time
299        // specification hour value has the range `-167..=167` instead of
300        // `0..=24`.) Requiring strict POSIX rules doesn't seem necessary
301        // since the extension is a strict superset. Plus, GNU tooling
302        // seems to accept the extension.
303        let parser = Parser { ianav3plus: true, ..Parser::new(bytes) };
304        parser.parse()
305    }
306
307    /// Like `TimeZone::parse`, but parses a prefix of the input given. In
308    /// addition to returning a `TimeZone`, this also returns the offset into
309    /// `bytes` pointing at the beginning of any remaining unparsed input.
310    ///
311    /// # Errors
312    ///
313    /// This returns an error if the given byte string is not a valid POSIX
314    /// time zone transition rule.
315    pub fn parse_prefix<'b, B: AsRef<[u8]> + ?Sized>(
316        bytes: &'b B,
317    ) -> Result<(TimeZone, usize), ParseError> {
318        let bytes = bytes.as_ref();
319        let parser = Parser { ianav3plus: true, ..Parser::new(bytes) };
320        parser.parse_prefix()
321    }
322}
323
324impl TimeZone {
325    /// Returns the appropriate time zone offset to use for the given
326    /// timestamp.
327    ///
328    /// If you need information like whether the offset is in DST or not, or
329    /// the time zone abbreviation, then use `TimeZone::to_offset_info`.
330    /// But that API may be more expensive to use, so only use it if you need
331    /// the additional data.
332    pub fn to_offset(&self, timestamp: Timestamp) -> Offset {
333        if self.dst.is_none() {
334            return self.std_offset;
335        }
336
337        let dt = timestamp.to_datetime(Offset::UTC);
338        self.dst_info_utc(dt.date().year())
339            .filter(|dst_info| dst_info.in_dst(dt))
340            .map(|dst_info| dst_info.offset())
341            .unwrap_or_else(|| self.std_offset)
342    }
343
344    /// Returns the appropriate time zone offset to use for the given
345    /// timestamp.
346    ///
347    /// This also includes whether the offset returned should be considered
348    /// to be "DST" or not, along with the time zone abbreviation (e.g., EST
349    /// for standard time in New York, and EDT for DST in New York).
350    pub fn to_offset_info(&self, timestamp: Timestamp) -> OffsetInfo {
351        if self.dst.is_none() {
352            return OffsetInfo {
353                offset: self.std_offset,
354                abbreviation: self.std_abbrev.clone(),
355                dst: super::Dst::No,
356            };
357        }
358
359        let dt = timestamp.to_datetime(Offset::UTC);
360        self.dst_info_utc(dt.date().year())
361            .filter(|dst_info| dst_info.in_dst(dt))
362            .map(|dst_info| OffsetInfo {
363                offset: dst_info.offset(),
364                abbreviation: dst_info.dst.abbrev.clone(),
365                dst: super::Dst::Yes,
366            })
367            .unwrap_or_else(|| OffsetInfo {
368                offset: self.std_offset,
369                abbreviation: self.std_abbrev.clone(),
370                dst: super::Dst::No,
371            })
372    }
373
374    /// Returns a possibly ambiguous timestamp for the given civil datetime.
375    ///
376    /// The given datetime should correspond to the "wall" clock time of what
377    /// humans use to tell time for this time zone.
378    ///
379    /// Note that "ambiguous timestamp" is represented by the possible
380    /// selection of offsets that could be applied to the given datetime. In
381    /// general, it is only ambiguous around transitions to-and-from DST. The
382    /// ambiguity can arise as a "fold" (when a particular wall clock time is
383    /// repeated) or as a "gap" (when a particular wall clock time is skipped
384    /// entirely).
385    pub fn to_ambiguous_timestamp(&self, dt: DateTime) -> AmbiguousTimestamp {
386        let year = dt.date().year();
387        let std_offset = self.std_offset;
388        let Some(dst_info) = self.dst_info_wall(year) else {
389            return AmbiguousOffset::Unambiguous { offset: std_offset }
390                .into_ambiguous_timestamp(dt);
391        };
392        let dst_offset = dst_info.offset();
393        let diff = std_offset.until(dst_offset);
394        // When the difference between DST and standard is positive, that means
395        // STD->DST results in a gap while DST->STD results in a fold. However,
396        // when the difference is negative, that means STD->DST results in a
397        // fold while DST->STD results in a gap. The former is by far the most
398        // common. The latter is a bit weird, but real cases do exist. For
399        // example, Dublin has DST in winter (UTC+01) and STD in the summer
400        // (UTC+00).
401        //
402        // When the difference is zero, then we have a weird POSIX time zone
403        // where a DST transition rule was specified, but was set to explicitly
404        // be the same as STD. In this case, there can be no ambiguity. (The
405        // zero case is strictly redundant. Both the diff < 0 and diff > 0
406        // cases handle the zero case correctly. But we write it out for
407        // clarity.)
408        let ambiguous_offset = if diff == 0 {
409            if true {
    {
        match (&std_offset, &dst_offset) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(std_offset, dst_offset);
410            AmbiguousOffset::Unambiguous { offset: std_offset }
411        } else if diff.is_negative() {
412            // For DST transitions that always move behind one hour, ambiguous
413            // timestamps only occur when the given civil datetime falls in the
414            // standard time range.
415            if dst_info.in_dst(dt) {
416                AmbiguousOffset::Unambiguous { offset: dst_offset }
417            } else {
418                let fold_start = dst_info.start.saturating_add_seconds(diff);
419                let gap_end =
420                    dst_info.end.saturating_add_seconds(diff.saturating_neg());
421                if fold_start <= dt && dt < dst_info.start {
422                    AmbiguousOffset::Fold {
423                        before: std_offset,
424                        after: dst_offset,
425                    }
426                } else if dst_info.end <= dt && dt < gap_end {
427                    AmbiguousOffset::Gap {
428                        before: dst_offset,
429                        after: std_offset,
430                    }
431                } else {
432                    AmbiguousOffset::Unambiguous { offset: std_offset }
433                }
434            }
435        } else {
436            // For DST transitions that always move ahead one hour, ambiguous
437            // timestamps only occur when the given civil datetime falls in the
438            // DST range.
439            if !dst_info.in_dst(dt) {
440                AmbiguousOffset::Unambiguous { offset: std_offset }
441            } else {
442                // PERF: I wonder if it makes sense to pre-compute these?
443                // Probably not, because we have to do it based on year of
444                // datetime given. But if we ever add a "caching" layer for
445                // POSIX time zones, then it might be worth adding these to it.
446                let gap_end = dst_info.start.saturating_add_seconds(diff);
447                let fold_start =
448                    dst_info.end.saturating_add_seconds(diff.saturating_neg());
449                if dst_info.start <= dt && dt < gap_end {
450                    AmbiguousOffset::Gap {
451                        before: std_offset,
452                        after: dst_offset,
453                    }
454                } else if fold_start <= dt && dt < dst_info.end {
455                    AmbiguousOffset::Fold {
456                        before: dst_offset,
457                        after: std_offset,
458                    }
459                } else {
460                    AmbiguousOffset::Unambiguous { offset: dst_offset }
461                }
462            }
463        };
464        ambiguous_offset.into_ambiguous_timestamp(dt)
465    }
466
467    /// Returns the timestamp of the most recent time zone transition prior
468    /// to the timestamp given. If one doesn't exist, `None` is returned.
469    pub fn previous_transition(
470        &self,
471        timestamp: Timestamp,
472    ) -> Option<Transition> {
473        let dt = timestamp.to_datetime(Offset::UTC);
474        let dst_info = self.dst_info_utc(dt.date().year())?;
475        let (earlier, later) = dst_info.ordered();
476        let (prev, dst_info) = if dt > later {
477            (later, dst_info)
478        } else if dt > earlier {
479            (earlier, dst_info)
480        } else {
481            let prev_year = if dt.date().year() == Date::MIN.year() {
482                return None;
483            } else {
484                dt.date().year() - 1
485            };
486            let dst_info = self.dst_info_utc(prev_year)?;
487            let (_, later) = dst_info.ordered();
488            (later, dst_info)
489        };
490
491        let timestamp = prev.to_timestamp(Offset::UTC).ok()?;
492        let dt = timestamp.to_datetime(Offset::UTC);
493        let (offset, abbreviation, dst) = if dst_info.in_dst(dt) {
494            (dst_info.offset(), dst_info.dst.abbrev.clone(), super::Dst::Yes)
495        } else {
496            (self.std_offset, self.std_abbrev.clone(), super::Dst::No)
497        };
498        let info = OffsetInfo { offset, abbreviation, dst };
499        Some(Transition { timestamp, info })
500    }
501
502    /// Returns the timestamp of the soonest time zone transition after the
503    /// timestamp given. If one doesn't exist, `None` is returned.
504    pub fn next_transition(&self, timestamp: Timestamp) -> Option<Transition> {
505        let dt = timestamp.to_datetime(Offset::UTC);
506        let dst_info = self.dst_info_utc(dt.date().year())?;
507        let (earlier, later) = dst_info.ordered();
508        let (next, dst_info) = if dt < earlier {
509            (earlier, dst_info)
510        } else if dt < later {
511            (later, dst_info)
512        } else {
513            let next_year = if dt.date().year() == Date::MAX.year() {
514                return None;
515            } else {
516                dt.date().year() + 1
517            };
518            let dst_info = self.dst_info_utc(next_year)?;
519            let (earlier, _) = dst_info.ordered();
520            (earlier, dst_info)
521        };
522
523        let timestamp = next.to_timestamp(Offset::UTC).ok()?;
524        let dt = timestamp.to_datetime(Offset::UTC);
525        let (offset, abbreviation, dst) = if dst_info.in_dst(dt) {
526            (dst_info.offset(), dst_info.dst.abbrev.clone(), super::Dst::Yes)
527        } else {
528            (self.std_offset, self.std_abbrev.clone(), super::Dst::No)
529        };
530        let info = OffsetInfo { offset, abbreviation, dst };
531        Some(Transition { timestamp, info })
532    }
533
534    /// Returns the range in which DST occurs.
535    ///
536    /// The civil datetimes returned are in UTC. This is useful for determining
537    /// whether a timestamp is in DST or not.
538    fn dst_info_utc(&self, year: i16) -> Option<DstInfo<'_>> {
539        let dst = self.dst.as_ref()?;
540        // DST time starts with respect to standard time, so offset it by the
541        // standard offset.
542        let start = dst.rule.start.to_datetime(year, self.std_offset);
543        // DST time ends with respect to DST time, so offset it by the DST
544        // offset.
545        let mut end = dst.rule.end.to_datetime(year, dst.offset);
546        // This is a whacky special case when DST is permanent, but the math
547        // used to calculate the start/end datetimes ends up leaving a gap
548        // for standard time to appear. In which case, it's possible for a
549        // timestamp at the end of a calendar year to get standard time when
550        // it really should be DST.
551        //
552        // We detect this case by re-interpreting the end of the boundary using
553        // the standard offset. If we get a datetime that is in a different
554        // year, then it follows that standard time is actually impossible to
555        // occur.
556        //
557        // These weird POSIX time zones can occur as the TZ strings in
558        // a TZif file compiled using rearguard semantics. For example,
559        // `Africa/Casablanca` has:
560        //
561        //     XXX-2<+01>-1,0/0,J365/23
562        //
563        // Notice here that DST is actually one hour *behind* (it is usually
564        // one hour *ahead*) _and_ it ends at 23:00:00 on the last day of the
565        // year. But if it ends at 23:00, then jumping to standard time moves
566        // the clocks *forward*. Which would bring us to 00:00:00 on the first
567        // of the next year... but that is when DST begins! Hence, DST is
568        // permanent.
569        //
570        // Ideally, this could just be handled by our math automatically. But
571        // I couldn't figure out how to make it work. In particular, in the
572        // above example for year 2087, we get
573        //
574        //     start == 2087-01-01T00:00:00Z
575        //     end == 2087-12-31T22:00:00Z
576        //
577        // Which leaves a two hour gap for a timestamp to get erroneously
578        // categorized as standard time.
579        //
580        // ... so we special case this. We could pre-compute whether a POSIX
581        // time zone is in permanent DST at construction time, but it's not
582        // obvious to me that it's worth it. Especially since this is an
583        // exceptionally rare case.
584        //
585        // Note that I did try to consult tzcode's (incredibly inscrutable)
586        // `localtime` implementation to figure out how they deal with it. At
587        // first, it looks like they don't have any special handling for this
588        // case. But looking more closely, they skip any time zone transitions
589        // generated by POSIX time zones whose rule spans more than 1 year:
590        //
591        //     https://github.com/eggert/tz/blob/8d65db9786753f3b263087e31c59d191561d63e3/localtime.c#L1717-L1735
592        //
593        // By just ignoring them, I think it achieves the desired effect of
594        // permanent DST. But I'm not 100% confident in my understanding of
595        // the code.
596        if start.date().month() == 1
597            && start.date().day() == 1
598            && start.time() == Time::MIN
599            // NOTE: This should come last because it is potentially expensive.
600            && year
601                != end.saturating_add_seconds(self.std_offset.seconds()).date().year()
602        {
603            end = DateTime::from_parts(
604                Date::new(year, 12, 31)
605                    .expect("12/31 is valid for all valid years"),
606                Time::MAX,
607            );
608        }
609        Some(DstInfo { dst, start, end })
610    }
611
612    /// Returns the range in which DST occurs.
613    ///
614    /// The civil datetimes returned are in "wall clock time." That is, they
615    /// represent the transitions as they are seen from humans reading a clock
616    /// within the geographic location of that time zone.
617    fn dst_info_wall(&self, year: i16) -> Option<DstInfo<'_>> {
618        let dst = self.dst.as_ref()?;
619        // POSIX time zones express their DST transitions in terms of wall
620        // clock time. Since this method specifically is returning wall
621        // clock times, we don't want to offset our datetimes at all.
622        let start = dst.rule.start.to_datetime(year, Offset::UTC);
623        let end = dst.rule.end.to_datetime(year, Offset::UTC);
624        Some(DstInfo { dst, start, end })
625    }
626
627    /// Returns the DST transition rule. This panics if this time zone doesn't
628    /// have DST.
629    #[cfg(test)]
630    fn rule(&self) -> &Rule {
631        &self.dst.as_ref().unwrap().rule
632    }
633}
634
635impl DayTime {
636    /// Turns this POSIX datetime spec into a civil datetime in the year given
637    /// with the given offset. The datetimes returned are offset by the given
638    /// offset. For wall clock time, an offset of `0` should be given. For
639    /// UTC time, the offset (standard or DST) corresponding to this time
640    /// spec should be given.
641    ///
642    /// The datetime returned is guaranteed to have a year component equal
643    /// to the year given. This guarantee is upheld even when the datetime
644    /// specification (combined with the offset) would extend past the end of
645    /// the year (or before the start of the year). In this case, the maximal
646    /// (or minimal) datetime for the given year is returned.
647    fn to_datetime(&self, year: i16, offset: Offset) -> DateTime {
648        let mkmin =
649            || DateTime::from_parts(Date::new(year, 1, 1).unwrap(), Time::MIN);
650        let mkmax = || {
651            DateTime::from_parts(Date::new(year, 12, 31).unwrap(), Time::MAX)
652        };
653        let Some(date) = self.date.to_date(year) else { return mkmax() };
654        // The range on `self.time` is `-604799..=604799`, and the range
655        // on `offset.second` is `-93599..=93599`. Therefore, subtracting
656        // them can never overflow an `i32`.
657        let offset = self.time.second - offset.seconds();
658        // If the time goes negative or above 86400, then we might have
659        // to adjust our date.
660        let days = offset.div_euclid(86400);
661        let second = offset.rem_euclid(86400);
662
663        let Ok(date) = date.checked_add(days) else {
664            return if offset < 0 { mkmin() } else { mkmax() };
665        };
666        if date.year() < year {
667            mkmin()
668        } else if date.year() > year {
669            mkmax()
670        } else {
671            // OK because we just did modulo 86400 above.
672            let time = TimeSecond::new(second).unwrap().to_time();
673            DateTime::from_parts(date, time)
674        }
675    }
676}
677
678impl Day {
679    /// Convert this date specification to a civil date in the year given.
680    ///
681    /// If this date specification couldn't be turned into a date in the year
682    /// given, then `None` is returned. This happens when `366` is given as
683    /// a day, but the year given is not a leap year. In this case, callers may
684    /// want to assume a datetime that is maximal for the year given.
685    fn to_date(&self, year: i16) -> Option<Date> {
686        match *self {
687            Day::JulianOne(day) => {
688                // Parsing validates that our day is 1-365 which will always
689                // succeed for all possible year values. That is, every valid
690                // year has a December 31.
691                Some(
692                    Date::from_day_of_year_no_leap(year, day)
693                        .expect("Julian `J day` should be in bounds"),
694                )
695            }
696            Day::JulianZero(day) => {
697                // OK because our value for `day` is validated to be `0..=365`,
698                // and since it is an `i16`, it is always valid to add 1.
699                //
700                // Also, while `day+1` is guaranteed to be in `1..=366`, it is
701                // possible that `366` is invalid, for when `year` is not a
702                // leap year. In this case, we throw our hands up, and ask the
703                // caller to make a decision for how to deal with it. Why does
704                // POSIX go out of its way to specifically not specify behavior
705                // in error cases?
706                Date::from_day_of_year(year, day + 1).ok()
707            }
708            Day::WeekdayOfMonth { month, week, weekday } => {
709                let first = Date::new(year, month, 1)
710                    .expect("all valid year/month combinations support day 1");
711                let week = if week == 5 { -1 } else { week };
712                if true {
    if !(week == -1 || (1..=4).contains(&week)) {
        ::core::panicking::panic("assertion failed: week == -1 || (1..=4).contains(&week)")
    };
};debug_assert!(week == -1 || (1..=4).contains(&week));
713                // This is maybe non-obvious, but this will always succeed
714                // because it can only fail when the week number is one of
715                // {-5, 0, 5}. Since we've validated that 'week' is in 1..=5,
716                // we know it can't be 0. Moreover, because of the conditional
717                // above and since `5` actually means "last weekday of month,"
718                // that case will always translate to `-1`.
719                //
720                // Also, I looked at how other libraries deal with this case,
721                // and almost all of them just do a bunch of inline hairy
722                // arithmetic here. I suppose I could be reduced to such
723                // things if perf called for it, but we have a nice civil date
724                // abstraction. So use it, god damn it. (Well, we did, and now
725                // we have a lower level IDate abstraction. But it's still
726                // an abstraction!)
727                Some(
728                    first
729                        .nth_weekday_of_month(week, weekday)
730                        .expect("nth weekday always exists"),
731                )
732            }
733        }
734    }
735}
736
737impl TransitionCivilTime {
738    /// The "default" time for a time zone transition to occur.
739    ///
740    /// This is used, as specified by POSIX, whenever a specific time of day
741    /// is omitted from a POSIX time zone transition rule string.
742    pub const DEFAULT: TransitionCivilTime =
743        TransitionCivilTime { second: 2 * 60 * 60 };
744}
745
746/// The daylight saving time (DST) info for a POSIX time zone in a particular
747/// year.
748#[derive(#[automatically_derived]impl<'a> ::core::fmt::Debug for DstInfo<'a> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "DstInfo dst start end", &self.dst, &self.start, &&self.end)
    }
}Debug, #[automatically_derived]impl<'a> ::core::cmp::Eq for DstInfo<'a> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<&'a Dst>;
        let _: ::core::cmp::AssertParamIsEq<DateTime>;
    }
}Eq, #[automatically_derived]impl<'a> ::core::marker::StructuralPartialEq for
    DstInfo<'a> {
}
#[automatically_derived]impl<'a> ::core::cmp::PartialEq for DstInfo<'a> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.dst == other.dst && self.start == other.start &&
            self.end == other.end
    }
}PartialEq)]
749struct DstInfo<'a> {
750    /// The DST transition rule that generated this info.
751    dst: &'a Dst,
752    /// The start time (inclusive) that DST begins.
753    ///
754    /// Note that this may be greater than `end`. This tends to happen in the
755    /// southern hemisphere.
756    ///
757    /// Note also that this may be in UTC or in wall clock civil
758    /// time. It depends on whether `TimeZone::dst_info_utc` or
759    /// `TimeZone::dst_info_wall` was used.
760    start: DateTime,
761    /// The end time (exclusive) that DST ends.
762    ///
763    /// Note that this may be less than `start`. This tends to happen in the
764    /// southern hemisphere.
765    ///
766    /// Note also that this may be in UTC or in wall clock civil
767    /// time. It depends on whether `TimeZone::dst_info_utc` or
768    /// `TimeZone::dst_info_wall` was used.
769    end: DateTime,
770}
771
772impl<'a> DstInfo<'a> {
773    /// Returns true if and only if the given civil datetime ought to be
774    /// considered in DST.
775    fn in_dst(&self, utc_dt: DateTime) -> bool {
776        if self.start <= self.end {
777            self.start <= utc_dt && utc_dt < self.end
778        } else {
779            !(self.end <= utc_dt && utc_dt < self.start)
780        }
781    }
782
783    /// Returns the earlier and later times for this DST info.
784    fn ordered(&self) -> (DateTime, DateTime) {
785        if self.start <= self.end {
786            (self.start, self.end)
787        } else {
788            (self.end, self.start)
789        }
790    }
791
792    /// Returns the DST offset.
793    fn offset(&self) -> Offset {
794        self.dst.offset
795    }
796}
797
798/// A parser for POSIX time zones.
799#[derive(#[automatically_derived]impl<'s> ::core::fmt::Debug for Parser<'s> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "Parser tz pos ianav3plus", &self.tz, &self.pos,
            &&self.ianav3plus)
    }
}Debug)]
800struct Parser<'s> {
801    /// The `TZ` string that we're parsing.
802    tz: &'s [u8],
803    /// The parser's current position in `tz`.
804    pos: core::cell::Cell<usize>,
805    /// Whether to use IANA rules, i.e., when parsing a TZ string in a TZif
806    /// file of version 3 or greater. From `tzfile(5)`:
807    ///
808    /// > First, the hours part of its transition times may be signed and range
809    /// > from `-167` through `167` instead of the POSIX-required unsigned
810    /// > values from `0` through `24`. Second, DST is in effect all year if
811    /// > it starts January 1 at 00:00 and ends December 31 at 24:00 plus the
812    /// > difference between daylight saving and standard time.
813    ///
814    /// At time of writing, I don't think I understand the significance of
815    /// the second part above. (RFC 8536 elaborates that it is meant to be an
816    /// explicit clarification of something that POSIX itself implies.) But the
817    /// first part is clear: it permits the hours to be a bigger range.
818    ianav3plus: bool,
819}
820
821impl<'s> Parser<'s> {
822    /// Create a new parser for extracting a POSIX time zone from the given
823    /// bytes.
824    fn new<B: ?Sized + AsRef<[u8]>>(tz: &'s B) -> Parser<'s> {
825        Parser {
826            tz: tz.as_ref(),
827            pos: core::cell::Cell::new(0),
828            ianav3plus: false,
829        }
830    }
831
832    /// Parses a POSIX time zone from the current position of the parser and
833    /// ensures that the entire TZ string corresponds to a single valid POSIX
834    /// time zone.
835    fn parse(&self) -> Result<TimeZone, ParseError> {
836        let (time_zone, len) = self.parse_prefix()?;
837        if !self.tz[len..].is_empty() {
838            return Err(ParseErrorKind::FoundRemaining.into());
839        }
840        Ok(time_zone)
841    }
842
843    /// Parses a POSIX time zone from the current position of the parser and
844    /// returns the remaining input.
845    fn parse_prefix(&self) -> Result<(TimeZone, usize), ParseError> {
846        let time_zone = self.parse_posix_time_zone()?;
847        Ok((time_zone, self.pos()))
848    }
849
850    /// Parse a POSIX time zone from the current position of the parser.
851    ///
852    /// Upon success, the parser will be positioned immediately following the
853    /// TZ string.
854    #[inline(never)] // avoid making multiple copies of the parser
855    fn parse_posix_time_zone(&self) -> Result<TimeZone, ParseError> {
856        if self.is_done() {
857            return Err(ParseErrorKind::Empty.into());
858        }
859        let std_abbrev = self
860            .parse_abbreviation()
861            .map_err(ParseErrorKind::AbbreviationStd)?;
862        let std_offset =
863            self.parse_posix_offset().map_err(ParseErrorKind::OffsetStd)?;
864        let mut dst = None;
865        if !self.is_done()
866            && (self.byte().is_ascii_alphabetic() || self.byte() == b'<')
867        {
868            dst = Some(self.parse_posix_dst(std_offset)?);
869        }
870        Ok(TimeZone { std_abbrev, std_offset, dst })
871    }
872
873    /// Parse a DST zone with an optional explicit transition rule.
874    ///
875    /// This assumes the parser is positioned at the first byte of the DST
876    /// abbreviation.
877    ///
878    /// Upon success, the parser will be positioned immediately after the end
879    /// of the DST transition rule (which might just be the abbreviation, but
880    /// might also include explicit start/end datetime specifications).
881    fn parse_posix_dst(&self, std_offset: Offset) -> Result<Dst, ParseError> {
882        let abbrev = self
883            .parse_abbreviation()
884            .map_err(ParseErrorKind::AbbreviationDst)?;
885        if self.is_done() {
886            return Err(ParseErrorKind::FoundDstNoRule.into());
887        }
888        // This is the default: one hour ahead of standard time. We may
889        // override this if the DST portion specifies an offset. (But it
890        // usually doesn't.)
891        //
892        // This unwrap is okay, but in a subtle way. We ensure that all PARSED
893        // offsets are 24:59:59 or less. But the maximum offset is 25:59:59.
894        // It was specifically setup that way so as to make this addition work.
895        let mut offset = std_offset.checked_add(3600).unwrap();
896        if self.byte() != b',' {
897            offset = self
898                .parse_posix_offset()
899                .map_err(ParseErrorKind::OffsetDst)?;
900            if self.is_done() {
901                return Err(ParseErrorKind::FoundDstNoRuleWithOffset.into());
902            }
903        }
904        if self.byte() != b',' {
905            return Err(ParseErrorKind::ExpectedCommaAfterDst.into());
906        }
907        if !self.bump() {
908            return Err(ParseErrorKind::FoundEndAfterComma.into());
909        }
910        let rule = self.parse_rule().map_err(ParseErrorKind::Rule)?;
911        Ok(Dst { abbrev, offset, rule })
912    }
913
914    /// Parse a time zone abbreviation.
915    ///
916    /// This assumes the parser is positioned at the first byte of
917    /// the abbreviation. This is either the first character in the
918    /// abbreviation, or the opening quote of a quoted abbreviation.
919    ///
920    /// Upon success, the parser will be positioned immediately following
921    /// the abbreviation name.
922    ///
923    /// The string returned is guaranteed to be no more than 30 bytes.
924    /// (This restriction is somewhat arbitrary, but it's so we can put
925    /// the abbreviation in a fixed capacity array.)
926    fn parse_abbreviation(&self) -> Result<Abbreviation, AbbreviationError> {
927        if self.byte() == b'<' {
928            if !self.bump() {
929                return Err(AbbreviationError::Quoted(
930                    QuotedAbbreviationError::UnexpectedEndAfterOpening,
931                ));
932            }
933            self.parse_quoted_abbreviation().map_err(AbbreviationError::Quoted)
934        } else {
935            self.parse_unquoted_abbreviation()
936                .map_err(AbbreviationError::Unquoted)
937        }
938    }
939
940    /// Parses an unquoted time zone abbreviation.
941    ///
942    /// This assumes the parser is position at the first byte in the
943    /// abbreviation.
944    ///
945    /// Upon success, the parser will be positioned immediately after the
946    /// last byte in the abbreviation.
947    ///
948    /// The string returned is guaranteed to be no more than 30 bytes.
949    /// (This restriction is somewhat arbitrary, but it's so we can put
950    /// the abbreviation in a fixed capacity array.)
951    fn parse_unquoted_abbreviation(
952        &self,
953    ) -> Result<Abbreviation, UnquotedAbbreviationError> {
954        let start = self.pos();
955        for _ in 0.. {
956            if !self.byte().is_ascii_alphabetic() {
957                break;
958            }
959            if self.pos() - start >= REASONABLE_ABBREVIATION_MAX {
960                return Err(UnquotedAbbreviationError::TooLong);
961            }
962            if !self.bump() {
963                break;
964            }
965        }
966        let end = self.pos();
967        let abbrev =
968            core::str::from_utf8(&self.tz[start..end]).map_err(|_| {
969                // NOTE: I believe this error is technically impossible
970                // since the loop above restricts letters in an
971                // abbreviation to ASCII. So everything from `start` to
972                // `end` is ASCII and thus should be UTF-8. But it doesn't
973                // cost us anything to report an error here in case the
974                // code above evolves somehow.
975                UnquotedAbbreviationError::InvalidUtf8
976            })?;
977        if abbrev.len() < 3 {
978            return Err(UnquotedAbbreviationError::TooShort);
979        }
980        Abbreviation::new(abbrev).ok_or(UnquotedAbbreviationError::TooLong)
981    }
982
983    /// Parses a quoted time zone abbreviation.
984    ///
985    /// This assumes the parser is positioned immediately after the opening
986    /// `<` quote. That is, at the first byte in the abbreviation.
987    ///
988    /// Upon success, the parser will be positioned immediately after the
989    /// closing `>` quote.
990    ///
991    /// The string returned is guaranteed to be no more than 30 bytes.
992    /// (This restriction is somewhat arbitrary, but it's so we can put
993    /// the abbreviation in a fixed capacity array.)
994    fn parse_quoted_abbreviation(
995        &self,
996    ) -> Result<Abbreviation, QuotedAbbreviationError> {
997        let start = self.pos();
998        for _ in 0.. {
999            if !self.byte().is_ascii_alphanumeric()
1000                && self.byte() != b'+'
1001                && self.byte() != b'-'
1002            {
1003                break;
1004            }
1005            if self.pos() - start >= REASONABLE_ABBREVIATION_MAX {
1006                return Err(QuotedAbbreviationError::TooLong);
1007            }
1008            if !self.bump() {
1009                break;
1010            }
1011        }
1012        let end = self.pos();
1013        let abbrev =
1014            core::str::from_utf8(&self.tz[start..end]).map_err(|_| {
1015                // NOTE: I believe this error is technically impossible
1016                // since the loop above restricts letters in an
1017                // abbreviation to ASCII. So everything from `start` to
1018                // `end` is ASCII and thus should be UTF-8. But it doesn't
1019                // cost us anything to report an error here in case the
1020                // code above evolves somehow.
1021                QuotedAbbreviationError::InvalidUtf8
1022            })?;
1023        if self.is_done() {
1024            return Err(QuotedAbbreviationError::UnexpectedEnd);
1025        }
1026        if self.byte() != b'>' {
1027            return Err(QuotedAbbreviationError::UnexpectedLastByte);
1028        }
1029        self.bump();
1030        if abbrev.len() < 3 {
1031            return Err(QuotedAbbreviationError::TooShort);
1032        }
1033        Abbreviation::new(abbrev).ok_or(QuotedAbbreviationError::TooLong)
1034    }
1035
1036    /// Parse a POSIX time offset.
1037    ///
1038    /// This assumes the parser is positioned at the first byte of the
1039    /// offset. This can either be a digit (for a positive offset) or the
1040    /// sign of the offset (which must be either `-` or `+`).
1041    ///
1042    /// Upon success, the parser will be positioned immediately after the
1043    /// end of the offset.
1044    fn parse_posix_offset(&self) -> Result<Offset, OffsetError> {
1045        let sign = self.parse_optional_sign()?.unwrap_or(1);
1046        let hour = self.parse_hour_posix()?;
1047        let (mut minute, mut second) = (0, 0);
1048        if self.maybe_byte() == Some(b':') {
1049            if !self.bump() {
1050                return Err(OffsetError::IncompleteMinutes);
1051            }
1052            minute = self.parse_minute()?;
1053            if self.maybe_byte() == Some(b':') {
1054                if !self.bump() {
1055                    return Err(OffsetError::IncompleteSeconds);
1056                }
1057                second = self.parse_second()?;
1058            }
1059        }
1060        let mut offset = Offset::from_hours(hour).expect("hours are valid");
1061        offset += i32::from(minute) * 60;
1062        offset += i32::from(second);
1063        // Yes, we flip the sign, because POSIX is backwards.
1064        // For example, `EST5` corresponds to `-05:00`.
1065        if sign.is_positive() {
1066            offset = -offset;
1067        }
1068        // Must be true because the parsing routines for hours, minutes
1069        // and seconds enforce they are in the ranges -24..=24, 0..=59
1070        // and 0..=59, respectively.
1071        if !(-89999 <= offset.seconds() && offset.seconds() <= 89999) {
    {
        ::core::panicking::panic_fmt(format_args!("POSIX offset seconds {0} is out of range",
                offset.seconds()));
    }
};assert!(
1072            -89999 <= offset.seconds() && offset.seconds() <= 89999,
1073            "POSIX offset seconds {} is out of range",
1074            offset.seconds(),
1075        );
1076        Ok(offset)
1077    }
1078
1079    /// Parses a POSIX DST transition rule.
1080    ///
1081    /// This assumes the parser is positioned at the first byte in the
1082    /// rule. That is, it comes immediately after the DST abbreviation or
1083    /// its optional offset.
1084    ///
1085    /// Upon success, the parser will be positioned immediately after the
1086    /// DST transition rule. In typical cases, this corresponds to the end
1087    /// of the TZ string.
1088    fn parse_rule(&self) -> Result<Rule, RuleError> {
1089        let start =
1090            self.parse_posix_datetime().map_err(RuleError::DateTimeStart)?;
1091        if self.maybe_byte() != Some(b',') || !self.bump() {
1092            return Err(RuleError::ExpectedEnd);
1093        }
1094        let end =
1095            self.parse_posix_datetime().map_err(RuleError::DateTimeEnd)?;
1096        Ok(Rule { start, end })
1097    }
1098
1099    /// Parses a POSIX datetime specification.
1100    ///
1101    /// This assumes the parser is position at the first byte where a
1102    /// datetime specification is expected to occur.
1103    ///
1104    /// Upon success, the parser will be positioned after the datetime
1105    /// specification. This will either be immediately after the date, or
1106    /// if it's present, the time part of the specification.
1107    fn parse_posix_datetime(&self) -> Result<DayTime, DateTimeError> {
1108        let mut daytime = DayTime {
1109            date: self.parse_posix_date()?,
1110            time: TransitionCivilTime::DEFAULT,
1111        };
1112        if self.maybe_byte() != Some(b'/') {
1113            return Ok(daytime);
1114        }
1115        if !self.bump() {
1116            return Err(DateTimeError::ExpectedTime);
1117        }
1118        daytime.time = self.parse_posix_time()?;
1119        Ok(daytime)
1120    }
1121
1122    /// Parses a POSIX date specification.
1123    ///
1124    /// This assumes the parser is positioned at the first byte of the date
1125    /// specification. This can be `J` (for one based Julian day without
1126    /// leap days), `M` (for "weekday of month") or a digit starting the
1127    /// zero based Julian day with leap days. This routine will validate
1128    /// that the position points to one of these possible values. That is,
1129    /// the caller doesn't need to parse the `M` or the `J` or the leading
1130    /// digit. The caller should just call this routine when it *expect* a
1131    /// date specification to follow.
1132    ///
1133    /// Upon success, the parser will be positioned immediately after the
1134    /// date specification.
1135    fn parse_posix_date(&self) -> Result<Day, DateError> {
1136        match self.byte() {
1137            b'J' => {
1138                if !self.bump() {
1139                    return Err(DateError::ExpectedJulianNoLeap);
1140                }
1141                Ok(Day::JulianOne(self.parse_posix_julian_day_no_leap()?))
1142            }
1143            b'0'..=b'9' => {
1144                Ok(Day::JulianZero(self.parse_posix_julian_day_with_leap()?))
1145            }
1146            b'M' => {
1147                if !self.bump() {
1148                    return Err(DateError::ExpectedMonthWeekWeekday);
1149                }
1150                let (month, week, weekday) = self.parse_weekday_of_month()?;
1151                Ok(Day::WeekdayOfMonth { month, week, weekday })
1152            }
1153            _ => Err(DateError::UnexpectedByte),
1154        }
1155    }
1156
1157    /// Parses a POSIX Julian day that does not include leap days
1158    /// (`1 <= n <= 365`).
1159    ///
1160    /// This assumes the parser is positioned just after the `J` and at the
1161    /// first digit of the Julian day. Upon success, the parser will be
1162    /// positioned immediately following the day number.
1163    fn parse_posix_julian_day_no_leap(
1164        &self,
1165    ) -> Result<i16, JulianNoLeapError> {
1166        let number = self
1167            .parse_number_with_upto_n_digits(3)
1168            .map_err(JulianNoLeapError::Parse)?;
1169        let number =
1170            i16::try_from(number).map_err(|_| JulianNoLeapError::Range)?;
1171        if !(1 <= number && number <= 365) {
1172            return Err(JulianNoLeapError::Range);
1173        }
1174        Ok(number)
1175    }
1176
1177    /// Parses a POSIX Julian day that includes leap days (`0 <= n <=
1178    /// 365`).
1179    ///
1180    /// This assumes the parser is positioned at the first digit of the
1181    /// Julian day. Upon success, the parser will be positioned immediately
1182    /// following the day number.
1183    fn parse_posix_julian_day_with_leap(
1184        &self,
1185    ) -> Result<i16, JulianLeapError> {
1186        let number = self
1187            .parse_number_with_upto_n_digits(3)
1188            .map_err(JulianLeapError::Parse)?;
1189        let number =
1190            i16::try_from(number).map_err(|_| JulianLeapError::Range)?;
1191        if !(0 <= number && number <= 365) {
1192            return Err(JulianLeapError::Range);
1193        }
1194        Ok(number)
1195    }
1196
1197    /// Parses a POSIX "weekday of month" specification.
1198    ///
1199    /// This assumes the parser is positioned just after the `M` byte and
1200    /// at the first digit of the month. Upon success, the parser will be
1201    /// positioned immediately following the "weekday of the month" that
1202    /// was parsed.
1203    ///
1204    /// The tuple returned is month (1..=12), week (1..=5) and weekday
1205    /// (0..=6 with 0=Sunday).
1206    fn parse_weekday_of_month(
1207        &self,
1208    ) -> Result<(i8, i8, Weekday), WeekdayOfMonthError> {
1209        let month = self.parse_month()?;
1210        if self.maybe_byte() != Some(b'.') {
1211            return Err(WeekdayOfMonthError::ExpectedDotAfterMonth);
1212        }
1213        if !self.bump() {
1214            return Err(WeekdayOfMonthError::ExpectedWeekAfterMonth);
1215        }
1216        let week = self.parse_week()?;
1217        if self.maybe_byte() != Some(b'.') {
1218            return Err(WeekdayOfMonthError::ExpectedDotAfterWeek);
1219        }
1220        if !self.bump() {
1221            return Err(WeekdayOfMonthError::ExpectedDayOfWeekAfterWeek);
1222        }
1223        let weekday = self.parse_weekday()?;
1224        Ok((month, week, weekday))
1225    }
1226
1227    /// This parses a POSIX time specification in the format
1228    /// `[+/-]hh?[:mm[:ss]]`.
1229    ///
1230    /// This assumes the parser is positioned at the first `h` (or the
1231    /// sign, if present). Upon success, the parser will be positioned
1232    /// immediately following the end of the time specification.
1233    fn parse_posix_time(&self) -> Result<TransitionCivilTime, TimeError> {
1234        let (sign, hour) = if self.ianav3plus {
1235            let sign = self.parse_optional_sign()?.unwrap_or(1);
1236            let hour = self.parse_hour_ianav3plus()?;
1237            (sign, hour)
1238        } else {
1239            (1, i16::from(self.parse_hour_posix()?))
1240        };
1241        let (mut minute, mut second) = (0, 0);
1242        if self.maybe_byte() == Some(b':') {
1243            if !self.bump() {
1244                return Err(TimeError::IncompleteMinutes);
1245            }
1246            minute = self.parse_minute()?;
1247            if self.maybe_byte() == Some(b':') {
1248                if !self.bump() {
1249                    return Err(TimeError::IncompleteSeconds);
1250                }
1251                second = self.parse_second()?;
1252            }
1253        }
1254        let mut time = TransitionCivilTime { second: i32::from(hour) * 3600 };
1255        time.second += i32::from(minute) * 60;
1256        time.second += i32::from(second);
1257        time.second *= i32::from(sign);
1258        // Must be true because the parsing routines for hours, minutes
1259        // and seconds enforce they are in the ranges -167..=167, 0..=59
1260        // and 0..=59, respectively.
1261        if !(-604799 <= time.second && time.second <= 604799) {
    {
        ::core::panicking::panic_fmt(format_args!("POSIX time seconds {0} is out of range",
                time.second));
    }
};assert!(
1262            -604799 <= time.second && time.second <= 604799,
1263            "POSIX time seconds {} is out of range",
1264            time.second
1265        );
1266        Ok(time)
1267    }
1268
1269    /// Parses a month.
1270    ///
1271    /// This is expected to be positioned at the first digit. Upon success,
1272    /// the parser will be positioned after the month (which may contain
1273    /// two digits).
1274    fn parse_month(&self) -> Result<i8, MonthError> {
1275        let number = self
1276            .parse_number_with_upto_n_digits(2)
1277            .map_err(MonthError::Parse)?;
1278        let number = i8::try_from(number).map_err(|_| MonthError::Range)?;
1279        if !(1 <= number && number <= 12) {
1280            return Err(MonthError::Range);
1281        }
1282        Ok(number)
1283    }
1284
1285    /// Parses a week-of-month number.
1286    ///
1287    /// This is expected to be positioned at the first digit. Upon success,
1288    /// the parser will be positioned after the week digit.
1289    fn parse_week(&self) -> Result<i8, WeekOfMonthError> {
1290        let number = self
1291            .parse_number_with_exactly_n_digits(1)
1292            .map_err(WeekOfMonthError::Parse)?;
1293        let number =
1294            i8::try_from(number).map_err(|_| WeekOfMonthError::Range)?;
1295        if !(1 <= number && number <= 5) {
1296            return Err(WeekOfMonthError::Range);
1297        }
1298        Ok(number)
1299    }
1300
1301    /// Parses a weekday number.
1302    ///
1303    /// This is expected to be positioned at the first digit. Upon success,
1304    /// the parser will be positioned after the week digit.
1305    ///
1306    /// The weekday returned is guaranteed to be in the range `0..=6`, with
1307    /// `0` corresponding to Sunday.
1308    fn parse_weekday(&self) -> Result<Weekday, WeekdayError> {
1309        let number = self
1310            .parse_number_with_exactly_n_digits(1)
1311            .map_err(WeekdayError::Parse)?;
1312        let number = i8::try_from(number).map_err(|_| WeekdayError::Range)?;
1313
1314        Weekday::from_sunday_zero_offset(number)
1315            .map_err(|_| WeekdayError::Range)
1316    }
1317
1318    /// Parses an hour from a POSIX time specification with the IANA
1319    /// v3+ extension. That is, the hour may be in the range `0..=167`.
1320    /// (Callers should parse an optional sign preceding the hour digits
1321    /// when IANA V3+ parsing is enabled.)
1322    ///
1323    /// The hour is allowed to be a single digit (unlike minutes or
1324    /// seconds).
1325    ///
1326    /// This assumes the parser is positioned at the position where the
1327    /// first hour digit should occur. Upon success, the parser will be
1328    /// positioned immediately after the last hour digit.
1329    fn parse_hour_ianav3plus(&self) -> Result<i16, HourIanaError> {
1330        // Callers should only be using this method when IANA v3+ parsing
1331        // is enabled.
1332        if !self.ianav3plus {
    ::core::panicking::panic("assertion failed: self.ianav3plus")
};assert!(self.ianav3plus);
1333        let number = self
1334            .parse_number_with_upto_n_digits(3)
1335            .map_err(HourIanaError::Parse)?;
1336        let number =
1337            i16::try_from(number).map_err(|_| HourIanaError::Range)?;
1338        if !(0 <= number && number <= 167) {
1339            // The error message says -167 but the check above uses 0.
1340            // This is because the caller is responsible for parsing
1341            // the sign.
1342            return Err(HourIanaError::Range);
1343        }
1344        Ok(number)
1345    }
1346
1347    /// Parses an hour from a POSIX time specification, with the allowed
1348    /// range being `0..=24`.
1349    ///
1350    /// The hour is allowed to be a single digit (unlike minutes or
1351    /// seconds).
1352    ///
1353    /// This assumes the parser is positioned at the position where the
1354    /// first hour digit should occur. Upon success, the parser will be
1355    /// positioned immediately after the last hour digit.
1356    fn parse_hour_posix(&self) -> Result<i8, HourPosixError> {
1357        let number = self
1358            .parse_number_with_upto_n_digits(2)
1359            .map_err(HourPosixError::Parse)?;
1360        let number =
1361            i8::try_from(number).map_err(|_| HourPosixError::Range)?;
1362        if !(0 <= number && number <= 24) {
1363            return Err(HourPosixError::Range);
1364        }
1365        Ok(number)
1366    }
1367
1368    /// Parses a minute from a POSIX time specification.
1369    ///
1370    /// The minute must be exactly two digits.
1371    ///
1372    /// This assumes the parser is positioned at the position where the
1373    /// first minute digit should occur. Upon success, the parser will be
1374    /// positioned immediately after the second minute digit.
1375    fn parse_minute(&self) -> Result<i8, MinuteError> {
1376        let number = self
1377            .parse_number_with_exactly_n_digits(2)
1378            .map_err(MinuteError::Parse)?;
1379        let number = i8::try_from(number).map_err(|_| MinuteError::Range)?;
1380        if !(0 <= number && number <= 59) {
1381            return Err(MinuteError::Range);
1382        }
1383        Ok(number)
1384    }
1385
1386    /// Parses a second from a POSIX time specification.
1387    ///
1388    /// The second must be exactly two digits.
1389    ///
1390    /// This assumes the parser is positioned at the position where the
1391    /// first second digit should occur. Upon success, the parser will be
1392    /// positioned immediately after the second second digit.
1393    fn parse_second(&self) -> Result<i8, SecondError> {
1394        let number = self
1395            .parse_number_with_exactly_n_digits(2)
1396            .map_err(SecondError::Parse)?;
1397        let number = i8::try_from(number).map_err(|_| SecondError::Range)?;
1398        if !(0 <= number && number <= 59) {
1399            return Err(SecondError::Range);
1400        }
1401        Ok(number)
1402    }
1403
1404    /// Parses a signed 64-bit integer expressed in exactly `n` digits.
1405    ///
1406    /// If `n` digits could not be found (or if the `TZ` string ends before
1407    /// `n` digits could be found), then this returns an error.
1408    ///
1409    /// This assumes that `n >= 1` and that the parser is positioned at the
1410    /// first digit. Upon success, the parser is positioned immediately
1411    /// after the `n`th digit.
1412    fn parse_number_with_exactly_n_digits(
1413        &self,
1414        n: usize,
1415    ) -> Result<i32, NumberError> {
1416        if !(n >= 1) {
    {
        ::core::panicking::panic_fmt(format_args!("numbers must have at least 1 digit"));
    }
};assert!(n >= 1, "numbers must have at least 1 digit");
1417        let mut number: i32 = 0;
1418        for _ in 0..n {
1419            if self.is_done() {
1420                return Err(NumberError::ExpectedLength);
1421            }
1422            let byte = self.byte();
1423            let digit = match byte.checked_sub(b'0') {
1424                None => {
1425                    return Err(NumberError::InvalidDigit);
1426                }
1427                Some(digit) if digit > 9 => {
1428                    return Err(NumberError::InvalidDigit);
1429                }
1430                Some(digit) => {
1431                    if true {
    if !(0..=9).contains(&digit) {
        ::core::panicking::panic("assertion failed: (0..=9).contains(&digit)")
    };
};debug_assert!((0..=9).contains(&digit));
1432                    i32::from(digit)
1433                }
1434            };
1435            number = number
1436                .checked_mul(10)
1437                .and_then(|n| n.checked_add(digit))
1438                .ok_or(NumberError::TooBig)?;
1439            self.bump();
1440        }
1441        Ok(number)
1442    }
1443
1444    /// Parses a signed 64-bit integer expressed with up to `n` digits and
1445    /// at least 1 digit.
1446    ///
1447    /// This assumes that `n >= 1` and that the parser is positioned at the
1448    /// first digit. Upon success, the parser is position immediately after
1449    /// the last digit (which can be at most `n`).
1450    fn parse_number_with_upto_n_digits(
1451        &self,
1452        n: usize,
1453    ) -> Result<i32, NumberError> {
1454        if !(n >= 1) {
    {
        ::core::panicking::panic_fmt(format_args!("numbers must have at least 1 digit"));
    }
};assert!(n >= 1, "numbers must have at least 1 digit");
1455        let mut number: i32 = 0;
1456        for i in 0..n {
1457            if self.is_done() || !self.byte().is_ascii_digit() {
1458                if i == 0 {
1459                    return Err(NumberError::Empty);
1460                }
1461                break;
1462            }
1463            let digit = i32::from(self.byte() - b'0');
1464            number = number
1465                .checked_mul(10)
1466                .and_then(|n| n.checked_add(digit))
1467                .ok_or(NumberError::TooBig)?;
1468            self.bump();
1469        }
1470        Ok(number)
1471    }
1472
1473    /// Parses an optional sign.
1474    ///
1475    /// This assumes the parser is positioned at the position where a
1476    /// positive or negative sign is permitted. If one exists, then it
1477    /// is consumed and returned. Moreover, if one exists, then this
1478    /// guarantees that it is not the last byte in the input. That is, upon
1479    /// success, it is valid to call `self.byte()`.
1480    fn parse_optional_sign(&self) -> Result<Option<i8>, OptionalSignError> {
1481        if self.is_done() {
1482            return Ok(None);
1483        }
1484        Ok(match self.byte() {
1485            b'-' => {
1486                if !self.bump() {
1487                    return Err(OptionalSignError::ExpectedDigitAfterMinus);
1488                }
1489                Some(-1)
1490            }
1491            b'+' => {
1492                if !self.bump() {
1493                    return Err(OptionalSignError::ExpectedDigitAfterPlus);
1494                }
1495                Some(1)
1496            }
1497            _ => None,
1498        })
1499    }
1500}
1501
1502/// Helper routines for parsing a POSIX `TZ` string.
1503impl<'s> Parser<'s> {
1504    /// Bump the parser to the next byte.
1505    ///
1506    /// If the end of the input has been reached, then `false` is returned.
1507    fn bump(&self) -> bool {
1508        if self.is_done() {
1509            return false;
1510        }
1511        self.pos.set(
1512            self.pos().checked_add(1).expect("pos cannot overflow usize"),
1513        );
1514        !self.is_done()
1515    }
1516
1517    /// Returns true if the next call to `bump` would return false.
1518    fn is_done(&self) -> bool {
1519        self.pos() == self.tz.len()
1520    }
1521
1522    /// Return the byte at the current position of the parser.
1523    ///
1524    /// This panics if the parser is positioned at the end of the TZ
1525    /// string.
1526    fn byte(&self) -> u8 {
1527        self.tz[self.pos()]
1528    }
1529
1530    /// Return the byte at the current position of the parser. If the TZ
1531    /// string has been exhausted, then this returns `None`.
1532    fn maybe_byte(&self) -> Option<u8> {
1533        self.tz.get(self.pos()).copied()
1534    }
1535
1536    /// Return the current byte offset of the parser.
1537    ///
1538    /// The offset starts at `0` from the beginning of the TZ string.
1539    fn pos(&self) -> usize {
1540        self.pos.get()
1541    }
1542}
1543
1544/// An error that can occur when parsing a POSIX time zone string.
1545#[derive(#[automatically_derived]impl ::core::clone::Clone for ParseError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        ParseError { kind: ::core::clone::Clone::clone(&self.kind) }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for ParseError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "ParseError kind", &&self.kind)
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for ParseError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<ParseErrorKind>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ParseError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ParseError {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.kind == other.kind }
}PartialEq)]
1546#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1547pub struct ParseError {
1548    kind: ParseErrorKind,
1549}
1550
1551impl ParseError {
1552    /// Returns true if parsing a POSIX time zone failed because a DST
1553    /// transition rule was missing.
1554    ///
1555    /// As of POSIX 2024, behavior is unspecified when a DST abbreviation is
1556    /// provided but a transition rule is omitted. In this case, Jiff chooses
1557    /// to return an error. Some POSIX implementations default to the US
1558    /// daylight saving time rules or even behave as if `TZ=posixrules` was
1559    /// set.
1560    ///
1561    /// Callers therefore might want to inspect when Jiff rejects a POSIX
1562    /// time zone because of a missing transition rule and do something
1563    /// different.
1564    pub fn is_missing_dst_transition_rule(&self) -> bool {
1565        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    ParseErrorKind::FoundDstNoRule | ParseErrorKind::FoundDstNoRuleWithOffset
        => true,
    _ => false,
}matches!(
1566            self.kind,
1567            ParseErrorKind::FoundDstNoRule
1568                | ParseErrorKind::FoundDstNoRuleWithOffset
1569        )
1570    }
1571}
1572
1573#[derive(#[automatically_derived]impl ::core::clone::Clone for ParseErrorKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::AbbreviationDst(__self_0) =>
                ParseErrorKind::AbbreviationDst(::core::clone::Clone::clone(__self_0)),
            Self::AbbreviationStd(__self_0) =>
                ParseErrorKind::AbbreviationStd(::core::clone::Clone::clone(__self_0)),
            Self::Empty => ParseErrorKind::Empty,
            Self::ExpectedCommaAfterDst =>
                ParseErrorKind::ExpectedCommaAfterDst,
            Self::FoundDstNoRule => ParseErrorKind::FoundDstNoRule,
            Self::FoundDstNoRuleWithOffset =>
                ParseErrorKind::FoundDstNoRuleWithOffset,
            Self::FoundEndAfterComma => ParseErrorKind::FoundEndAfterComma,
            Self::FoundRemaining => ParseErrorKind::FoundRemaining,
            Self::OffsetDst(__self_0) =>
                ParseErrorKind::OffsetDst(::core::clone::Clone::clone(__self_0)),
            Self::OffsetStd(__self_0) =>
                ParseErrorKind::OffsetStd(::core::clone::Clone::clone(__self_0)),
            Self::Rule(__self_0) =>
                ParseErrorKind::Rule(::core::clone::Clone::clone(__self_0)),
            Self::TzEnvColonTooBig => ParseErrorKind::TzEnvColonTooBig,
            Self::TzEnvColonInvalidUtf8 =>
                ParseErrorKind::TzEnvColonInvalidUtf8,
            Self::TzEnvInvalidUtf8 => ParseErrorKind::TzEnvInvalidUtf8,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for ParseErrorKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::AbbreviationDst(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "AbbreviationDst", &__self_0),
            Self::AbbreviationStd(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "AbbreviationStd", &__self_0),
            Self::Empty => ::core::fmt::Formatter::write_str(f, "Empty"),
            Self::ExpectedCommaAfterDst =>
                ::core::fmt::Formatter::write_str(f, "ExpectedCommaAfterDst"),
            Self::FoundDstNoRule =>
                ::core::fmt::Formatter::write_str(f, "FoundDstNoRule"),
            Self::FoundDstNoRuleWithOffset =>
                ::core::fmt::Formatter::write_str(f,
                    "FoundDstNoRuleWithOffset"),
            Self::FoundEndAfterComma =>
                ::core::fmt::Formatter::write_str(f, "FoundEndAfterComma"),
            Self::FoundRemaining =>
                ::core::fmt::Formatter::write_str(f, "FoundRemaining"),
            Self::OffsetDst(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OffsetDst", &__self_0),
            Self::OffsetStd(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OffsetStd", &__self_0),
            Self::Rule(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Rule",
                    &__self_0),
            Self::TzEnvColonTooBig =>
                ::core::fmt::Formatter::write_str(f, "TzEnvColonTooBig"),
            Self::TzEnvColonInvalidUtf8 =>
                ::core::fmt::Formatter::write_str(f, "TzEnvColonInvalidUtf8"),
            Self::TzEnvInvalidUtf8 =>
                ::core::fmt::Formatter::write_str(f, "TzEnvInvalidUtf8"),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for ParseErrorKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<AbbreviationError>;
        let _: ::core::cmp::AssertParamIsEq<OffsetError>;
        let _: ::core::cmp::AssertParamIsEq<RuleError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ParseErrorKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ParseErrorKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::AbbreviationDst(__self_0),
                    Self::AbbreviationDst(__arg1_0)) => __self_0 == __arg1_0,
                (Self::AbbreviationStd(__self_0),
                    Self::AbbreviationStd(__arg1_0)) => __self_0 == __arg1_0,
                (Self::OffsetDst(__self_0), Self::OffsetDst(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::OffsetStd(__self_0), Self::OffsetStd(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Rule(__self_0), Self::Rule(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
1574#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1575enum ParseErrorKind {
1576    AbbreviationDst(AbbreviationError),
1577    AbbreviationStd(AbbreviationError),
1578    Empty,
1579    ExpectedCommaAfterDst,
1580    FoundDstNoRule,
1581    FoundDstNoRuleWithOffset,
1582    FoundEndAfterComma,
1583    FoundRemaining,
1584    OffsetDst(OffsetError),
1585    OffsetStd(OffsetError),
1586    Rule(RuleError),
1587    TzEnvColonTooBig,
1588    TzEnvColonInvalidUtf8,
1589    #[allow(dead_code)] // not used when std is disabled
1590    TzEnvInvalidUtf8,
1591}
1592
1593impl core::fmt::Display for ParseError {
1594    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1595        use self::ParseErrorKind::*;
1596        match self.kind {
1597            AbbreviationDst(ref err) => {
1598                f.write_str("failed to parse DST time zone abbreviation: ")?;
1599                core::fmt::Display::fmt(err, f)
1600            }
1601            AbbreviationStd(ref err) => {
1602                f.write_str(
1603                    "failed to parse standard time zone abbreviation: ",
1604                )?;
1605                core::fmt::Display::fmt(err, f)
1606            }
1607            Empty => f.write_str(
1608                "an empty string is not a valid POSIX time zone \
1609                 transition rule",
1610            ),
1611            ExpectedCommaAfterDst => f.write_str(
1612                "expected `,` after parsing DST offset \
1613                 in POSIX time zone string",
1614            ),
1615            FoundDstNoRule => f.write_str(
1616                "found DST abbreviation in POSIX time zone string, \
1617                 but no transition rule \
1618                 (this is technically allowed by POSIX, but has \
1619                 unspecified behavior)",
1620            ),
1621            FoundDstNoRuleWithOffset => f.write_str(
1622                "found DST abbreviation and offset in POSIX time zone string, \
1623                 but no transition rule \
1624                 (this is technically allowed by POSIX, but has \
1625                 unspecified behavior)",
1626            ),
1627            FoundEndAfterComma => f.write_str(
1628                "after parsing DST offset in POSIX time zone string, \
1629                 found end of string after a trailing `,`",
1630            ),
1631            FoundRemaining => f.write_str(
1632                "expected entire POSIX TZ string to be a valid \
1633                 time zone transition rule, but found data after \
1634                 parsing a valid time zone transition rule",
1635            ),
1636            OffsetDst(ref err) => {
1637                f.write_str("failed to parse DST offset: ")?;
1638                core::fmt::Display::fmt(err, f)
1639            }
1640            OffsetStd(ref err) => {
1641                f.write_str("failed to parse standard offset: ")?;
1642                core::fmt::Display::fmt(err, f)
1643            }
1644            Rule(ref err) => core::fmt::Display::fmt(err, f),
1645            TzEnvColonTooBig => {
1646                f.write_str(
1647                    "IANA time zone identifier is too big for core-only \
1648                     environments \
1649                     (must be less than or equal to ",
1650                )?;
1651                core::fmt::Display::fmt(&TimeZoneId::array_capacity_max(), f)?;
1652                f.write_str(" bytes)")
1653            }
1654            TzEnvColonInvalidUtf8 => {
1655                f.write_str("IANA time zone identifier is invalid UTF-8")
1656            }
1657            TzEnvInvalidUtf8 => f.write_str(
1658                "POSIX transition rule or \
1659                 IANA time zone identifier is invalid UTF-8",
1660            ),
1661        }
1662    }
1663}
1664
1665impl From<ParseErrorKind> for ParseError {
1666    fn from(kind: ParseErrorKind) -> ParseError {
1667        ParseError { kind }
1668    }
1669}
1670
1671#[derive(#[automatically_derived]impl ::core::clone::Clone for OffsetError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::HourPosix(__self_0) =>
                OffsetError::HourPosix(::core::clone::Clone::clone(__self_0)),
            Self::IncompleteMinutes => OffsetError::IncompleteMinutes,
            Self::IncompleteSeconds => OffsetError::IncompleteSeconds,
            Self::Minute(__self_0) =>
                OffsetError::Minute(::core::clone::Clone::clone(__self_0)),
            Self::OptionalSign(__self_0) =>
                OffsetError::OptionalSign(::core::clone::Clone::clone(__self_0)),
            Self::Second(__self_0) =>
                OffsetError::Second(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for OffsetError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::HourPosix(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "HourPosix", &__self_0),
            Self::IncompleteMinutes =>
                ::core::fmt::Formatter::write_str(f, "IncompleteMinutes"),
            Self::IncompleteSeconds =>
                ::core::fmt::Formatter::write_str(f, "IncompleteSeconds"),
            Self::Minute(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Minute", &__self_0),
            Self::OptionalSign(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OptionalSign", &__self_0),
            Self::Second(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Second", &__self_0),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for OffsetError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<HourPosixError>;
        let _: ::core::cmp::AssertParamIsEq<MinuteError>;
        let _: ::core::cmp::AssertParamIsEq<OptionalSignError>;
        let _: ::core::cmp::AssertParamIsEq<SecondError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    OffsetError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for OffsetError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::HourPosix(__self_0), Self::HourPosix(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Minute(__self_0), Self::Minute(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::OptionalSign(__self_0), Self::OptionalSign(__arg1_0))
                    => __self_0 == __arg1_0,
                (Self::Second(__self_0), Self::Second(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
1672#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1673enum OffsetError {
1674    HourPosix(HourPosixError),
1675    IncompleteMinutes,
1676    IncompleteSeconds,
1677    Minute(MinuteError),
1678    OptionalSign(OptionalSignError),
1679    Second(SecondError),
1680}
1681
1682impl core::fmt::Display for OffsetError {
1683    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1684        use self::OffsetError::*;
1685        match *self {
1686            HourPosix(ref err) => core::fmt::Display::fmt(err, f),
1687            IncompleteMinutes => f.write_str(
1688                "incomplete time in \
1689                 POSIX time zone string (missing minutes)",
1690            ),
1691            IncompleteSeconds => f.write_str(
1692                "incomplete time in \
1693                 POSIX time zone string (missing seconds)",
1694            ),
1695            Minute(ref err) => core::fmt::Display::fmt(err, f),
1696            Second(ref err) => core::fmt::Display::fmt(err, f),
1697            OptionalSign(ref err) => {
1698                f.write_str(
1699                    "failed to parse sign for time offset \
1700                     POSIX time zone string",
1701                )?;
1702                core::fmt::Display::fmt(err, f)
1703            }
1704        }
1705    }
1706}
1707
1708impl From<HourPosixError> for OffsetError {
1709    fn from(err: HourPosixError) -> OffsetError {
1710        OffsetError::HourPosix(err)
1711    }
1712}
1713
1714impl From<MinuteError> for OffsetError {
1715    fn from(err: MinuteError) -> OffsetError {
1716        OffsetError::Minute(err)
1717    }
1718}
1719
1720impl From<OptionalSignError> for OffsetError {
1721    fn from(err: OptionalSignError) -> OffsetError {
1722        OffsetError::OptionalSign(err)
1723    }
1724}
1725
1726impl From<SecondError> for OffsetError {
1727    fn from(err: SecondError) -> OffsetError {
1728        OffsetError::Second(err)
1729    }
1730}
1731
1732#[derive(#[automatically_derived]impl ::core::clone::Clone for RuleError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::DateTimeEnd(__self_0) =>
                RuleError::DateTimeEnd(::core::clone::Clone::clone(__self_0)),
            Self::DateTimeStart(__self_0) =>
                RuleError::DateTimeStart(::core::clone::Clone::clone(__self_0)),
            Self::ExpectedEnd => RuleError::ExpectedEnd,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for RuleError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::DateTimeEnd(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "DateTimeEnd", &__self_0),
            Self::DateTimeStart(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "DateTimeStart", &__self_0),
            Self::ExpectedEnd =>
                ::core::fmt::Formatter::write_str(f, "ExpectedEnd"),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for RuleError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DateTimeError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for RuleError
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for RuleError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::DateTimeEnd(__self_0), Self::DateTimeEnd(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::DateTimeStart(__self_0), Self::DateTimeStart(__arg1_0))
                    => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
1733#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1734enum RuleError {
1735    DateTimeEnd(DateTimeError),
1736    DateTimeStart(DateTimeError),
1737    ExpectedEnd,
1738}
1739
1740impl core::fmt::Display for RuleError {
1741    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1742        use self::RuleError::*;
1743        match *self {
1744            DateTimeEnd(ref err) => {
1745                f.write_str("failed to parse end of DST transition rule: ")?;
1746                core::fmt::Display::fmt(err, f)
1747            }
1748            DateTimeStart(ref err) => {
1749                f.write_str("failed to parse start of DST transition rule: ")?;
1750                core::fmt::Display::fmt(err, f)
1751            }
1752            ExpectedEnd => f.write_str(
1753                "expected end of DST rule after parsing the start \
1754                 of the DST rule",
1755            ),
1756        }
1757    }
1758}
1759
1760#[derive(#[automatically_derived]impl ::core::clone::Clone for DateTimeError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Date(__self_0) =>
                DateTimeError::Date(::core::clone::Clone::clone(__self_0)),
            Self::ExpectedTime => DateTimeError::ExpectedTime,
            Self::Time(__self_0) =>
                DateTimeError::Time(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for DateTimeError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Date(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Date",
                    &__self_0),
            Self::ExpectedTime =>
                ::core::fmt::Formatter::write_str(f, "ExpectedTime"),
            Self::Time(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Time",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for DateTimeError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DateError>;
        let _: ::core::cmp::AssertParamIsEq<TimeError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    DateTimeError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for DateTimeError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Date(__self_0), Self::Date(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Time(__self_0), Self::Time(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
1761#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1762enum DateTimeError {
1763    Date(DateError),
1764    ExpectedTime,
1765    Time(TimeError),
1766}
1767
1768impl core::fmt::Display for DateTimeError {
1769    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1770        use self::DateTimeError::*;
1771        match *self {
1772            Date(ref err) => core::fmt::Display::fmt(err, f),
1773            ExpectedTime => f.write_str(
1774                "expected time specification after `/` following a date
1775                 specification in a POSIX time zone DST transition rule",
1776            ),
1777            Time(ref err) => core::fmt::Display::fmt(err, f),
1778        }
1779    }
1780}
1781
1782impl From<DateError> for DateTimeError {
1783    fn from(err: DateError) -> DateTimeError {
1784        DateTimeError::Date(err)
1785    }
1786}
1787
1788impl From<TimeError> for DateTimeError {
1789    fn from(err: TimeError) -> DateTimeError {
1790        DateTimeError::Time(err)
1791    }
1792}
1793
1794#[derive(#[automatically_derived]impl ::core::clone::Clone for DateError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::ExpectedJulianNoLeap => DateError::ExpectedJulianNoLeap,
            Self::ExpectedMonthWeekWeekday =>
                DateError::ExpectedMonthWeekWeekday,
            Self::JulianLeap(__self_0) =>
                DateError::JulianLeap(::core::clone::Clone::clone(__self_0)),
            Self::JulianNoLeap(__self_0) =>
                DateError::JulianNoLeap(::core::clone::Clone::clone(__self_0)),
            Self::UnexpectedByte => DateError::UnexpectedByte,
            Self::WeekdayOfMonth(__self_0) =>
                DateError::WeekdayOfMonth(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for DateError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::ExpectedJulianNoLeap =>
                ::core::fmt::Formatter::write_str(f, "ExpectedJulianNoLeap"),
            Self::ExpectedMonthWeekWeekday =>
                ::core::fmt::Formatter::write_str(f,
                    "ExpectedMonthWeekWeekday"),
            Self::JulianLeap(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "JulianLeap", &__self_0),
            Self::JulianNoLeap(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "JulianNoLeap", &__self_0),
            Self::UnexpectedByte =>
                ::core::fmt::Formatter::write_str(f, "UnexpectedByte"),
            Self::WeekdayOfMonth(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "WeekdayOfMonth", &__self_0),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for DateError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<JulianLeapError>;
        let _: ::core::cmp::AssertParamIsEq<JulianNoLeapError>;
        let _: ::core::cmp::AssertParamIsEq<WeekdayOfMonthError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for DateError
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for DateError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::JulianLeap(__self_0), Self::JulianLeap(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::JulianNoLeap(__self_0), Self::JulianNoLeap(__arg1_0))
                    => __self_0 == __arg1_0,
                (Self::WeekdayOfMonth(__self_0),
                    Self::WeekdayOfMonth(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
1795#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1796enum DateError {
1797    ExpectedJulianNoLeap,
1798    ExpectedMonthWeekWeekday,
1799    JulianLeap(JulianLeapError),
1800    JulianNoLeap(JulianNoLeapError),
1801    UnexpectedByte,
1802    WeekdayOfMonth(WeekdayOfMonthError),
1803}
1804
1805impl core::fmt::Display for DateError {
1806    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1807        use self::DateError::*;
1808        match *self {
1809            ExpectedJulianNoLeap => f.write_str(
1810                "expected one-based Julian day after `J` in date \
1811                 specification of a POSIX time zone DST \
1812                 transition rule, but found the end of input",
1813            ),
1814            ExpectedMonthWeekWeekday => f.write_str(
1815                "expected month-week-weekday after `M` in date \
1816                 specification of a POSIX time zone DST \
1817                 transition rule, but found the end of input",
1818            ),
1819            JulianLeap(ref err) => core::fmt::Display::fmt(err, f),
1820            JulianNoLeap(ref err) => core::fmt::Display::fmt(err, f),
1821            UnexpectedByte => f.write_str(
1822                "expected `J`, a digit or `M` at the beginning of a date \
1823                 specification of a POSIX time zone DST transition rule",
1824            ),
1825            WeekdayOfMonth(ref err) => core::fmt::Display::fmt(err, f),
1826        }
1827    }
1828}
1829
1830impl From<JulianLeapError> for DateError {
1831    fn from(err: JulianLeapError) -> DateError {
1832        DateError::JulianLeap(err)
1833    }
1834}
1835
1836impl From<JulianNoLeapError> for DateError {
1837    fn from(err: JulianNoLeapError) -> DateError {
1838        DateError::JulianNoLeap(err)
1839    }
1840}
1841
1842impl From<WeekdayOfMonthError> for DateError {
1843    fn from(err: WeekdayOfMonthError) -> DateError {
1844        DateError::WeekdayOfMonth(err)
1845    }
1846}
1847
1848#[derive(#[automatically_derived]impl ::core::clone::Clone for JulianNoLeapError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Parse(__self_0) =>
                JulianNoLeapError::Parse(::core::clone::Clone::clone(__self_0)),
            Self::Range => JulianNoLeapError::Range,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for JulianNoLeapError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Parse(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Parse",
                    &__self_0),
            Self::Range => ::core::fmt::Formatter::write_str(f, "Range"),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for JulianNoLeapError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NumberError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    JulianNoLeapError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for JulianNoLeapError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Parse(__self_0), Self::Parse(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
1849#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1850enum JulianNoLeapError {
1851    Parse(NumberError),
1852    Range,
1853}
1854
1855impl core::fmt::Display for JulianNoLeapError {
1856    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1857        use self::JulianNoLeapError::*;
1858        match *self {
1859            Parse(ref err) => {
1860                f.write_str("invalid one-based Julian day digits: ")?;
1861                core::fmt::Display::fmt(err, f)
1862            }
1863            Range => f.write_str(
1864                "parsed one-based Julian day, but it's not in supported \
1865                 range of `1..=365`",
1866            ),
1867        }
1868    }
1869}
1870
1871#[derive(#[automatically_derived]impl ::core::clone::Clone for JulianLeapError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Parse(__self_0) =>
                JulianLeapError::Parse(::core::clone::Clone::clone(__self_0)),
            Self::Range => JulianLeapError::Range,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for JulianLeapError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Parse(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Parse",
                    &__self_0),
            Self::Range => ::core::fmt::Formatter::write_str(f, "Range"),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for JulianLeapError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NumberError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    JulianLeapError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for JulianLeapError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Parse(__self_0), Self::Parse(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
1872#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1873enum JulianLeapError {
1874    Parse(NumberError),
1875    Range,
1876}
1877
1878impl core::fmt::Display for JulianLeapError {
1879    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1880        use self::JulianLeapError::*;
1881        match *self {
1882            Parse(ref err) => {
1883                f.write_str("invalid zero-based Julian day digits: ")?;
1884                core::fmt::Display::fmt(err, f)
1885            }
1886            Range => f.write_str(
1887                "parsed zero-based Julian day, but it's not in supported \
1888                 range of `0..=365`",
1889            ),
1890        }
1891    }
1892}
1893
1894#[derive(#[automatically_derived]impl ::core::clone::Clone for AbbreviationError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Quoted(__self_0) =>
                AbbreviationError::Quoted(::core::clone::Clone::clone(__self_0)),
            Self::Unquoted(__self_0) =>
                AbbreviationError::Unquoted(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for AbbreviationError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Quoted(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Quoted", &__self_0),
            Self::Unquoted(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Unquoted", &__self_0),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for AbbreviationError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<QuotedAbbreviationError>;
        let _: ::core::cmp::AssertParamIsEq<UnquotedAbbreviationError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    AbbreviationError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for AbbreviationError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Quoted(__self_0), Self::Quoted(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Unquoted(__self_0), Self::Unquoted(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq)]
1895#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1896enum AbbreviationError {
1897    Quoted(QuotedAbbreviationError),
1898    Unquoted(UnquotedAbbreviationError),
1899}
1900
1901impl core::fmt::Display for AbbreviationError {
1902    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1903        use self::AbbreviationError::*;
1904        match *self {
1905            Quoted(ref err) => core::fmt::Display::fmt(err, f),
1906            Unquoted(ref err) => core::fmt::Display::fmt(err, f),
1907        }
1908    }
1909}
1910
1911#[derive(#[automatically_derived]impl ::core::clone::Clone for
    UnquotedAbbreviationError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::InvalidUtf8 => UnquotedAbbreviationError::InvalidUtf8,
            Self::TooLong => UnquotedAbbreviationError::TooLong,
            Self::TooShort => UnquotedAbbreviationError::TooShort,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for UnquotedAbbreviationError
    {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                UnquotedAbbreviationError::InvalidUtf8 => "InvalidUtf8",
                UnquotedAbbreviationError::TooLong => "TooLong",
                UnquotedAbbreviationError::TooShort => "TooShort",
            })
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for UnquotedAbbreviationError { }Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    UnquotedAbbreviationError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for
    UnquotedAbbreviationError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
1912#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1913enum UnquotedAbbreviationError {
1914    InvalidUtf8,
1915    TooLong,
1916    TooShort,
1917}
1918
1919impl core::fmt::Display for UnquotedAbbreviationError {
1920    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1921        use self::UnquotedAbbreviationError::*;
1922        match *self {
1923            InvalidUtf8 => f.write_str(
1924                "unquoted time zone abbreviation must be valid UTF-8",
1925            ),
1926            TooLong => f.write_fmt(format_args!("expected unquoted time zone abbreviation with at most {0} bytes, but found an abbreviation that is longer",
        REASONABLE_ABBREVIATION_MAX))write!(
1927                f,
1928                "expected unquoted time zone abbreviation with at most \
1929                 {} bytes, but found an abbreviation that is longer",
1930                REASONABLE_ABBREVIATION_MAX,
1931            ),
1932            TooShort => f.write_str(
1933                "expected unquoted time zone abbreviation to have length of \
1934                 3 or more bytes, but an abbreviation that is shorter",
1935            ),
1936        }
1937    }
1938}
1939
1940#[derive(#[automatically_derived]impl ::core::clone::Clone for QuotedAbbreviationError
    {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::InvalidUtf8 => QuotedAbbreviationError::InvalidUtf8,
            Self::TooLong => QuotedAbbreviationError::TooLong,
            Self::TooShort => QuotedAbbreviationError::TooShort,
            Self::UnexpectedEnd => QuotedAbbreviationError::UnexpectedEnd,
            Self::UnexpectedEndAfterOpening =>
                QuotedAbbreviationError::UnexpectedEndAfterOpening,
            Self::UnexpectedLastByte =>
                QuotedAbbreviationError::UnexpectedLastByte,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for QuotedAbbreviationError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "InvalidUtf8 TooLong TooShort UnexpectedEnd UnexpectedEndAfterOpening UnexpectedLastByte",
            match self {
                QuotedAbbreviationError::InvalidUtf8 => 0usize,
                QuotedAbbreviationError::TooLong => 12usize,
                QuotedAbbreviationError::TooShort => 20usize,
                QuotedAbbreviationError::UnexpectedEnd => 29usize,
                QuotedAbbreviationError::UnexpectedEndAfterOpening => 43usize,
                QuotedAbbreviationError::UnexpectedLastByte => 69usize,
            })
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for QuotedAbbreviationError { }Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    QuotedAbbreviationError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for
    QuotedAbbreviationError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
1941#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1942enum QuotedAbbreviationError {
1943    InvalidUtf8,
1944    TooLong,
1945    TooShort,
1946    UnexpectedEnd,
1947    UnexpectedEndAfterOpening,
1948    UnexpectedLastByte,
1949}
1950
1951impl core::fmt::Display for QuotedAbbreviationError {
1952    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1953        use self::QuotedAbbreviationError::*;
1954        match *self {
1955            InvalidUtf8 => f.write_str(
1956                "quoted time zone abbreviation must be valid UTF-8",
1957            ),
1958            TooLong => f.write_fmt(format_args!("expected quoted time zone abbreviation with at most {0} bytes, but found an abbreviation that is longer",
        REASONABLE_ABBREVIATION_MAX))write!(
1959                f,
1960                "expected quoted time zone abbreviation with at most \
1961                 {} bytes, but found an abbreviation that is longer",
1962                REASONABLE_ABBREVIATION_MAX,
1963            ),
1964            TooShort => f.write_str(
1965                "expected quoted time zone abbreviation to have length of \
1966                 3 or more bytes, but an abbreviation that is shorter",
1967            ),
1968            UnexpectedEnd => f.write_str(
1969                "found non-empty quoted time zone abbreviation, but \
1970                 found end of input before an end-of-quoted abbreviation \
1971                 `>` character",
1972            ),
1973            UnexpectedEndAfterOpening => f.write_str(
1974                "found opening `<` quote for time zone abbreviation in \
1975                 POSIX time zone transition rule, and expected a name \
1976                 following it, but found the end of input instead",
1977            ),
1978            UnexpectedLastByte => f.write_str(
1979                "found non-empty quoted time zone abbreviation, but \
1980                 found did not find end-of-quoted abbreviation `>` \
1981                 character",
1982            ),
1983        }
1984    }
1985}
1986
1987#[derive(#[automatically_derived]impl ::core::clone::Clone for WeekdayOfMonthError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::ExpectedDayOfWeekAfterWeek =>
                WeekdayOfMonthError::ExpectedDayOfWeekAfterWeek,
            Self::ExpectedDotAfterMonth =>
                WeekdayOfMonthError::ExpectedDotAfterMonth,
            Self::ExpectedDotAfterWeek =>
                WeekdayOfMonthError::ExpectedDotAfterWeek,
            Self::ExpectedWeekAfterMonth =>
                WeekdayOfMonthError::ExpectedWeekAfterMonth,
            Self::Month(__self_0) =>
                WeekdayOfMonthError::Month(::core::clone::Clone::clone(__self_0)),
            Self::WeekOfMonth(__self_0) =>
                WeekdayOfMonthError::WeekOfMonth(::core::clone::Clone::clone(__self_0)),
            Self::Weekday(__self_0) =>
                WeekdayOfMonthError::Weekday(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for WeekdayOfMonthError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::ExpectedDayOfWeekAfterWeek =>
                ::core::fmt::Formatter::write_str(f,
                    "ExpectedDayOfWeekAfterWeek"),
            Self::ExpectedDotAfterMonth =>
                ::core::fmt::Formatter::write_str(f, "ExpectedDotAfterMonth"),
            Self::ExpectedDotAfterWeek =>
                ::core::fmt::Formatter::write_str(f, "ExpectedDotAfterWeek"),
            Self::ExpectedWeekAfterMonth =>
                ::core::fmt::Formatter::write_str(f,
                    "ExpectedWeekAfterMonth"),
            Self::Month(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Month",
                    &__self_0),
            Self::WeekOfMonth(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "WeekOfMonth", &__self_0),
            Self::Weekday(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Weekday", &__self_0),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for WeekdayOfMonthError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<MonthError>;
        let _: ::core::cmp::AssertParamIsEq<WeekOfMonthError>;
        let _: ::core::cmp::AssertParamIsEq<WeekdayError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    WeekdayOfMonthError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for WeekdayOfMonthError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Month(__self_0), Self::Month(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::WeekOfMonth(__self_0), Self::WeekOfMonth(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Weekday(__self_0), Self::Weekday(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
1988#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1989enum WeekdayOfMonthError {
1990    ExpectedDayOfWeekAfterWeek,
1991    ExpectedDotAfterMonth,
1992    ExpectedDotAfterWeek,
1993    ExpectedWeekAfterMonth,
1994    Month(MonthError),
1995    WeekOfMonth(WeekOfMonthError),
1996    Weekday(WeekdayError),
1997}
1998
1999impl core::fmt::Display for WeekdayOfMonthError {
2000    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2001        use self::WeekdayOfMonthError::*;
2002        match *self {
2003            ExpectedDayOfWeekAfterWeek => f.write_str(
2004                "expected day-of-week after week in POSIX time zone rule",
2005            ),
2006            ExpectedDotAfterMonth => {
2007                f.write_str("expected `.` after month in POSIX time zone rule")
2008            }
2009            ExpectedWeekAfterMonth => f.write_str(
2010                "expected week after month in POSIX time zone rule",
2011            ),
2012            ExpectedDotAfterWeek => {
2013                f.write_str("expected `.` after week in POSIX time zone rule")
2014            }
2015            Month(ref err) => core::fmt::Display::fmt(err, f),
2016            WeekOfMonth(ref err) => core::fmt::Display::fmt(err, f),
2017            Weekday(ref err) => core::fmt::Display::fmt(err, f),
2018        }
2019    }
2020}
2021
2022impl From<MonthError> for WeekdayOfMonthError {
2023    fn from(err: MonthError) -> WeekdayOfMonthError {
2024        WeekdayOfMonthError::Month(err)
2025    }
2026}
2027
2028impl From<WeekOfMonthError> for WeekdayOfMonthError {
2029    fn from(err: WeekOfMonthError) -> WeekdayOfMonthError {
2030        WeekdayOfMonthError::WeekOfMonth(err)
2031    }
2032}
2033
2034impl From<WeekdayError> for WeekdayOfMonthError {
2035    fn from(err: WeekdayError) -> WeekdayOfMonthError {
2036        WeekdayOfMonthError::Weekday(err)
2037    }
2038}
2039
2040#[derive(#[automatically_derived]impl ::core::clone::Clone for TimeError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::HourIana(__self_0) =>
                TimeError::HourIana(::core::clone::Clone::clone(__self_0)),
            Self::HourPosix(__self_0) =>
                TimeError::HourPosix(::core::clone::Clone::clone(__self_0)),
            Self::IncompleteMinutes => TimeError::IncompleteMinutes,
            Self::IncompleteSeconds => TimeError::IncompleteSeconds,
            Self::Minute(__self_0) =>
                TimeError::Minute(::core::clone::Clone::clone(__self_0)),
            Self::OptionalSign(__self_0) =>
                TimeError::OptionalSign(::core::clone::Clone::clone(__self_0)),
            Self::Second(__self_0) =>
                TimeError::Second(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for TimeError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::HourIana(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "HourIana", &__self_0),
            Self::HourPosix(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "HourPosix", &__self_0),
            Self::IncompleteMinutes =>
                ::core::fmt::Formatter::write_str(f, "IncompleteMinutes"),
            Self::IncompleteSeconds =>
                ::core::fmt::Formatter::write_str(f, "IncompleteSeconds"),
            Self::Minute(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Minute", &__self_0),
            Self::OptionalSign(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OptionalSign", &__self_0),
            Self::Second(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Second", &__self_0),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for TimeError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<HourIanaError>;
        let _: ::core::cmp::AssertParamIsEq<HourPosixError>;
        let _: ::core::cmp::AssertParamIsEq<MinuteError>;
        let _: ::core::cmp::AssertParamIsEq<OptionalSignError>;
        let _: ::core::cmp::AssertParamIsEq<SecondError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for TimeError
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for TimeError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::HourIana(__self_0), Self::HourIana(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::HourPosix(__self_0), Self::HourPosix(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Minute(__self_0), Self::Minute(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::OptionalSign(__self_0), Self::OptionalSign(__arg1_0))
                    => __self_0 == __arg1_0,
                (Self::Second(__self_0), Self::Second(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
2041#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2042enum TimeError {
2043    HourIana(HourIanaError),
2044    HourPosix(HourPosixError),
2045    IncompleteMinutes,
2046    IncompleteSeconds,
2047    Minute(MinuteError),
2048    OptionalSign(OptionalSignError),
2049    Second(SecondError),
2050}
2051
2052impl core::fmt::Display for TimeError {
2053    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2054        use self::TimeError::*;
2055        match *self {
2056            HourIana(ref err) => core::fmt::Display::fmt(err, f),
2057            HourPosix(ref err) => core::fmt::Display::fmt(err, f),
2058            IncompleteMinutes => f.write_str(
2059                "incomplete time zone transition time in \
2060                 POSIX time zone string (missing minutes)",
2061            ),
2062            IncompleteSeconds => f.write_str(
2063                "incomplete time zone transition time in \
2064                 POSIX time zone string (missing seconds)",
2065            ),
2066            Minute(ref err) => core::fmt::Display::fmt(err, f),
2067            Second(ref err) => core::fmt::Display::fmt(err, f),
2068            OptionalSign(ref err) => {
2069                f.write_str(
2070                    "failed to parse sign for time zone transition time",
2071                )?;
2072                core::fmt::Display::fmt(err, f)
2073            }
2074        }
2075    }
2076}
2077
2078impl From<HourIanaError> for TimeError {
2079    fn from(err: HourIanaError) -> TimeError {
2080        TimeError::HourIana(err)
2081    }
2082}
2083
2084impl From<HourPosixError> for TimeError {
2085    fn from(err: HourPosixError) -> TimeError {
2086        TimeError::HourPosix(err)
2087    }
2088}
2089
2090impl From<MinuteError> for TimeError {
2091    fn from(err: MinuteError) -> TimeError {
2092        TimeError::Minute(err)
2093    }
2094}
2095
2096impl From<OptionalSignError> for TimeError {
2097    fn from(err: OptionalSignError) -> TimeError {
2098        TimeError::OptionalSign(err)
2099    }
2100}
2101
2102impl From<SecondError> for TimeError {
2103    fn from(err: SecondError) -> TimeError {
2104        TimeError::Second(err)
2105    }
2106}
2107
2108#[derive(#[automatically_derived]impl ::core::clone::Clone for MonthError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Parse(__self_0) =>
                MonthError::Parse(::core::clone::Clone::clone(__self_0)),
            Self::Range => MonthError::Range,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for MonthError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Parse(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Parse",
                    &__self_0),
            Self::Range => ::core::fmt::Formatter::write_str(f, "Range"),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for MonthError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NumberError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    MonthError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for MonthError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Parse(__self_0), Self::Parse(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
2109#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2110enum MonthError {
2111    Parse(NumberError),
2112    Range,
2113}
2114
2115impl core::fmt::Display for MonthError {
2116    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2117        use self::MonthError::*;
2118        match *self {
2119            Parse(ref err) => {
2120                f.write_str("invalid month digits: ")?;
2121                core::fmt::Display::fmt(err, f)
2122            }
2123            Range => f.write_str(
2124                "parsed month, but it's not in supported \
2125                 range of `1..=12`",
2126            ),
2127        }
2128    }
2129}
2130
2131#[derive(#[automatically_derived]impl ::core::clone::Clone for WeekOfMonthError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Parse(__self_0) =>
                WeekOfMonthError::Parse(::core::clone::Clone::clone(__self_0)),
            Self::Range => WeekOfMonthError::Range,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for WeekOfMonthError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Parse(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Parse",
                    &__self_0),
            Self::Range => ::core::fmt::Formatter::write_str(f, "Range"),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for WeekOfMonthError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NumberError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    WeekOfMonthError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for WeekOfMonthError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Parse(__self_0), Self::Parse(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
2132#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2133enum WeekOfMonthError {
2134    Parse(NumberError),
2135    Range,
2136}
2137
2138impl core::fmt::Display for WeekOfMonthError {
2139    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2140        use self::WeekOfMonthError::*;
2141        match *self {
2142            Parse(ref err) => {
2143                f.write_str("invalid week-of-month digits: ")?;
2144                core::fmt::Display::fmt(err, f)
2145            }
2146            Range => f.write_str(
2147                "parsed week-of-month, but it's not in supported \
2148                 range of `1..=5`",
2149            ),
2150        }
2151    }
2152}
2153
2154#[derive(#[automatically_derived]impl ::core::clone::Clone for WeekdayError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Parse(__self_0) =>
                WeekdayError::Parse(::core::clone::Clone::clone(__self_0)),
            Self::Range => WeekdayError::Range,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for WeekdayError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Parse(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Parse",
                    &__self_0),
            Self::Range => ::core::fmt::Formatter::write_str(f, "Range"),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for WeekdayError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NumberError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    WeekdayError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for WeekdayError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Parse(__self_0), Self::Parse(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
2155#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2156enum WeekdayError {
2157    Parse(NumberError),
2158    Range,
2159}
2160
2161impl core::fmt::Display for WeekdayError {
2162    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2163        use self::WeekdayError::*;
2164        match *self {
2165            Parse(ref err) => {
2166                f.write_str("invalid weekday digits: ")?;
2167                core::fmt::Display::fmt(err, f)
2168            }
2169            Range => f.write_str(
2170                "parsed weekday, but it's not in supported \
2171                 range of `0..=6` (with `0` corresponding to Sunday)",
2172            ),
2173        }
2174    }
2175}
2176
2177#[derive(#[automatically_derived]impl ::core::clone::Clone for HourIanaError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Parse(__self_0) =>
                HourIanaError::Parse(::core::clone::Clone::clone(__self_0)),
            Self::Range => HourIanaError::Range,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for HourIanaError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Parse(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Parse",
                    &__self_0),
            Self::Range => ::core::fmt::Formatter::write_str(f, "Range"),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for HourIanaError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NumberError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    HourIanaError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for HourIanaError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Parse(__self_0), Self::Parse(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
2178#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2179enum HourIanaError {
2180    Parse(NumberError),
2181    Range,
2182}
2183
2184impl core::fmt::Display for HourIanaError {
2185    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2186        use self::HourIanaError::*;
2187        match *self {
2188            Parse(ref err) => {
2189                f.write_str("invalid hour digits: ")?;
2190                core::fmt::Display::fmt(err, f)
2191            }
2192            Range => f.write_str(
2193                "parsed hours, but it's not in supported \
2194                 range of `-167..=167`",
2195            ),
2196        }
2197    }
2198}
2199
2200#[derive(#[automatically_derived]impl ::core::clone::Clone for HourPosixError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Parse(__self_0) =>
                HourPosixError::Parse(::core::clone::Clone::clone(__self_0)),
            Self::Range => HourPosixError::Range,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for HourPosixError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Parse(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Parse",
                    &__self_0),
            Self::Range => ::core::fmt::Formatter::write_str(f, "Range"),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for HourPosixError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NumberError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    HourPosixError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for HourPosixError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Parse(__self_0), Self::Parse(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
2201#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2202enum HourPosixError {
2203    Parse(NumberError),
2204    Range,
2205}
2206
2207impl core::fmt::Display for HourPosixError {
2208    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2209        use self::HourPosixError::*;
2210        match *self {
2211            Parse(ref err) => {
2212                f.write_str("invalid hour digits: ")?;
2213                core::fmt::Display::fmt(err, f)
2214            }
2215            Range => f.write_str(
2216                "parsed hours, but it's not in supported \
2217                 range of `0..=24`",
2218            ),
2219        }
2220    }
2221}
2222
2223#[derive(#[automatically_derived]impl ::core::clone::Clone for MinuteError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Parse(__self_0) =>
                MinuteError::Parse(::core::clone::Clone::clone(__self_0)),
            Self::Range => MinuteError::Range,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for MinuteError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Parse(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Parse",
                    &__self_0),
            Self::Range => ::core::fmt::Formatter::write_str(f, "Range"),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for MinuteError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NumberError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    MinuteError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for MinuteError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Parse(__self_0), Self::Parse(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
2224#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2225enum MinuteError {
2226    Parse(NumberError),
2227    Range,
2228}
2229
2230impl core::fmt::Display for MinuteError {
2231    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2232        use self::MinuteError::*;
2233        match *self {
2234            Parse(ref err) => {
2235                f.write_str("invalid minute digits: ")?;
2236                core::fmt::Display::fmt(err, f)
2237            }
2238            Range => f.write_str(
2239                "parsed minutes, but it's not in supported \
2240                 range of `0..=59`",
2241            ),
2242        }
2243    }
2244}
2245
2246#[derive(#[automatically_derived]impl ::core::clone::Clone for SecondError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Parse(__self_0) =>
                SecondError::Parse(::core::clone::Clone::clone(__self_0)),
            Self::Range => SecondError::Range,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for SecondError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Parse(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Parse",
                    &__self_0),
            Self::Range => ::core::fmt::Formatter::write_str(f, "Range"),
        }
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for SecondError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NumberError>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    SecondError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for SecondError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Parse(__self_0), Self::Parse(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
2247#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2248enum SecondError {
2249    Parse(NumberError),
2250    Range,
2251}
2252
2253impl core::fmt::Display for SecondError {
2254    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2255        use self::SecondError::*;
2256        match *self {
2257            Parse(ref err) => {
2258                f.write_str("invalid second digits: ")?;
2259                core::fmt::Display::fmt(err, f)
2260            }
2261            Range => f.write_str(
2262                "parsed seconds, but it's not in supported \
2263                 range of `0..=59`",
2264            ),
2265        }
2266    }
2267}
2268
2269#[derive(#[automatically_derived]impl ::core::clone::Clone for NumberError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Empty => NumberError::Empty,
            Self::ExpectedLength => NumberError::ExpectedLength,
            Self::InvalidDigit => NumberError::InvalidDigit,
            Self::TooBig => NumberError::TooBig,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for NumberError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                NumberError::Empty => "Empty",
                NumberError::ExpectedLength => "ExpectedLength",
                NumberError::InvalidDigit => "InvalidDigit",
                NumberError::TooBig => "TooBig",
            })
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for NumberError { }Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    NumberError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for NumberError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
2270#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2271enum NumberError {
2272    Empty,
2273    ExpectedLength,
2274    InvalidDigit,
2275    TooBig,
2276}
2277
2278impl core::fmt::Display for NumberError {
2279    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2280        use self::NumberError::*;
2281        match *self {
2282            Empty => f.write_str("invalid number, no digits found"),
2283            ExpectedLength => f.write_str(
2284                "expected a fixed number of digits, \
2285                 but found incorrect number",
2286            ),
2287            InvalidDigit => f.write_str("expected digit in range `0..=9`"),
2288            TooBig => f.write_str(
2289                "parsed number too big to fit into a 32-bit signed integer",
2290            ),
2291        }
2292    }
2293}
2294
2295#[derive(#[automatically_derived]impl ::core::clone::Clone for OptionalSignError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::ExpectedDigitAfterMinus =>
                OptionalSignError::ExpectedDigitAfterMinus,
            Self::ExpectedDigitAfterPlus =>
                OptionalSignError::ExpectedDigitAfterPlus,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for OptionalSignError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                OptionalSignError::ExpectedDigitAfterMinus =>
                    "ExpectedDigitAfterMinus",
                OptionalSignError::ExpectedDigitAfterPlus =>
                    "ExpectedDigitAfterPlus",
            })
    }
}Debug, #[automatically_derived]impl ::core::cmp::Eq for OptionalSignError { }Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    OptionalSignError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for OptionalSignError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
2296#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2297enum OptionalSignError {
2298    ExpectedDigitAfterMinus,
2299    ExpectedDigitAfterPlus,
2300}
2301
2302impl core::fmt::Display for OptionalSignError {
2303    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2304        use self::OptionalSignError::*;
2305        match *self {
2306            ExpectedDigitAfterMinus => f.write_str(
2307                "expected digit after `-` sign, \
2308                 but got end of input",
2309            ),
2310            ExpectedDigitAfterPlus => f.write_str(
2311                "expected digit after `+` sign, \
2312                 but got end of input",
2313            ),
2314        }
2315    }
2316}
2317
2318#[cfg(test)]
2319mod tests {
2320    use crate::civil::date;
2321
2322    use super::*;
2323
2324    fn posix_time_zone(input: impl AsRef<[u8]>) -> TimeZone {
2325        let input = input.as_ref();
2326        let tz = TimeZone::parse(input).unwrap();
2327        tz
2328    }
2329
2330    fn parser(s: &str) -> Parser<'_> {
2331        Parser::new(s)
2332    }
2333
2334    fn astr(s: &'static str) -> Abbreviation {
2335        Abbreviation::array(s)
2336    }
2337
2338    fn off(seconds: i32) -> Offset {
2339        Offset::from_seconds(seconds).unwrap()
2340    }
2341
2342    #[test]
2343    fn parse() {
2344        let p = parser("NZST-12NZDT,J60,J300");
2345        assert_eq!(
2346            p.parse().unwrap(),
2347            TimeZone {
2348                std_abbrev: astr("NZST"),
2349                std_offset: off(12 * 60 * 60),
2350                dst: Some(Dst {
2351                    abbrev: astr("NZDT"),
2352                    offset: off(13 * 60 * 60),
2353                    rule: Rule {
2354                        start: DayTime {
2355                            date: Day::JulianOne(60),
2356                            time: TransitionCivilTime { second: 2 * 60 * 60 },
2357                        },
2358                        end: DayTime {
2359                            date: Day::JulianOne(300),
2360                            time: TransitionCivilTime { second: 2 * 60 * 60 },
2361                        },
2362                    },
2363                }),
2364            },
2365        );
2366
2367        let p = Parser::new("NZST-12NZDT,J60,J300WAT");
2368        assert!(p.parse().is_err());
2369    }
2370
2371    #[test]
2372    fn parse_posix_time_zone() {
2373        let p = Parser::new("NZST-12NZDT,M9.5.0,M4.1.0/3");
2374        assert_eq!(
2375            p.parse_posix_time_zone().unwrap(),
2376            TimeZone {
2377                std_abbrev: astr("NZST"),
2378                std_offset: off(12 * 60 * 60),
2379                dst: Some(Dst {
2380                    abbrev: astr("NZDT"),
2381                    offset: off(13 * 60 * 60),
2382                    rule: Rule {
2383                        start: DayTime {
2384                            date: Day::WeekdayOfMonth {
2385                                month: 9,
2386                                week: 5,
2387                                weekday: Weekday::Sunday,
2388                            },
2389                            time: TransitionCivilTime { second: 2 * 60 * 60 },
2390                        },
2391                        end: DayTime {
2392                            date: Day::WeekdayOfMonth {
2393                                month: 4,
2394                                week: 1,
2395                                weekday: Weekday::Sunday,
2396                            },
2397                            time: TransitionCivilTime { second: 3 * 60 * 60 },
2398                        },
2399                    },
2400                }),
2401            },
2402        );
2403
2404        let p = Parser::new("NZST-12NZDT,M9.5.0,M4.1.0/3WAT");
2405        assert_eq!(
2406            p.parse_posix_time_zone().unwrap(),
2407            TimeZone {
2408                std_abbrev: astr("NZST"),
2409                std_offset: off(12 * 60 * 60),
2410                dst: Some(Dst {
2411                    abbrev: astr("NZDT"),
2412                    offset: off(13 * 60 * 60),
2413                    rule: Rule {
2414                        start: DayTime {
2415                            date: Day::WeekdayOfMonth {
2416                                month: 9,
2417                                week: 5,
2418                                weekday: Weekday::Sunday,
2419                            },
2420                            time: TransitionCivilTime { second: 2 * 60 * 60 },
2421                        },
2422                        end: DayTime {
2423                            date: Day::WeekdayOfMonth {
2424                                month: 4,
2425                                week: 1,
2426                                weekday: Weekday::Sunday,
2427                            },
2428                            time: TransitionCivilTime { second: 3 * 60 * 60 },
2429                        },
2430                    },
2431                }),
2432            },
2433        );
2434
2435        let p = Parser::new("NZST-12NZDT,J60,J300");
2436        assert_eq!(
2437            p.parse_posix_time_zone().unwrap(),
2438            TimeZone {
2439                std_abbrev: astr("NZST"),
2440                std_offset: off(12 * 60 * 60),
2441                dst: Some(Dst {
2442                    abbrev: astr("NZDT"),
2443                    offset: off(13 * 60 * 60),
2444                    rule: Rule {
2445                        start: DayTime {
2446                            date: Day::JulianOne(60),
2447                            time: TransitionCivilTime { second: 2 * 60 * 60 },
2448                        },
2449                        end: DayTime {
2450                            date: Day::JulianOne(300),
2451                            time: TransitionCivilTime { second: 2 * 60 * 60 },
2452                        },
2453                    },
2454                }),
2455            },
2456        );
2457
2458        let p = Parser::new("NZST-12NZDT,J60,J300WAT");
2459        assert_eq!(
2460            p.parse_posix_time_zone().unwrap(),
2461            TimeZone {
2462                std_abbrev: astr("NZST"),
2463                std_offset: off(12 * 60 * 60),
2464                dst: Some(Dst {
2465                    abbrev: astr("NZDT"),
2466                    offset: off(13 * 60 * 60),
2467                    rule: Rule {
2468                        start: DayTime {
2469                            date: Day::JulianOne(60),
2470                            time: TransitionCivilTime { second: 2 * 60 * 60 },
2471                        },
2472                        end: DayTime {
2473                            date: Day::JulianOne(300),
2474                            time: TransitionCivilTime { second: 2 * 60 * 60 },
2475                        },
2476                    },
2477                }),
2478            },
2479        );
2480    }
2481
2482    #[test]
2483    fn parse_posix_dst() {
2484        let p = Parser::new("NZDT,M9.5.0,M4.1.0/3");
2485        assert_eq!(
2486            p.parse_posix_dst(off(12 * 60 * 60)).unwrap(),
2487            Dst {
2488                abbrev: astr("NZDT"),
2489                offset: off(13 * 60 * 60),
2490                rule: Rule {
2491                    start: DayTime {
2492                        date: Day::WeekdayOfMonth {
2493                            month: 9,
2494                            week: 5,
2495                            weekday: Weekday::Sunday,
2496                        },
2497                        time: TransitionCivilTime { second: 2 * 60 * 60 },
2498                    },
2499                    end: DayTime {
2500                        date: Day::WeekdayOfMonth {
2501                            month: 4,
2502                            week: 1,
2503                            weekday: Weekday::Sunday,
2504                        },
2505                        time: TransitionCivilTime { second: 3 * 60 * 60 },
2506                    },
2507                },
2508            },
2509        );
2510
2511        let p = Parser::new("NZDT,J60,J300");
2512        assert_eq!(
2513            p.parse_posix_dst(off(12 * 60 * 60)).unwrap(),
2514            Dst {
2515                abbrev: astr("NZDT"),
2516                offset: off(13 * 60 * 60),
2517                rule: Rule {
2518                    start: DayTime {
2519                        date: Day::JulianOne(60),
2520                        time: TransitionCivilTime { second: 2 * 60 * 60 },
2521                    },
2522                    end: DayTime {
2523                        date: Day::JulianOne(300),
2524                        time: TransitionCivilTime { second: 2 * 60 * 60 },
2525                    },
2526                },
2527            },
2528        );
2529
2530        let p = Parser::new("NZDT-7,J60,J300");
2531        assert_eq!(
2532            p.parse_posix_dst(off(12 * 60 * 60)).unwrap(),
2533            Dst {
2534                abbrev: astr("NZDT"),
2535                offset: off(7 * 60 * 60),
2536                rule: Rule {
2537                    start: DayTime {
2538                        date: Day::JulianOne(60),
2539                        time: TransitionCivilTime { second: 2 * 60 * 60 },
2540                    },
2541                    end: DayTime {
2542                        date: Day::JulianOne(300),
2543                        time: TransitionCivilTime { second: 2 * 60 * 60 },
2544                    },
2545                },
2546            },
2547        );
2548
2549        let p = Parser::new("NZDT+7,J60,J300");
2550        assert_eq!(
2551            p.parse_posix_dst(off(12 * 60 * 60)).unwrap(),
2552            Dst {
2553                abbrev: astr("NZDT"),
2554                offset: off(-7 * 60 * 60),
2555                rule: Rule {
2556                    start: DayTime {
2557                        date: Day::JulianOne(60),
2558                        time: TransitionCivilTime { second: 2 * 60 * 60 },
2559                    },
2560                    end: DayTime {
2561                        date: Day::JulianOne(300),
2562                        time: TransitionCivilTime { second: 2 * 60 * 60 },
2563                    },
2564                },
2565            },
2566        );
2567
2568        let p = Parser::new("NZDT7,J60,J300");
2569        assert_eq!(
2570            p.parse_posix_dst(off(12 * 60 * 60)).unwrap(),
2571            Dst {
2572                abbrev: astr("NZDT"),
2573                offset: off(-7 * 60 * 60),
2574                rule: Rule {
2575                    start: DayTime {
2576                        date: Day::JulianOne(60),
2577                        time: TransitionCivilTime { second: 2 * 60 * 60 },
2578                    },
2579                    end: DayTime {
2580                        date: Day::JulianOne(300),
2581                        time: TransitionCivilTime { second: 2 * 60 * 60 },
2582                    },
2583                },
2584            },
2585        );
2586
2587        let p = Parser::new("NZDT7,");
2588        assert!(p.parse_posix_dst(off(12 * 60 * 60)).is_err());
2589
2590        let p = Parser::new("NZDT7!");
2591        assert!(p.parse_posix_dst(off(12 * 60 * 60)).is_err());
2592    }
2593
2594    #[test]
2595    fn parse_abbreviation() {
2596        let p = Parser::new("ABC");
2597        assert_eq!(p.parse_abbreviation().unwrap(), "ABC");
2598
2599        let p = Parser::new("<ABC>");
2600        assert_eq!(p.parse_abbreviation().unwrap(), "ABC");
2601
2602        let p = Parser::new("<+09>");
2603        assert_eq!(p.parse_abbreviation().unwrap(), "+09");
2604
2605        let p = Parser::new("+09");
2606        assert!(p.parse_abbreviation().is_err());
2607    }
2608
2609    #[test]
2610    fn parse_unquoted_abbreviation() {
2611        let p = Parser::new("ABC");
2612        assert_eq!(p.parse_unquoted_abbreviation().unwrap(), "ABC");
2613
2614        let p = Parser::new("ABCXYZ");
2615        assert_eq!(p.parse_unquoted_abbreviation().unwrap(), "ABCXYZ");
2616
2617        let p = Parser::new("ABC123");
2618        assert_eq!(p.parse_unquoted_abbreviation().unwrap(), "ABC");
2619
2620        let tz = "a".repeat(6);
2621        let p = Parser::new(&tz);
2622        assert_eq!(p.parse_unquoted_abbreviation().unwrap(), &*tz);
2623
2624        let p = Parser::new("a");
2625        assert!(p.parse_unquoted_abbreviation().is_err());
2626
2627        let p = Parser::new("ab");
2628        assert!(p.parse_unquoted_abbreviation().is_err());
2629
2630        let p = Parser::new("ab1");
2631        assert!(p.parse_unquoted_abbreviation().is_err());
2632
2633        let tz = "a".repeat(31);
2634        #[cfg(feature = "alloc")]
2635        {
2636            let p = Parser::new(&tz);
2637            assert_eq!(p.parse_unquoted_abbreviation().unwrap(), &*tz);
2638        }
2639        #[cfg(not(feature = "alloc"))]
2640        {
2641            let p = Parser::new(&tz);
2642            assert!(p.parse_unquoted_abbreviation().is_err());
2643        }
2644
2645        let p = Parser::new(b"ab\xFFcd");
2646        assert!(p.parse_unquoted_abbreviation().is_err());
2647    }
2648
2649    #[test]
2650    fn parse_quoted_abbreviation() {
2651        // The inputs look a little funny here, but that's because
2652        // 'parse_quoted_abbreviation' starts after the opening quote
2653        // has been parsed.
2654
2655        let p = Parser::new("ABC>");
2656        assert_eq!(p.parse_quoted_abbreviation().unwrap(), "ABC");
2657
2658        let p = Parser::new("ABCXYZ>");
2659        assert_eq!(p.parse_quoted_abbreviation().unwrap(), "ABCXYZ");
2660
2661        let p = Parser::new("ABC>123");
2662        assert_eq!(p.parse_quoted_abbreviation().unwrap(), "ABC");
2663
2664        let p = Parser::new("ABC123>");
2665        assert_eq!(p.parse_quoted_abbreviation().unwrap(), "ABC123");
2666
2667        let p = Parser::new("ab1>");
2668        assert_eq!(p.parse_quoted_abbreviation().unwrap(), "ab1");
2669
2670        let p = Parser::new("+09>");
2671        assert_eq!(p.parse_quoted_abbreviation().unwrap(), "+09");
2672
2673        let p = Parser::new("-09>");
2674        assert_eq!(p.parse_quoted_abbreviation().unwrap(), "-09");
2675
2676        let tz = alloc::format!("{}>", "a".repeat(6));
2677        let p = Parser::new(&tz);
2678        assert_eq!(
2679            p.parse_quoted_abbreviation().unwrap(),
2680            tz.trim_end_matches(">")
2681        );
2682
2683        let p = Parser::new("a>");
2684        assert!(p.parse_quoted_abbreviation().is_err());
2685
2686        let p = Parser::new("ab>");
2687        assert!(p.parse_quoted_abbreviation().is_err());
2688
2689        let tz = alloc::format!("{}>", "a".repeat(31));
2690        #[cfg(feature = "alloc")]
2691        {
2692            let p = Parser::new(&tz);
2693            assert_eq!(
2694                p.parse_quoted_abbreviation().unwrap(),
2695                tz.trim_end_matches(">")
2696            );
2697        }
2698        #[cfg(not(feature = "alloc"))]
2699        {
2700            let p = Parser::new(&tz);
2701            assert!(p.parse_quoted_abbreviation().is_err());
2702        }
2703
2704        let p = Parser::new(b"ab\xFFcd>");
2705        assert!(p.parse_quoted_abbreviation().is_err());
2706
2707        let p = Parser::new("ABC");
2708        assert!(p.parse_quoted_abbreviation().is_err());
2709
2710        let p = Parser::new("ABC!>");
2711        assert!(p.parse_quoted_abbreviation().is_err());
2712    }
2713
2714    #[test]
2715    fn parse_posix_offset() {
2716        let p = Parser::new("5");
2717        assert_eq!(p.parse_posix_offset().unwrap().seconds(), -5 * 60 * 60);
2718
2719        let p = Parser::new("+5");
2720        assert_eq!(p.parse_posix_offset().unwrap().seconds(), -5 * 60 * 60);
2721
2722        let p = Parser::new("-5");
2723        assert_eq!(p.parse_posix_offset().unwrap().seconds(), 5 * 60 * 60);
2724
2725        let p = Parser::new("-12:34:56");
2726        assert_eq!(
2727            p.parse_posix_offset().unwrap().seconds(),
2728            12 * 60 * 60 + 34 * 60 + 56,
2729        );
2730
2731        let p = Parser::new("a");
2732        assert!(p.parse_posix_offset().is_err());
2733
2734        let p = Parser::new("-");
2735        assert!(p.parse_posix_offset().is_err());
2736
2737        let p = Parser::new("+");
2738        assert!(p.parse_posix_offset().is_err());
2739
2740        let p = Parser::new("-a");
2741        assert!(p.parse_posix_offset().is_err());
2742
2743        let p = Parser::new("+a");
2744        assert!(p.parse_posix_offset().is_err());
2745
2746        let p = Parser::new("-25");
2747        assert!(p.parse_posix_offset().is_err());
2748
2749        let p = Parser::new("+25");
2750        assert!(p.parse_posix_offset().is_err());
2751
2752        // This checks that we don't accidentally permit IANA rules for
2753        // offset parsing. Namely, the IANA tzfile v3+ extension only applies
2754        // to transition times. But since POSIX says that the "time" for the
2755        // offset and transition is the same format, it would be an easy
2756        // implementation mistake to implement the more flexible rule for
2757        // IANA and have it accidentally also apply to the offset. So we check
2758        // that it doesn't here.
2759        let p = Parser { ianav3plus: true, ..Parser::new("25") };
2760        assert!(p.parse_posix_offset().is_err());
2761        let p = Parser { ianav3plus: true, ..Parser::new("+25") };
2762        assert!(p.parse_posix_offset().is_err());
2763        let p = Parser { ianav3plus: true, ..Parser::new("-25") };
2764        assert!(p.parse_posix_offset().is_err());
2765    }
2766
2767    #[test]
2768    fn parse_rule() {
2769        let p = Parser::new("M9.5.0,M4.1.0/3");
2770        assert_eq!(
2771            p.parse_rule().unwrap(),
2772            Rule {
2773                start: DayTime {
2774                    date: Day::WeekdayOfMonth {
2775                        month: 9,
2776                        week: 5,
2777                        weekday: Weekday::Sunday,
2778                    },
2779                    time: TransitionCivilTime { second: 2 * 60 * 60 },
2780                },
2781                end: DayTime {
2782                    date: Day::WeekdayOfMonth {
2783                        month: 4,
2784                        week: 1,
2785                        weekday: Weekday::Sunday,
2786                    },
2787                    time: TransitionCivilTime { second: 3 * 60 * 60 },
2788                },
2789            },
2790        );
2791
2792        let p = Parser::new("M9.5.0");
2793        assert!(p.parse_rule().is_err());
2794
2795        let p = Parser::new(",M9.5.0,M4.1.0/3");
2796        assert!(p.parse_rule().is_err());
2797
2798        let p = Parser::new("M9.5.0/");
2799        assert!(p.parse_rule().is_err());
2800
2801        let p = Parser::new("M9.5.0,M4.1.0/");
2802        assert!(p.parse_rule().is_err());
2803    }
2804
2805    #[test]
2806    fn parse_posix_datetime() {
2807        let p = Parser::new("J1");
2808        assert_eq!(
2809            p.parse_posix_datetime().unwrap(),
2810            DayTime {
2811                date: Day::JulianOne(1),
2812                time: TransitionCivilTime { second: 2 * 60 * 60 }
2813            },
2814        );
2815
2816        let p = Parser::new("J1/3");
2817        assert_eq!(
2818            p.parse_posix_datetime().unwrap(),
2819            DayTime {
2820                date: Day::JulianOne(1),
2821                time: TransitionCivilTime { second: 3 * 60 * 60 }
2822            },
2823        );
2824
2825        let p = Parser::new("M4.1.0/3");
2826        assert_eq!(
2827            p.parse_posix_datetime().unwrap(),
2828            DayTime {
2829                date: Day::WeekdayOfMonth {
2830                    month: 4,
2831                    week: 1,
2832                    weekday: Weekday::Sunday
2833                },
2834                time: TransitionCivilTime { second: 3 * 60 * 60 },
2835            },
2836        );
2837
2838        let p = Parser::new("1/3:45:05");
2839        assert_eq!(
2840            p.parse_posix_datetime().unwrap(),
2841            DayTime {
2842                date: Day::JulianZero(1),
2843                time: TransitionCivilTime {
2844                    second: 3 * 60 * 60 + 45 * 60 + 5
2845                },
2846            },
2847        );
2848
2849        let p = Parser::new("a");
2850        assert!(p.parse_posix_datetime().is_err());
2851
2852        let p = Parser::new("J1/");
2853        assert!(p.parse_posix_datetime().is_err());
2854
2855        let p = Parser::new("1/");
2856        assert!(p.parse_posix_datetime().is_err());
2857
2858        let p = Parser::new("M4.1.0/");
2859        assert!(p.parse_posix_datetime().is_err());
2860    }
2861
2862    #[test]
2863    fn parse_posix_date() {
2864        let p = Parser::new("J1");
2865        assert_eq!(p.parse_posix_date().unwrap(), Day::JulianOne(1));
2866        let p = Parser::new("J365");
2867        assert_eq!(p.parse_posix_date().unwrap(), Day::JulianOne(365));
2868
2869        let p = Parser::new("0");
2870        assert_eq!(p.parse_posix_date().unwrap(), Day::JulianZero(0));
2871        let p = Parser::new("1");
2872        assert_eq!(p.parse_posix_date().unwrap(), Day::JulianZero(1));
2873        let p = Parser::new("365");
2874        assert_eq!(p.parse_posix_date().unwrap(), Day::JulianZero(365));
2875
2876        let p = Parser::new("M9.5.0");
2877        assert_eq!(
2878            p.parse_posix_date().unwrap(),
2879            Day::WeekdayOfMonth {
2880                month: 9,
2881                week: 5,
2882                weekday: Weekday::Sunday
2883            },
2884        );
2885        let p = Parser::new("M9.5.6");
2886        assert_eq!(
2887            p.parse_posix_date().unwrap(),
2888            Day::WeekdayOfMonth {
2889                month: 9,
2890                week: 5,
2891                weekday: Weekday::Saturday
2892            },
2893        );
2894        let p = Parser::new("M09.5.6");
2895        assert_eq!(
2896            p.parse_posix_date().unwrap(),
2897            Day::WeekdayOfMonth {
2898                month: 9,
2899                week: 5,
2900                weekday: Weekday::Saturday
2901            },
2902        );
2903        let p = Parser::new("M12.1.1");
2904        assert_eq!(
2905            p.parse_posix_date().unwrap(),
2906            Day::WeekdayOfMonth {
2907                month: 12,
2908                week: 1,
2909                weekday: Weekday::Monday
2910            },
2911        );
2912
2913        let p = Parser::new("a");
2914        assert!(p.parse_posix_date().is_err());
2915
2916        let p = Parser::new("j");
2917        assert!(p.parse_posix_date().is_err());
2918
2919        let p = Parser::new("m");
2920        assert!(p.parse_posix_date().is_err());
2921
2922        let p = Parser::new("n");
2923        assert!(p.parse_posix_date().is_err());
2924
2925        let p = Parser::new("J366");
2926        assert!(p.parse_posix_date().is_err());
2927
2928        let p = Parser::new("366");
2929        assert!(p.parse_posix_date().is_err());
2930    }
2931
2932    #[test]
2933    fn parse_posix_julian_day_no_leap() {
2934        let p = Parser::new("1");
2935        assert_eq!(p.parse_posix_julian_day_no_leap().unwrap(), 1);
2936
2937        let p = Parser::new("001");
2938        assert_eq!(p.parse_posix_julian_day_no_leap().unwrap(), 1);
2939
2940        let p = Parser::new("365");
2941        assert_eq!(p.parse_posix_julian_day_no_leap().unwrap(), 365);
2942
2943        let p = Parser::new("3655");
2944        assert_eq!(p.parse_posix_julian_day_no_leap().unwrap(), 365);
2945
2946        let p = Parser::new("0");
2947        assert!(p.parse_posix_julian_day_no_leap().is_err());
2948
2949        let p = Parser::new("366");
2950        assert!(p.parse_posix_julian_day_no_leap().is_err());
2951    }
2952
2953    #[test]
2954    fn parse_posix_julian_day_with_leap() {
2955        let p = Parser::new("0");
2956        assert_eq!(p.parse_posix_julian_day_with_leap().unwrap(), 0);
2957
2958        let p = Parser::new("1");
2959        assert_eq!(p.parse_posix_julian_day_with_leap().unwrap(), 1);
2960
2961        let p = Parser::new("001");
2962        assert_eq!(p.parse_posix_julian_day_with_leap().unwrap(), 1);
2963
2964        let p = Parser::new("365");
2965        assert_eq!(p.parse_posix_julian_day_with_leap().unwrap(), 365);
2966
2967        let p = Parser::new("3655");
2968        assert_eq!(p.parse_posix_julian_day_with_leap().unwrap(), 365);
2969
2970        let p = Parser::new("366");
2971        assert!(p.parse_posix_julian_day_with_leap().is_err());
2972    }
2973
2974    #[test]
2975    fn parse_weekday_of_month() {
2976        let p = Parser::new("9.5.0");
2977        assert_eq!(
2978            p.parse_weekday_of_month().unwrap(),
2979            (9, 5, Weekday::Sunday)
2980        );
2981
2982        let p = Parser::new("9.1.6");
2983        assert_eq!(
2984            p.parse_weekday_of_month().unwrap(),
2985            (9, 1, Weekday::Saturday)
2986        );
2987
2988        let p = Parser::new("09.1.6");
2989        assert_eq!(
2990            p.parse_weekday_of_month().unwrap(),
2991            (9, 1, Weekday::Saturday)
2992        );
2993
2994        let p = Parser::new("9");
2995        assert!(p.parse_weekday_of_month().is_err());
2996
2997        let p = Parser::new("9.");
2998        assert!(p.parse_weekday_of_month().is_err());
2999
3000        let p = Parser::new("9.5");
3001        assert!(p.parse_weekday_of_month().is_err());
3002
3003        let p = Parser::new("9.5.");
3004        assert!(p.parse_weekday_of_month().is_err());
3005
3006        let p = Parser::new("0.5.0");
3007        assert!(p.parse_weekday_of_month().is_err());
3008
3009        let p = Parser::new("13.5.0");
3010        assert!(p.parse_weekday_of_month().is_err());
3011
3012        let p = Parser::new("9.0.0");
3013        assert!(p.parse_weekday_of_month().is_err());
3014
3015        let p = Parser::new("9.6.0");
3016        assert!(p.parse_weekday_of_month().is_err());
3017
3018        let p = Parser::new("9.5.7");
3019        assert!(p.parse_weekday_of_month().is_err());
3020    }
3021
3022    #[test]
3023    fn parse_posix_time() {
3024        let p = Parser::new("5");
3025        assert_eq!(p.parse_posix_time().unwrap().second, 5 * 60 * 60);
3026
3027        let p = Parser::new("22");
3028        assert_eq!(p.parse_posix_time().unwrap().second, 22 * 60 * 60);
3029
3030        let p = Parser::new("02");
3031        assert_eq!(p.parse_posix_time().unwrap().second, 2 * 60 * 60);
3032
3033        let p = Parser::new("5:45");
3034        assert_eq!(
3035            p.parse_posix_time().unwrap().second,
3036            5 * 60 * 60 + 45 * 60
3037        );
3038
3039        let p = Parser::new("5:45:12");
3040        assert_eq!(
3041            p.parse_posix_time().unwrap().second,
3042            5 * 60 * 60 + 45 * 60 + 12
3043        );
3044
3045        let p = Parser::new("5:45:129");
3046        assert_eq!(
3047            p.parse_posix_time().unwrap().second,
3048            5 * 60 * 60 + 45 * 60 + 12
3049        );
3050
3051        let p = Parser::new("5:45:12:");
3052        assert_eq!(
3053            p.parse_posix_time().unwrap().second,
3054            5 * 60 * 60 + 45 * 60 + 12
3055        );
3056
3057        let p = Parser { ianav3plus: true, ..Parser::new("+5:45:12") };
3058        assert_eq!(
3059            p.parse_posix_time().unwrap().second,
3060            5 * 60 * 60 + 45 * 60 + 12
3061        );
3062
3063        let p = Parser { ianav3plus: true, ..Parser::new("-5:45:12") };
3064        assert_eq!(
3065            p.parse_posix_time().unwrap().second,
3066            -(5 * 60 * 60 + 45 * 60 + 12)
3067        );
3068
3069        let p = Parser { ianav3plus: true, ..Parser::new("-167:45:12") };
3070        assert_eq!(
3071            p.parse_posix_time().unwrap().second,
3072            -(167 * 60 * 60 + 45 * 60 + 12),
3073        );
3074
3075        let p = Parser::new("25");
3076        assert!(p.parse_posix_time().is_err());
3077
3078        let p = Parser::new("12:2");
3079        assert!(p.parse_posix_time().is_err());
3080
3081        let p = Parser::new("12:");
3082        assert!(p.parse_posix_time().is_err());
3083
3084        let p = Parser::new("12:23:5");
3085        assert!(p.parse_posix_time().is_err());
3086
3087        let p = Parser::new("12:23:");
3088        assert!(p.parse_posix_time().is_err());
3089
3090        let p = Parser { ianav3plus: true, ..Parser::new("168") };
3091        assert!(p.parse_posix_time().is_err());
3092
3093        let p = Parser { ianav3plus: true, ..Parser::new("-168") };
3094        assert!(p.parse_posix_time().is_err());
3095
3096        let p = Parser { ianav3plus: true, ..Parser::new("+168") };
3097        assert!(p.parse_posix_time().is_err());
3098    }
3099
3100    #[test]
3101    fn parse_month() {
3102        let p = Parser::new("1");
3103        assert_eq!(p.parse_month().unwrap(), 1);
3104
3105        // Should this be allowed? POSIX spec is unclear.
3106        // We allow it because our parse does stop at 2
3107        // digits, so this seems harmless. Namely, '001'
3108        // results in an error.
3109        let p = Parser::new("01");
3110        assert_eq!(p.parse_month().unwrap(), 1);
3111
3112        let p = Parser::new("12");
3113        assert_eq!(p.parse_month().unwrap(), 12);
3114
3115        let p = Parser::new("0");
3116        assert!(p.parse_month().is_err());
3117
3118        let p = Parser::new("00");
3119        assert!(p.parse_month().is_err());
3120
3121        let p = Parser::new("001");
3122        assert!(p.parse_month().is_err());
3123
3124        let p = Parser::new("13");
3125        assert!(p.parse_month().is_err());
3126    }
3127
3128    #[test]
3129    fn parse_week() {
3130        let p = Parser::new("1");
3131        assert_eq!(p.parse_week().unwrap(), 1);
3132
3133        let p = Parser::new("5");
3134        assert_eq!(p.parse_week().unwrap(), 5);
3135
3136        let p = Parser::new("55");
3137        assert_eq!(p.parse_week().unwrap(), 5);
3138
3139        let p = Parser::new("0");
3140        assert!(p.parse_week().is_err());
3141
3142        let p = Parser::new("6");
3143        assert!(p.parse_week().is_err());
3144
3145        let p = Parser::new("00");
3146        assert!(p.parse_week().is_err());
3147
3148        let p = Parser::new("01");
3149        assert!(p.parse_week().is_err());
3150
3151        let p = Parser::new("05");
3152        assert!(p.parse_week().is_err());
3153    }
3154
3155    #[test]
3156    fn parse_weekday() {
3157        let p = Parser::new("0");
3158        assert_eq!(p.parse_weekday().unwrap(), Weekday::Sunday);
3159
3160        let p = Parser::new("1");
3161        assert_eq!(p.parse_weekday().unwrap(), Weekday::Monday);
3162
3163        let p = Parser::new("6");
3164        assert_eq!(p.parse_weekday().unwrap(), Weekday::Saturday);
3165
3166        let p = Parser::new("00");
3167        assert_eq!(p.parse_weekday().unwrap(), Weekday::Sunday);
3168
3169        let p = Parser::new("06");
3170        assert_eq!(p.parse_weekday().unwrap(), Weekday::Sunday);
3171
3172        let p = Parser::new("60");
3173        assert_eq!(p.parse_weekday().unwrap(), Weekday::Saturday);
3174
3175        let p = Parser::new("7");
3176        assert!(p.parse_weekday().is_err());
3177    }
3178
3179    #[test]
3180    fn parse_hour_posix() {
3181        let p = Parser::new("5");
3182        assert_eq!(p.parse_hour_posix().unwrap(), 5);
3183
3184        let p = Parser::new("0");
3185        assert_eq!(p.parse_hour_posix().unwrap(), 0);
3186
3187        let p = Parser::new("00");
3188        assert_eq!(p.parse_hour_posix().unwrap(), 0);
3189
3190        let p = Parser::new("24");
3191        assert_eq!(p.parse_hour_posix().unwrap(), 24);
3192
3193        let p = Parser::new("100");
3194        assert_eq!(p.parse_hour_posix().unwrap(), 10);
3195
3196        let p = Parser::new("25");
3197        assert!(p.parse_hour_posix().is_err());
3198
3199        let p = Parser::new("99");
3200        assert!(p.parse_hour_posix().is_err());
3201    }
3202
3203    #[test]
3204    fn parse_hour_ianav3plus() {
3205        let new = |input| Parser { ianav3plus: true, ..Parser::new(input) };
3206
3207        let p = new("5");
3208        assert_eq!(p.parse_hour_ianav3plus().unwrap(), 5);
3209
3210        let p = new("0");
3211        assert_eq!(p.parse_hour_ianav3plus().unwrap(), 0);
3212
3213        let p = new("00");
3214        assert_eq!(p.parse_hour_ianav3plus().unwrap(), 0);
3215
3216        let p = new("000");
3217        assert_eq!(p.parse_hour_ianav3plus().unwrap(), 0);
3218
3219        let p = new("24");
3220        assert_eq!(p.parse_hour_ianav3plus().unwrap(), 24);
3221
3222        let p = new("100");
3223        assert_eq!(p.parse_hour_ianav3plus().unwrap(), 100);
3224
3225        let p = new("1000");
3226        assert_eq!(p.parse_hour_ianav3plus().unwrap(), 100);
3227
3228        let p = new("167");
3229        assert_eq!(p.parse_hour_ianav3plus().unwrap(), 167);
3230
3231        let p = new("168");
3232        assert!(p.parse_hour_ianav3plus().is_err());
3233
3234        let p = new("999");
3235        assert!(p.parse_hour_ianav3plus().is_err());
3236    }
3237
3238    #[test]
3239    fn parse_minute() {
3240        let p = Parser::new("00");
3241        assert_eq!(p.parse_minute().unwrap(), 0);
3242
3243        let p = Parser::new("24");
3244        assert_eq!(p.parse_minute().unwrap(), 24);
3245
3246        let p = Parser::new("59");
3247        assert_eq!(p.parse_minute().unwrap(), 59);
3248
3249        let p = Parser::new("599");
3250        assert_eq!(p.parse_minute().unwrap(), 59);
3251
3252        let p = Parser::new("0");
3253        assert!(p.parse_minute().is_err());
3254
3255        let p = Parser::new("1");
3256        assert!(p.parse_minute().is_err());
3257
3258        let p = Parser::new("9");
3259        assert!(p.parse_minute().is_err());
3260
3261        let p = Parser::new("60");
3262        assert!(p.parse_minute().is_err());
3263    }
3264
3265    #[test]
3266    fn parse_second() {
3267        let p = Parser::new("00");
3268        assert_eq!(p.parse_second().unwrap(), 0);
3269
3270        let p = Parser::new("24");
3271        assert_eq!(p.parse_second().unwrap(), 24);
3272
3273        let p = Parser::new("59");
3274        assert_eq!(p.parse_second().unwrap(), 59);
3275
3276        let p = Parser::new("599");
3277        assert_eq!(p.parse_second().unwrap(), 59);
3278
3279        let p = Parser::new("0");
3280        assert!(p.parse_second().is_err());
3281
3282        let p = Parser::new("1");
3283        assert!(p.parse_second().is_err());
3284
3285        let p = Parser::new("9");
3286        assert!(p.parse_second().is_err());
3287
3288        let p = Parser::new("60");
3289        assert!(p.parse_second().is_err());
3290    }
3291
3292    #[test]
3293    fn parse_number_with_exactly_n_digits() {
3294        let p = Parser::new("1");
3295        assert_eq!(p.parse_number_with_exactly_n_digits(1).unwrap(), 1);
3296
3297        let p = Parser::new("12");
3298        assert_eq!(p.parse_number_with_exactly_n_digits(2).unwrap(), 12);
3299
3300        let p = Parser::new("123");
3301        assert_eq!(p.parse_number_with_exactly_n_digits(2).unwrap(), 12);
3302
3303        let p = Parser::new("");
3304        assert!(p.parse_number_with_exactly_n_digits(1).is_err());
3305
3306        let p = Parser::new("1");
3307        assert!(p.parse_number_with_exactly_n_digits(2).is_err());
3308
3309        let p = Parser::new("12");
3310        assert!(p.parse_number_with_exactly_n_digits(3).is_err());
3311    }
3312
3313    #[test]
3314    fn parse_number_with_upto_n_digits() {
3315        let p = Parser::new("1");
3316        assert_eq!(p.parse_number_with_upto_n_digits(1).unwrap(), 1);
3317
3318        let p = Parser::new("1");
3319        assert_eq!(p.parse_number_with_upto_n_digits(2).unwrap(), 1);
3320
3321        let p = Parser::new("12");
3322        assert_eq!(p.parse_number_with_upto_n_digits(2).unwrap(), 12);
3323
3324        let p = Parser::new("12");
3325        assert_eq!(p.parse_number_with_upto_n_digits(3).unwrap(), 12);
3326
3327        let p = Parser::new("123");
3328        assert_eq!(p.parse_number_with_upto_n_digits(2).unwrap(), 12);
3329
3330        let p = Parser::new("");
3331        assert!(p.parse_number_with_upto_n_digits(1).is_err());
3332
3333        let p = Parser::new("a");
3334        assert!(p.parse_number_with_upto_n_digits(1).is_err());
3335    }
3336
3337    #[test]
3338    fn to_dst_civil_datetime_utc_range() {
3339        let tz = posix_time_zone("WART4WARST,J1/-3,J365/20");
3340        let dst_info = DstInfo {
3341            // We test this in other places. It's too annoying to write this
3342            // out here, and I didn't adopt snapshot testing until I had
3343            // written out these tests by hand.
3344            dst: tz.dst.as_ref().unwrap(),
3345            start: date(2024, 1, 1).at(1, 0, 0, 0),
3346            end: date(2024, 12, 31).at(23, 0, 0, 0),
3347        };
3348        assert_eq!(tz.dst_info_utc(2024), Some(dst_info));
3349
3350        let tz = posix_time_zone("WART4WARST,J1/-4,J365/21");
3351        let dst_info = DstInfo {
3352            dst: tz.dst.as_ref().unwrap(),
3353            start: date(2024, 1, 1).at(0, 0, 0, 0),
3354            end: date(2024, 12, 31).at(23, 59, 59, 999_999_999),
3355        };
3356        assert_eq!(tz.dst_info_utc(2024), Some(dst_info));
3357
3358        let tz = posix_time_zone("EST5EDT,M3.2.0,M11.1.0");
3359        let dst_info = DstInfo {
3360            dst: tz.dst.as_ref().unwrap(),
3361            start: date(2024, 3, 10).at(7, 0, 0, 0),
3362            end: date(2024, 11, 3).at(6, 0, 0, 0),
3363        };
3364        assert_eq!(tz.dst_info_utc(2024), Some(dst_info));
3365    }
3366
3367    // See: https://github.com/BurntSushi/jiff/issues/386
3368    #[test]
3369    fn regression_permanent_dst() {
3370        let tz = posix_time_zone("XXX-2<+01>-1,0/0,J365/23");
3371        let dst_info = DstInfo {
3372            dst: tz.dst.as_ref().unwrap(),
3373            start: date(2087, 1, 1).at(0, 0, 0, 0),
3374            end: date(2087, 12, 31).at(23, 59, 59, 999_999_999),
3375        };
3376        assert_eq!(tz.dst_info_utc(2087), Some(dst_info));
3377    }
3378
3379    #[test]
3380    fn reasonable() {
3381        assert!(TimeZone::parse(b"EST5").is_ok());
3382        assert!(TimeZone::parse(b"EST5EDT").is_err());
3383        assert!(TimeZone::parse(b"EST5EDT,J1,J365").is_ok());
3384
3385        let tz = posix_time_zone("EST24EDT,J1,J365");
3386        assert_eq!(
3387            tz,
3388            TimeZone {
3389                std_abbrev: astr("EST"),
3390                std_offset: off(-24 * 60 * 60),
3391                dst: Some(Dst {
3392                    abbrev: astr("EDT"),
3393                    offset: off(-23 * 60 * 60),
3394                    rule: Rule {
3395                        start: DayTime {
3396                            date: Day::JulianOne(1),
3397                            time: TransitionCivilTime::DEFAULT,
3398                        },
3399                        end: DayTime {
3400                            date: Day::JulianOne(365),
3401                            time: TransitionCivilTime::DEFAULT,
3402                        },
3403                    },
3404                }),
3405            },
3406        );
3407
3408        let tz = posix_time_zone("EST-24EDT,J1,J365");
3409        assert_eq!(
3410            tz,
3411            TimeZone {
3412                std_abbrev: astr("EST"),
3413                std_offset: off(24 * 60 * 60),
3414                dst: Some(Dst {
3415                    abbrev: astr("EDT"),
3416                    offset: off(25 * 60 * 60),
3417                    rule: Rule {
3418                        start: DayTime {
3419                            date: Day::JulianOne(1),
3420                            time: TransitionCivilTime::DEFAULT,
3421                        },
3422                        end: DayTime {
3423                            date: Day::JulianOne(365),
3424                            time: TransitionCivilTime::DEFAULT,
3425                        },
3426                    },
3427                }),
3428            },
3429        );
3430    }
3431
3432    #[test]
3433    fn posix_date_time_spec_to_datetime() {
3434        // For this test, we just keep the offset to zero to simplify things
3435        // a bit. We get coverage for non-zero offsets in higher level tests.
3436        let to_datetime = |daytime: &DayTime, year: i16| {
3437            daytime.to_datetime(year, Offset::UTC)
3438        };
3439
3440        let tz = posix_time_zone("EST5EDT,J1,J365/5:12:34");
3441        assert_eq!(
3442            to_datetime(&tz.rule().start, 2023),
3443            date(2023, 1, 1).at(2, 0, 0, 0),
3444        );
3445        assert_eq!(
3446            to_datetime(&tz.rule().end, 2023),
3447            date(2023, 12, 31).at(5, 12, 34, 0),
3448        );
3449
3450        let tz = posix_time_zone("EST+5EDT,M3.2.0/2,M11.1.0/2");
3451        assert_eq!(
3452            to_datetime(&tz.rule().start, 2024),
3453            date(2024, 3, 10).at(2, 0, 0, 0),
3454        );
3455        assert_eq!(
3456            to_datetime(&tz.rule().end, 2024),
3457            date(2024, 11, 3).at(2, 0, 0, 0),
3458        );
3459
3460        let tz = posix_time_zone("EST+5EDT,M1.1.1,M12.5.2");
3461        assert_eq!(
3462            to_datetime(&tz.rule().start, 2024),
3463            date(2024, 1, 1).at(2, 0, 0, 0),
3464        );
3465        assert_eq!(
3466            to_datetime(&tz.rule().end, 2024),
3467            date(2024, 12, 31).at(2, 0, 0, 0),
3468        );
3469
3470        let tz = posix_time_zone("EST5EDT,0/0,J365/25");
3471        assert_eq!(
3472            to_datetime(&tz.rule().start, 2024),
3473            date(2024, 1, 1).at(0, 0, 0, 0),
3474        );
3475        assert_eq!(
3476            to_datetime(&tz.rule().end, 2024),
3477            date(2024, 12, 31).at(23, 59, 59, 999_999_999),
3478        );
3479
3480        let tz = posix_time_zone("XXX3EDT4,0/0,J365/23");
3481        assert_eq!(
3482            to_datetime(&tz.rule().start, 2024),
3483            date(2024, 1, 1).at(0, 0, 0, 0),
3484        );
3485        assert_eq!(
3486            to_datetime(&tz.rule().end, 2024),
3487            date(2024, 12, 31).at(23, 0, 0, 0),
3488        );
3489
3490        let tz = posix_time_zone("XXX3EDT4,0/0,365");
3491        assert_eq!(
3492            to_datetime(&tz.rule().end, 2023),
3493            date(2023, 12, 31).at(23, 59, 59, 999_999_999),
3494        );
3495        assert_eq!(
3496            to_datetime(&tz.rule().end, 2024),
3497            date(2024, 12, 31).at(2, 0, 0, 0),
3498        );
3499
3500        let tz = posix_time_zone("XXX3EDT4,J1/-167:59:59,J365/167:59:59");
3501        assert_eq!(
3502            to_datetime(&tz.rule().start, 2024),
3503            date(2024, 1, 1).at(0, 0, 0, 0),
3504        );
3505        assert_eq!(
3506            to_datetime(&tz.rule().end, 2024),
3507            date(2024, 12, 31).at(23, 59, 59, 999_999_999),
3508        );
3509    }
3510
3511    #[test]
3512    fn posix_date_time_spec_time() {
3513        let tz = posix_time_zone("EST5EDT,J1,J365/5:12:34");
3514        assert_eq!(tz.rule().start.time, TransitionCivilTime::DEFAULT);
3515        assert_eq!(
3516            tz.rule().end.time,
3517            TransitionCivilTime { second: 5 * 60 * 60 + 12 * 60 + 34 },
3518        );
3519    }
3520
3521    #[test]
3522    fn posix_date_spec_to_date() {
3523        let tz = posix_time_zone("EST+5EDT,M3.2.0/2,M11.1.0/2");
3524        let start = tz.rule().start.date.to_date(2023);
3525        assert_eq!(start, Some(date(2023, 3, 12)));
3526        let end = tz.rule().end.date.to_date(2023);
3527        assert_eq!(end, Some(date(2023, 11, 5)));
3528        let start = tz.rule().start.date.to_date(2024);
3529        assert_eq!(start, Some(date(2024, 3, 10)));
3530        let end = tz.rule().end.date.to_date(2024);
3531        assert_eq!(end, Some(date(2024, 11, 3)));
3532
3533        let tz = posix_time_zone("EST+5EDT,J60,J365");
3534        let start = tz.rule().start.date.to_date(2023);
3535        assert_eq!(start, Some(date(2023, 3, 1)));
3536        let end = tz.rule().end.date.to_date(2023);
3537        assert_eq!(end, Some(date(2023, 12, 31)));
3538        let start = tz.rule().start.date.to_date(2024);
3539        assert_eq!(start, Some(date(2024, 3, 1)));
3540        let end = tz.rule().end.date.to_date(2024);
3541        assert_eq!(end, Some(date(2024, 12, 31)));
3542
3543        let tz = posix_time_zone("EST+5EDT,59,365");
3544        let start = tz.rule().start.date.to_date(2023);
3545        assert_eq!(start, Some(date(2023, 3, 1)));
3546        let end = tz.rule().end.date.to_date(2023);
3547        assert_eq!(end, None);
3548        let start = tz.rule().start.date.to_date(2024);
3549        assert_eq!(start, Some(date(2024, 2, 29)));
3550        let end = tz.rule().end.date.to_date(2024);
3551        assert_eq!(end, Some(date(2024, 12, 31)));
3552
3553        let tz = posix_time_zone("EST+5EDT,M1.1.1,M12.5.2");
3554        let start = tz.rule().start.date.to_date(2024);
3555        assert_eq!(start, Some(date(2024, 1, 1)));
3556        let end = tz.rule().end.date.to_date(2024);
3557        assert_eq!(end, Some(date(2024, 12, 31)));
3558    }
3559
3560    #[test]
3561    fn posix_time_spec_to_civil_time() {
3562        let tz = posix_time_zone("EST5EDT,J1,J365/5:12:34");
3563        assert_eq!(
3564            tz.dst.as_ref().unwrap().rule.start.time.second,
3565            2 * 60 * 60,
3566        );
3567        assert_eq!(
3568            tz.dst.as_ref().unwrap().rule.end.time.second,
3569            5 * 60 * 60 + 12 * 60 + 34,
3570        );
3571
3572        let tz = posix_time_zone("EST5EDT,J1/23:59:59,J365/24:00:00");
3573        assert_eq!(
3574            tz.dst.as_ref().unwrap().rule.start.time.second,
3575            23 * 60 * 60 + 59 * 60 + 59,
3576        );
3577        assert_eq!(
3578            tz.dst.as_ref().unwrap().rule.end.time.second,
3579            24 * 60 * 60,
3580        );
3581
3582        let tz = posix_time_zone("EST5EDT,J1/-1,J365/167:00:00");
3583        assert_eq!(
3584            tz.dst.as_ref().unwrap().rule.start.time.second,
3585            -1 * 60 * 60,
3586        );
3587        assert_eq!(
3588            tz.dst.as_ref().unwrap().rule.end.time.second,
3589            167 * 60 * 60,
3590        );
3591    }
3592
3593    #[test]
3594    fn parse_iana() {
3595        // Ref: https://github.com/chronotope/chrono/issues/1153
3596        let p = TimeZone::parse(b"CRAZY5SHORT,M12.5.0/50,0/2").unwrap();
3597        assert_eq!(
3598            p,
3599            TimeZone {
3600                std_abbrev: astr("CRAZY"),
3601                std_offset: off(-5 * 60 * 60),
3602                dst: Some(Dst {
3603                    abbrev: astr("SHORT"),
3604                    offset: off(-4 * 60 * 60),
3605                    rule: Rule {
3606                        start: DayTime {
3607                            date: Day::WeekdayOfMonth {
3608                                month: 12,
3609                                week: 5,
3610                                weekday: Weekday::Sunday,
3611                            },
3612                            time: TransitionCivilTime { second: 50 * 60 * 60 },
3613                        },
3614                        end: DayTime {
3615                            date: Day::JulianZero(0),
3616                            time: TransitionCivilTime { second: 2 * 60 * 60 },
3617                        },
3618                    },
3619                }),
3620            },
3621        );
3622
3623        assert!(TimeZone::parse(b"America/New_York").is_err());
3624        assert!(TimeZone::parse(b":America/New_York").is_err());
3625    }
3626
3627    // See: https://github.com/BurntSushi/jiff/issues/407
3628    #[test]
3629    fn parse_empty_is_err() {
3630        assert!(TimeZone::parse(b"").is_err());
3631    }
3632
3633    // See: https://github.com/BurntSushi/jiff/issues/407
3634    #[test]
3635    fn parse_weird_is_err() {
3636        let s =
3637            b"AAAAAAAAAAAAAAACAAAAAAAAAAAAQA8AACAAAAAAAAAAAAAAAAACAAAAAAAAAAA";
3638        assert!(TimeZone::parse(s).is_err());
3639
3640        let s =
3641            b"<AAAAAAAAAAAAAAACAAAAAAAAAAAAQA>8<AACAAAAAAAAAAAAAAAAACAAAAAAAAAAA>";
3642        assert!(TimeZone::parse(s).is_err());
3643
3644        let s = b"PPPPPPPPPPPPPPPPPPPPnoofPPPAAA6DaPPPPPPPPPPPPPPPPPPPPPnoofPPPPP,n";
3645        assert!(TimeZone::parse(s).is_err());
3646
3647        let s = b"oooooooooovooooooooooooooooool9<ooooo2o-o-oooooookoorooooooooroo8";
3648        assert!(TimeZone::parse(s).is_err());
3649    }
3650
3651    #[test]
3652    fn parse_long() {
3653        let ts = Timestamp::new(1782939639, 0).unwrap();
3654
3655        let p = posix_time_zone("EST5EDT,M3.2.0,M11.1.0");
3656        assert_eq!(p.next_transition(ts).unwrap().abbreviation(), "EST");
3657        assert_eq!(p.previous_transition(ts).unwrap().abbreviation(), "EDT");
3658
3659        let p = posix_time_zone("ABCDEF5abcdef,M3.2.0,M11.1.0");
3660        assert_eq!(p.next_transition(ts).unwrap().abbreviation(), "ABCDEF");
3661        assert_eq!(
3662            p.previous_transition(ts).unwrap().abbreviation(),
3663            "abcdef"
3664        );
3665
3666        #[cfg(not(feature = "alloc"))]
3667        {
3668            let core_only_over_max = "ABCDEFGHIJ5abcdefghij,M3.2.0,M11.1.0";
3669            assert!(TimeZone::parse(core_only_over_max).is_err());
3670        }
3671
3672        #[cfg(feature = "alloc")]
3673        {
3674            let alloc_max = "\
3675                ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3676                ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3677                ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3678                ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3679                ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3680                ABCDE\
3681                5\
3682                abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3683                abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3684                abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3685                abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3686                abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3687                abcde\
3688                ,M3.2.0,M11.1.0\
3689            ";
3690            let p = posix_time_zone(alloc_max);
3691            assert_eq!(
3692                p.next_transition(ts).unwrap().abbreviation(),
3693                "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3694                 ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3695                 ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3696                 ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3697                 ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3698                 ABCDE\
3699                ",
3700            );
3701            assert_eq!(
3702                p.previous_transition(ts).unwrap().abbreviation(),
3703                "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3704                 abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3705                 abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3706                 abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3707                 abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3708                 abcde\
3709                ",
3710            );
3711
3712            let alloc_over_max = "\
3713                ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3714                ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3715                ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3716                ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3717                ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3718                ABCDEF\
3719                5\
3720                abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3721                abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3722                abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3723                abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3724                abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3725                abcdef\
3726                ,M3.2.0,M11.1.0\
3727            ";
3728            assert!(TimeZone::parse(alloc_over_max).is_err());
3729        }
3730    }
3731
3732    #[test]
3733    fn extremes() {
3734        assert!(TimeZone::parse(b"XXX25YYY,M3.2.0,M11.1.0").is_err());
3735        assert!(TimeZone::parse(b"XXX-25YYY,M3.2.0,M11.1.0").is_err());
3736        assert!(
3737            TimeZone::parse(b"XXX24:59:59YYY25:59:59,M3.2.0,M11.1.0").is_err()
3738        );
3739        // Weird, but actually possible if you omit the DST offset!
3740        assert!(
3741            TimeZone::parse(b"XXX-24:59:59YYY-25:59:59,M3.2.0,M11.1.0")
3742                .is_err()
3743        );
3744
3745        let p = TimeZone::parse(b"XXX24:59:59YYY,M3.2.0,M11.1.0").unwrap();
3746        // in std
3747        let ts = Timestamp::from_second(1783116302 + 6 * 30 * 86400).unwrap();
3748        assert_eq!(p.to_offset(ts), Offset::from_seconds(-89_999).unwrap());
3749        // in dst
3750        let ts = Timestamp::from_second(1783116302).unwrap();
3751        assert_eq!(p.to_offset(ts), Offset::from_seconds(-86_399).unwrap());
3752
3753        let p = TimeZone::parse(b"XXX-24:59:59YYY,M3.2.0,M11.1.0").unwrap();
3754        // in std
3755        let ts = Timestamp::from_second(1783116302 + 6 * 30 * 86400).unwrap();
3756        assert_eq!(p.to_offset(ts), Offset::from_seconds(89_999).unwrap());
3757        // in dst
3758        let ts = Timestamp::from_second(1783116302).unwrap();
3759        // And this is why `Offset::MAX` is set to the value it's at!
3760        assert_eq!(p.to_offset(ts), Offset::MAX);
3761    }
3762
3763    #[test]
3764    fn parse_posix_tz() {
3765        // We used to parse this and then error when we tried to
3766        // convert to a "reasonable" POSIX time zone with a DST
3767        // transition rule. We never actually used unreasonable POSIX
3768        // time zones and it was complicating the type definitions, so
3769        // now we just reject it outright.
3770        //
3771        // UPDATE: We now provide a way to inspect whether this happens
3772        // or not via a predicate on the error returned.
3773        assert!(
3774            TzEnv::parse("EST5EDT")
3775                .unwrap_err()
3776                .is_missing_dst_transition_rule()
3777        );
3778        assert!(
3779            TzEnv::parse("EST5EDT4")
3780                .unwrap_err()
3781                .is_missing_dst_transition_rule()
3782        );
3783
3784        let tz = TzEnv::parse(":EST5EDT").unwrap();
3785        assert_eq!(
3786            tz,
3787            TzEnv::Implementation(TimeZoneId::new("EST5EDT").unwrap())
3788        );
3789
3790        // We require implementation strings to be UTF-8, because we're
3791        // sensible.
3792        assert!(TzEnv::parse(b":EST5\xFFEDT").is_err());
3793    }
3794}