1/*!
2Implements POSIX time zone string parsing and transition handling.
34The `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.
1011Note 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]:
1617> 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.
2728Indeed, even [musl subscribes to this behavior][musl-env]. So that's what we do
29here too.
3031Note 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.
3435# IANA v3+ Support
3637While 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).
4546# `no-std` and `no-alloc` support
4748A 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.
5455POSIX 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.)
5859[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*/
6364use crate::{
65Timestamp,
66 civil::{Date, DateTime, Time, TimeSecond, Weekday},
67 tz::{
68Abbreviation, AmbiguousOffset, AmbiguousTimestamp, Offset, OffsetInfo,
69REASONABLE_ABBREVIATION_MAX, TimeZoneId, Transition,
70 },
71};
7273/// 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.
92Rule(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.
97Implementation(TimeZoneId),
98}
99100impl TzEnv {
101/// Parse a POSIX `TZ` environment variable string from the given bytes.
102pub fn parse<B: AsRef<[u8]>>(bytes: B) -> Result<TzEnv, ParseError> {
103let bytes = bytes.as_ref();
104if bytes.get(0) == Some(&b':') {
105let Ok(string) = core::str::from_utf8(&bytes[1..]) else {
106return Err(ParseErrorKind::TzEnvColonInvalidUtf8.into());
107 };
108let Some(smallstr) = TimeZoneId::new(string) else {
109return Err(ParseErrorKind::TzEnvColonTooBig.into());
110 };
111Ok(TzEnv::Implementation(smallstr))
112 } else {
113TimeZone::parse(bytes).map(TzEnv::Rule)
114 }
115 }
116117/// Parse a POSIX `TZ` environment variable string from the given `OsStr`.
118#[cfg(feature = "std")]
119pub fn parse_os_str<O: AsRef<std::ffi::OsStr>>(
120 osstr: O,
121 ) -> Result<TzEnv, ParseError> {
122let bytes = crate::util::os_str_bytes(osstr.as_ref())
123 .ok_or(ParseError::from(ParseErrorKind::TzEnvInvalidUtf8))?;
124TzEnv::parse(bytes)
125 }
126}
127128/// 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.
200pub std_abbrev: Abbreviation,
201/// The offset for standard time.
202pub std_offset: Offset,
203/// Whether there is any daylight saving time for this POSIX time zone.
204pub dst: Option<Dst>,
205}
206207/// 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.
212pub abbrev: Abbreviation,
213/// The offset from UTC that civil datetimes get when the daylight saving
214 /// time rule is satisfied.
215pub offset: Offset,
216/// The actual rule.
217pub rule: Rule,
218}
219220/// 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).
227pub start: DayTime,
228/// The end of the time zone transition (e.g., daylight saving time).
229pub end: DayTime,
230}
231232/// 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.
237pub date: Day,
238/// The civil time on the day when the offset for civil time changes.
239pub time: TransitionCivilTime,
240}
241242/// 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`.
248JulianOne(i16),
249/// Julian day in a year, counting for leap days.
250 ///
251 /// Valid range is `0..=365`.
252JulianZero(i16),
253/// The nth weekday of a month.
254WeekdayOfMonth {
255/// The month.
256 ///
257 /// Valid range is: `1..=12`.
258month: 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."
267week: i8,
268/// The weekday.
269weekday: Weekday,
270 },
271}
272273/// 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]`.
282pub second: i32,
283}
284285impl 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.
296pub fn parse<B: AsRef<[u8]>>(bytes: B) -> Result<TimeZone, ParseError> {
297let 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.
303let parser = Parser { ianav3plus: true, ..Parser::new(bytes) };
304parser.parse()
305 }
306307/// 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.
315pub fn parse_prefix<'b, B: AsRef<[u8]> + ?Sized>(
316 bytes: &'b B,
317 ) -> Result<(TimeZone, usize), ParseError> {
318let bytes = bytes.as_ref();
319let parser = Parser { ianav3plus: true, ..Parser::new(bytes) };
320parser.parse_prefix()
321 }
322}
323324impl 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.
332pub fn to_offset(&self, timestamp: Timestamp) -> Offset {
333if self.dst.is_none() {
334return self.std_offset;
335 }
336337let dt = timestamp.to_datetime(Offset::UTC);
338self.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 }
343344/// 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).
350pub fn to_offset_info(&self, timestamp: Timestamp) -> OffsetInfo {
351if self.dst.is_none() {
352return OffsetInfo {
353 offset: self.std_offset,
354 abbreviation: self.std_abbrev.clone(),
355 dst: super::Dst::No,
356 };
357 }
358359let dt = timestamp.to_datetime(Offset::UTC);
360self.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 }
373374/// 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).
385pub fn to_ambiguous_timestamp(&self, dt: DateTime) -> AmbiguousTimestamp {
386let year = dt.date().year();
387let std_offset = self.std_offset;
388let Some(dst_info) = self.dst_info_wall(year) else {
389return AmbiguousOffset::Unambiguous { offset: std_offset }
390 .into_ambiguous_timestamp(dt);
391 };
392let dst_offset = dst_info.offset();
393let 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.)
408let ambiguous_offset = if diff == 0 {
409if 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.
415if dst_info.in_dst(dt) {
416 AmbiguousOffset::Unambiguous { offset: dst_offset }
417 } else {
418let fold_start = dst_info.start.saturating_add_seconds(diff);
419let gap_end =
420dst_info.end.saturating_add_seconds(diff.saturating_neg());
421if 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.
439if !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.
446let gap_end = dst_info.start.saturating_add_seconds(diff);
447let fold_start =
448dst_info.end.saturating_add_seconds(diff.saturating_neg());
449if 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 };
464ambiguous_offset.into_ambiguous_timestamp(dt)
465 }
466467/// Returns the timestamp of the most recent time zone transition prior
468 /// to the timestamp given. If one doesn't exist, `None` is returned.
469pub fn previous_transition(
470&self,
471 timestamp: Timestamp,
472 ) -> Option<Transition> {
473let dt = timestamp.to_datetime(Offset::UTC);
474let dst_info = self.dst_info_utc(dt.date().year())?;
475let (earlier, later) = dst_info.ordered();
476let (prev, dst_info) = if dt > later {
477 (later, dst_info)
478 } else if dt > earlier {
479 (earlier, dst_info)
480 } else {
481let prev_year = if dt.date().year() == Date::MIN.year() {
482return None;
483 } else {
484dt.date().year() - 1
485};
486let dst_info = self.dst_info_utc(prev_year)?;
487let (_, later) = dst_info.ordered();
488 (later, dst_info)
489 };
490491let timestamp = prev.to_timestamp(Offset::UTC).ok()?;
492let dt = timestamp.to_datetime(Offset::UTC);
493let (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 };
498let info = OffsetInfo { offset, abbreviation, dst };
499Some(Transition { timestamp, info })
500 }
501502/// Returns the timestamp of the soonest time zone transition after the
503 /// timestamp given. If one doesn't exist, `None` is returned.
504pub fn next_transition(&self, timestamp: Timestamp) -> Option<Transition> {
505let dt = timestamp.to_datetime(Offset::UTC);
506let dst_info = self.dst_info_utc(dt.date().year())?;
507let (earlier, later) = dst_info.ordered();
508let (next, dst_info) = if dt < earlier {
509 (earlier, dst_info)
510 } else if dt < later {
511 (later, dst_info)
512 } else {
513let next_year = if dt.date().year() == Date::MAX.year() {
514return None;
515 } else {
516dt.date().year() + 1
517};
518let dst_info = self.dst_info_utc(next_year)?;
519let (earlier, _) = dst_info.ordered();
520 (earlier, dst_info)
521 };
522523let timestamp = next.to_timestamp(Offset::UTC).ok()?;
524let dt = timestamp.to_datetime(Offset::UTC);
525let (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 };
530let info = OffsetInfo { offset, abbreviation, dst };
531Some(Transition { timestamp, info })
532 }
533534/// 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.
538fn dst_info_utc(&self, year: i16) -> Option<DstInfo<'_>> {
539let dst = self.dst.as_ref()?;
540// DST time starts with respect to standard time, so offset it by the
541 // standard offset.
542let 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.
545let 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.
596if start.date().month() == 1
597&& start.date().day() == 1
598&& start.time() == Time::MIN599// NOTE: This should come last because it is potentially expensive.
600&& year601 != end.saturating_add_seconds(self.std_offset.seconds()).date().year()
602 {
603end = DateTime::from_parts(
604Date::new(year, 12, 31)
605 .expect("12/31 is valid for all valid years"),
606Time::MAX,
607 );
608 }
609Some(DstInfo { dst, start, end })
610 }
611612/// 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.
617fn dst_info_wall(&self, year: i16) -> Option<DstInfo<'_>> {
618let 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.
622let start = dst.rule.start.to_datetime(year, Offset::UTC);
623let end = dst.rule.end.to_datetime(year, Offset::UTC);
624Some(DstInfo { dst, start, end })
625 }
626627/// Returns the DST transition rule. This panics if this time zone doesn't
628 /// have DST.
629#[cfg(test)]
630fn rule(&self) -> &Rule {
631&self.dst.as_ref().unwrap().rule
632 }
633}
634635impl 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.
647fn to_datetime(&self, year: i16, offset: Offset) -> DateTime {
648let mkmin =
649 || DateTime::from_parts(Date::new(year, 1, 1).unwrap(), Time::MIN);
650let mkmax = || {
651DateTime::from_parts(Date::new(year, 12, 31).unwrap(), Time::MAX)
652 };
653let 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`.
657let offset = self.time.second - offset.seconds();
658// If the time goes negative or above 86400, then we might have
659 // to adjust our date.
660let days = offset.div_euclid(86400);
661let second = offset.rem_euclid(86400);
662663let Ok(date) = date.checked_add(days) else {
664return if offset < 0 { mkmin() } else { mkmax() };
665 };
666if date.year() < year {
667mkmin()
668 } else if date.year() > year {
669mkmax()
670 } else {
671// OK because we just did modulo 86400 above.
672let time = TimeSecond::new(second).unwrap().to_time();
673DateTime::from_parts(date, time)
674 }
675 }
676}
677678impl 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.
685fn to_date(&self, year: i16) -> Option<Date> {
686match *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.
691Some(
692Date::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?
706Date::from_day_of_year(year, day + 1).ok()
707 }
708 Day::WeekdayOfMonth { month, week, weekday } => {
709let first = Date::new(year, month, 1)
710 .expect("all valid year/month combinations support day 1");
711let week = if week == 5 { -1 } else { week };
712if 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!)
727Some(
728first729 .nth_weekday_of_month(week, weekday)
730 .expect("nth weekday always exists"),
731 )
732 }
733 }
734 }
735}
736737impl 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.
742pub const DEFAULT: TransitionCivilTime =
743TransitionCivilTime { second: 2 * 60 * 60 };
744}
745746/// 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.
751dst: &'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.
760start: 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.
769end: DateTime,
770}
771772impl<'a> DstInfo<'a> {
773/// Returns true if and only if the given civil datetime ought to be
774 /// considered in DST.
775fn in_dst(&self, utc_dt: DateTime) -> bool {
776if self.start <= self.end {
777self.start <= utc_dt && utc_dt < self.end
778 } else {
779 !(self.end <= utc_dt && utc_dt < self.start)
780 }
781 }
782783/// Returns the earlier and later times for this DST info.
784fn ordered(&self) -> (DateTime, DateTime) {
785if self.start <= self.end {
786 (self.start, self.end)
787 } else {
788 (self.end, self.start)
789 }
790 }
791792/// Returns the DST offset.
793fn offset(&self) -> Offset {
794self.dst.offset
795 }
796}
797798/// 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.
802tz: &'s [u8],
803/// The parser's current position in `tz`.
804pos: 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.
818ianav3plus: bool,
819}
820821impl<'s> Parser<'s> {
822/// Create a new parser for extracting a POSIX time zone from the given
823 /// bytes.
824fn new<B: ?Sized + AsRef<[u8]>>(tz: &'s B) -> Parser<'s> {
825Parser {
826 tz: tz.as_ref(),
827 pos: core::cell::Cell::new(0),
828 ianav3plus: false,
829 }
830 }
831832/// 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.
835fn parse(&self) -> Result<TimeZone, ParseError> {
836let (time_zone, len) = self.parse_prefix()?;
837if !self.tz[len..].is_empty() {
838return Err(ParseErrorKind::FoundRemaining.into());
839 }
840Ok(time_zone)
841 }
842843/// Parses a POSIX time zone from the current position of the parser and
844 /// returns the remaining input.
845fn parse_prefix(&self) -> Result<(TimeZone, usize), ParseError> {
846let time_zone = self.parse_posix_time_zone()?;
847Ok((time_zone, self.pos()))
848 }
849850/// 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
855fn parse_posix_time_zone(&self) -> Result<TimeZone, ParseError> {
856if self.is_done() {
857return Err(ParseErrorKind::Empty.into());
858 }
859let std_abbrev = self
860.parse_abbreviation()
861 .map_err(ParseErrorKind::AbbreviationStd)?;
862let std_offset =
863self.parse_posix_offset().map_err(ParseErrorKind::OffsetStd)?;
864let mut dst = None;
865if !self.is_done()
866 && (self.byte().is_ascii_alphabetic() || self.byte() == b'<')
867 {
868dst = Some(self.parse_posix_dst(std_offset)?);
869 }
870Ok(TimeZone { std_abbrev, std_offset, dst })
871 }
872873/// 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).
881fn parse_posix_dst(&self, std_offset: Offset) -> Result<Dst, ParseError> {
882let abbrev = self
883.parse_abbreviation()
884 .map_err(ParseErrorKind::AbbreviationDst)?;
885if self.is_done() {
886return 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.
895let mut offset = std_offset.checked_add(3600).unwrap();
896if self.byte() != b',' {
897offset = self
898.parse_posix_offset()
899 .map_err(ParseErrorKind::OffsetDst)?;
900if self.is_done() {
901return Err(ParseErrorKind::FoundDstNoRuleWithOffset.into());
902 }
903 }
904if self.byte() != b',' {
905return Err(ParseErrorKind::ExpectedCommaAfterDst.into());
906 }
907if !self.bump() {
908return Err(ParseErrorKind::FoundEndAfterComma.into());
909 }
910let rule = self.parse_rule().map_err(ParseErrorKind::Rule)?;
911Ok(Dst { abbrev, offset, rule })
912 }
913914/// 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.)
926fn parse_abbreviation(&self) -> Result<Abbreviation, AbbreviationError> {
927if self.byte() == b'<' {
928if !self.bump() {
929return Err(AbbreviationError::Quoted(
930 QuotedAbbreviationError::UnexpectedEndAfterOpening,
931 ));
932 }
933self.parse_quoted_abbreviation().map_err(AbbreviationError::Quoted)
934 } else {
935self.parse_unquoted_abbreviation()
936 .map_err(AbbreviationError::Unquoted)
937 }
938 }
939940/// 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.)
951fn parse_unquoted_abbreviation(
952&self,
953 ) -> Result<Abbreviation, UnquotedAbbreviationError> {
954let start = self.pos();
955for _ in 0.. {
956if !self.byte().is_ascii_alphabetic() {
957break;
958 }
959if self.pos() - start >= REASONABLE_ABBREVIATION_MAX {
960return Err(UnquotedAbbreviationError::TooLong);
961 }
962if !self.bump() {
963break;
964 }
965 }
966let end = self.pos();
967let 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.
975UnquotedAbbreviationError::InvalidUtf8
976 })?;
977if abbrev.len() < 3 {
978return Err(UnquotedAbbreviationError::TooShort);
979 }
980Abbreviation::new(abbrev).ok_or(UnquotedAbbreviationError::TooLong)
981 }
982983/// 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.)
994fn parse_quoted_abbreviation(
995&self,
996 ) -> Result<Abbreviation, QuotedAbbreviationError> {
997let start = self.pos();
998for _ in 0.. {
999if !self.byte().is_ascii_alphanumeric()
1000 && self.byte() != b'+'
1001&& self.byte() != b'-'
1002{
1003break;
1004 }
1005if self.pos() - start >= REASONABLE_ABBREVIATION_MAX {
1006return Err(QuotedAbbreviationError::TooLong);
1007 }
1008if !self.bump() {
1009break;
1010 }
1011 }
1012let end = self.pos();
1013let 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.
1021QuotedAbbreviationError::InvalidUtf8
1022 })?;
1023if self.is_done() {
1024return Err(QuotedAbbreviationError::UnexpectedEnd);
1025 }
1026if self.byte() != b'>' {
1027return Err(QuotedAbbreviationError::UnexpectedLastByte);
1028 }
1029self.bump();
1030if abbrev.len() < 3 {
1031return Err(QuotedAbbreviationError::TooShort);
1032 }
1033Abbreviation::new(abbrev).ok_or(QuotedAbbreviationError::TooLong)
1034 }
10351036/// 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.
1044fn parse_posix_offset(&self) -> Result<Offset, OffsetError> {
1045let sign = self.parse_optional_sign()?.unwrap_or(1);
1046let hour = self.parse_hour_posix()?;
1047let (mut minute, mut second) = (0, 0);
1048if self.maybe_byte() == Some(b':') {
1049if !self.bump() {
1050return Err(OffsetError::IncompleteMinutes);
1051 }
1052minute = self.parse_minute()?;
1053if self.maybe_byte() == Some(b':') {
1054if !self.bump() {
1055return Err(OffsetError::IncompleteSeconds);
1056 }
1057second = self.parse_second()?;
1058 }
1059 }
1060let mut offset = Offset::from_hours(hour).expect("hours are valid");
1061offset += i32::from(minute) * 60;
1062offset += i32::from(second);
1063// Yes, we flip the sign, because POSIX is backwards.
1064 // For example, `EST5` corresponds to `-05:00`.
1065if sign.is_positive() {
1066offset = -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.
1071if !(-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 );
1076Ok(offset)
1077 }
10781079/// 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.
1088fn parse_rule(&self) -> Result<Rule, RuleError> {
1089let start =
1090self.parse_posix_datetime().map_err(RuleError::DateTimeStart)?;
1091if self.maybe_byte() != Some(b',') || !self.bump() {
1092return Err(RuleError::ExpectedEnd);
1093 }
1094let end =
1095self.parse_posix_datetime().map_err(RuleError::DateTimeEnd)?;
1096Ok(Rule { start, end })
1097 }
10981099/// 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.
1107fn parse_posix_datetime(&self) -> Result<DayTime, DateTimeError> {
1108let mut daytime = DayTime {
1109 date: self.parse_posix_date()?,
1110 time: TransitionCivilTime::DEFAULT,
1111 };
1112if self.maybe_byte() != Some(b'/') {
1113return Ok(daytime);
1114 }
1115if !self.bump() {
1116return Err(DateTimeError::ExpectedTime);
1117 }
1118daytime.time = self.parse_posix_time()?;
1119Ok(daytime)
1120 }
11211122/// 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.
1135fn parse_posix_date(&self) -> Result<Day, DateError> {
1136match self.byte() {
1137b'J' => {
1138if !self.bump() {
1139return Err(DateError::ExpectedJulianNoLeap);
1140 }
1141Ok(Day::JulianOne(self.parse_posix_julian_day_no_leap()?))
1142 }
1143b'0'..=b'9' => {
1144Ok(Day::JulianZero(self.parse_posix_julian_day_with_leap()?))
1145 }
1146b'M' => {
1147if !self.bump() {
1148return Err(DateError::ExpectedMonthWeekWeekday);
1149 }
1150let (month, week, weekday) = self.parse_weekday_of_month()?;
1151Ok(Day::WeekdayOfMonth { month, week, weekday })
1152 }
1153_ => Err(DateError::UnexpectedByte),
1154 }
1155 }
11561157/// 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.
1163fn parse_posix_julian_day_no_leap(
1164&self,
1165 ) -> Result<i16, JulianNoLeapError> {
1166let number = self
1167.parse_number_with_upto_n_digits(3)
1168 .map_err(JulianNoLeapError::Parse)?;
1169let number =
1170 i16::try_from(number).map_err(|_| JulianNoLeapError::Range)?;
1171if !(1 <= number && number <= 365) {
1172return Err(JulianNoLeapError::Range);
1173 }
1174Ok(number)
1175 }
11761177/// 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.
1183fn parse_posix_julian_day_with_leap(
1184&self,
1185 ) -> Result<i16, JulianLeapError> {
1186let number = self
1187.parse_number_with_upto_n_digits(3)
1188 .map_err(JulianLeapError::Parse)?;
1189let number =
1190 i16::try_from(number).map_err(|_| JulianLeapError::Range)?;
1191if !(0 <= number && number <= 365) {
1192return Err(JulianLeapError::Range);
1193 }
1194Ok(number)
1195 }
11961197/// 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).
1206fn parse_weekday_of_month(
1207&self,
1208 ) -> Result<(i8, i8, Weekday), WeekdayOfMonthError> {
1209let month = self.parse_month()?;
1210if self.maybe_byte() != Some(b'.') {
1211return Err(WeekdayOfMonthError::ExpectedDotAfterMonth);
1212 }
1213if !self.bump() {
1214return Err(WeekdayOfMonthError::ExpectedWeekAfterMonth);
1215 }
1216let week = self.parse_week()?;
1217if self.maybe_byte() != Some(b'.') {
1218return Err(WeekdayOfMonthError::ExpectedDotAfterWeek);
1219 }
1220if !self.bump() {
1221return Err(WeekdayOfMonthError::ExpectedDayOfWeekAfterWeek);
1222 }
1223let weekday = self.parse_weekday()?;
1224Ok((month, week, weekday))
1225 }
12261227/// 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.
1233fn parse_posix_time(&self) -> Result<TransitionCivilTime, TimeError> {
1234let (sign, hour) = if self.ianav3plus {
1235let sign = self.parse_optional_sign()?.unwrap_or(1);
1236let hour = self.parse_hour_ianav3plus()?;
1237 (sign, hour)
1238 } else {
1239 (1, i16::from(self.parse_hour_posix()?))
1240 };
1241let (mut minute, mut second) = (0, 0);
1242if self.maybe_byte() == Some(b':') {
1243if !self.bump() {
1244return Err(TimeError::IncompleteMinutes);
1245 }
1246minute = self.parse_minute()?;
1247if self.maybe_byte() == Some(b':') {
1248if !self.bump() {
1249return Err(TimeError::IncompleteSeconds);
1250 }
1251second = self.parse_second()?;
1252 }
1253 }
1254let mut time = TransitionCivilTime { second: i32::from(hour) * 3600 };
1255time.second += i32::from(minute) * 60;
1256time.second += i32::from(second);
1257time.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.
1261if !(-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 );
1266Ok(time)
1267 }
12681269/// 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).
1274fn parse_month(&self) -> Result<i8, MonthError> {
1275let number = self
1276.parse_number_with_upto_n_digits(2)
1277 .map_err(MonthError::Parse)?;
1278let number = i8::try_from(number).map_err(|_| MonthError::Range)?;
1279if !(1 <= number && number <= 12) {
1280return Err(MonthError::Range);
1281 }
1282Ok(number)
1283 }
12841285/// 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.
1289fn parse_week(&self) -> Result<i8, WeekOfMonthError> {
1290let number = self
1291.parse_number_with_exactly_n_digits(1)
1292 .map_err(WeekOfMonthError::Parse)?;
1293let number =
1294 i8::try_from(number).map_err(|_| WeekOfMonthError::Range)?;
1295if !(1 <= number && number <= 5) {
1296return Err(WeekOfMonthError::Range);
1297 }
1298Ok(number)
1299 }
13001301/// 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.
1308fn parse_weekday(&self) -> Result<Weekday, WeekdayError> {
1309let number = self
1310.parse_number_with_exactly_n_digits(1)
1311 .map_err(WeekdayError::Parse)?;
1312let number = i8::try_from(number).map_err(|_| WeekdayError::Range)?;
13131314Weekday::from_sunday_zero_offset(number)
1315 .map_err(|_| WeekdayError::Range)
1316 }
13171318/// 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.
1329fn parse_hour_ianav3plus(&self) -> Result<i16, HourIanaError> {
1330// Callers should only be using this method when IANA v3+ parsing
1331 // is enabled.
1332if !self.ianav3plus {
::core::panicking::panic("assertion failed: self.ianav3plus")
};assert!(self.ianav3plus);
1333let number = self
1334.parse_number_with_upto_n_digits(3)
1335 .map_err(HourIanaError::Parse)?;
1336let number =
1337 i16::try_from(number).map_err(|_| HourIanaError::Range)?;
1338if !(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.
1342return Err(HourIanaError::Range);
1343 }
1344Ok(number)
1345 }
13461347/// 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.
1356fn parse_hour_posix(&self) -> Result<i8, HourPosixError> {
1357let number = self
1358.parse_number_with_upto_n_digits(2)
1359 .map_err(HourPosixError::Parse)?;
1360let number =
1361 i8::try_from(number).map_err(|_| HourPosixError::Range)?;
1362if !(0 <= number && number <= 24) {
1363return Err(HourPosixError::Range);
1364 }
1365Ok(number)
1366 }
13671368/// 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.
1375fn parse_minute(&self) -> Result<i8, MinuteError> {
1376let number = self
1377.parse_number_with_exactly_n_digits(2)
1378 .map_err(MinuteError::Parse)?;
1379let number = i8::try_from(number).map_err(|_| MinuteError::Range)?;
1380if !(0 <= number && number <= 59) {
1381return Err(MinuteError::Range);
1382 }
1383Ok(number)
1384 }
13851386/// 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.
1393fn parse_second(&self) -> Result<i8, SecondError> {
1394let number = self
1395.parse_number_with_exactly_n_digits(2)
1396 .map_err(SecondError::Parse)?;
1397let number = i8::try_from(number).map_err(|_| SecondError::Range)?;
1398if !(0 <= number && number <= 59) {
1399return Err(SecondError::Range);
1400 }
1401Ok(number)
1402 }
14031404/// 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.
1412fn parse_number_with_exactly_n_digits(
1413&self,
1414 n: usize,
1415 ) -> Result<i32, NumberError> {
1416if !(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");
1417let mut number: i32 = 0;
1418for _ in 0..n {
1419if self.is_done() {
1420return Err(NumberError::ExpectedLength);
1421 }
1422let byte = self.byte();
1423let digit = match byte.checked_sub(b'0') {
1424None => {
1425return Err(NumberError::InvalidDigit);
1426 }
1427Some(digit) if digit > 9 => {
1428return Err(NumberError::InvalidDigit);
1429 }
1430Some(digit) => {
1431if 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)?;
1439self.bump();
1440 }
1441Ok(number)
1442 }
14431444/// 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`).
1450fn parse_number_with_upto_n_digits(
1451&self,
1452 n: usize,
1453 ) -> Result<i32, NumberError> {
1454if !(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");
1455let mut number: i32 = 0;
1456for i in 0..n {
1457if self.is_done() || !self.byte().is_ascii_digit() {
1458if i == 0 {
1459return Err(NumberError::Empty);
1460 }
1461break;
1462 }
1463let 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)?;
1468self.bump();
1469 }
1470Ok(number)
1471 }
14721473/// 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()`.
1480fn parse_optional_sign(&self) -> Result<Option<i8>, OptionalSignError> {
1481if self.is_done() {
1482return Ok(None);
1483 }
1484Ok(match self.byte() {
1485b'-' => {
1486if !self.bump() {
1487return Err(OptionalSignError::ExpectedDigitAfterMinus);
1488 }
1489Some(-1)
1490 }
1491b'+' => {
1492if !self.bump() {
1493return Err(OptionalSignError::ExpectedDigitAfterPlus);
1494 }
1495Some(1)
1496 }
1497_ => None,
1498 })
1499 }
1500}
15011502/// 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.
1507fn bump(&self) -> bool {
1508if self.is_done() {
1509return false;
1510 }
1511self.pos.set(
1512self.pos().checked_add(1).expect("pos cannot overflow usize"),
1513 );
1514 !self.is_done()
1515 }
15161517/// Returns true if the next call to `bump` would return false.
1518fn is_done(&self) -> bool {
1519self.pos() == self.tz.len()
1520 }
15211522/// 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.
1526fn byte(&self) -> u8 {
1527self.tz[self.pos()]
1528 }
15291530/// Return the byte at the current position of the parser. If the TZ
1531 /// string has been exhausted, then this returns `None`.
1532fn maybe_byte(&self) -> Option<u8> {
1533self.tz.get(self.pos()).copied()
1534 }
15351536/// Return the current byte offset of the parser.
1537 ///
1538 /// The offset starts at `0` from the beginning of the TZ string.
1539fn pos(&self) -> usize {
1540self.pos.get()
1541 }
1542}
15431544/// 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}
15501551impl 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.
1564pub fn is_missing_dst_transition_rule(&self) -> bool {
1565#[allow(non_exhaustive_omitted_patterns)] match self.kind {
ParseErrorKind::FoundDstNoRule | ParseErrorKind::FoundDstNoRuleWithOffset
=> true,
_ => false,
}matches!(
1566self.kind,
1567 ParseErrorKind::FoundDstNoRule
1568 | ParseErrorKind::FoundDstNoRuleWithOffset
1569 )1570 }
1571}
15721573#[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
1590TzEnvInvalidUtf8,
1591}
15921593impl core::fmt::Displayfor ParseError {
1594fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1595use self::ParseErrorKind::*;
1596match self.kind {
1597AbbreviationDst(ref err) => {
1598 f.write_str("failed to parse DST time zone abbreviation: ")?;
1599 core::fmt::Display::fmt(err, f)
1600 }
1601AbbreviationStd(ref err) => {
1602 f.write_str(
1603"failed to parse standard time zone abbreviation: ",
1604 )?;
1605 core::fmt::Display::fmt(err, f)
1606 }
1607Empty => f.write_str(
1608"an empty string is not a valid POSIX time zone \
1609 transition rule",
1610 ),
1611ExpectedCommaAfterDst => f.write_str(
1612"expected `,` after parsing DST offset \
1613 in POSIX time zone string",
1614 ),
1615FoundDstNoRule => 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 ),
1621FoundDstNoRuleWithOffset => 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 ),
1627FoundEndAfterComma => f.write_str(
1628"after parsing DST offset in POSIX time zone string, \
1629 found end of string after a trailing `,`",
1630 ),
1631FoundRemaining => 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 ),
1636OffsetDst(ref err) => {
1637 f.write_str("failed to parse DST offset: ")?;
1638 core::fmt::Display::fmt(err, f)
1639 }
1640OffsetStd(ref err) => {
1641 f.write_str("failed to parse standard offset: ")?;
1642 core::fmt::Display::fmt(err, f)
1643 }
1644Rule(ref err) => core::fmt::Display::fmt(err, f),
1645TzEnvColonTooBig => {
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)?;
1652f.write_str(" bytes)")
1653 }
1654TzEnvColonInvalidUtf8 => {
1655f.write_str("IANA time zone identifier is invalid UTF-8")
1656 }
1657TzEnvInvalidUtf8 => f.write_str(
1658"POSIX transition rule or \
1659 IANA time zone identifier is invalid UTF-8",
1660 ),
1661 }
1662 }
1663}
16641665impl From<ParseErrorKind> for ParseError {
1666fn from(kind: ParseErrorKind) -> ParseError {
1667ParseError { kind }
1668 }
1669}
16701671#[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}
16811682impl core::fmt::Displayfor OffsetError {
1683fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1684use self::OffsetError::*;
1685match *self {
1686HourPosix(ref err) => core::fmt::Display::fmt(err, f),
1687IncompleteMinutes => f.write_str(
1688"incomplete time in \
1689 POSIX time zone string (missing minutes)",
1690 ),
1691IncompleteSeconds => f.write_str(
1692"incomplete time in \
1693 POSIX time zone string (missing seconds)",
1694 ),
1695Minute(ref err) => core::fmt::Display::fmt(err, f),
1696Second(ref err) => core::fmt::Display::fmt(err, f),
1697OptionalSign(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}
17071708impl From<HourPosixError> for OffsetError {
1709fn from(err: HourPosixError) -> OffsetError {
1710 OffsetError::HourPosix(err)
1711 }
1712}
17131714impl From<MinuteError> for OffsetError {
1715fn from(err: MinuteError) -> OffsetError {
1716 OffsetError::Minute(err)
1717 }
1718}
17191720impl From<OptionalSignError> for OffsetError {
1721fn from(err: OptionalSignError) -> OffsetError {
1722 OffsetError::OptionalSign(err)
1723 }
1724}
17251726impl From<SecondError> for OffsetError {
1727fn from(err: SecondError) -> OffsetError {
1728 OffsetError::Second(err)
1729 }
1730}
17311732#[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}
17391740impl core::fmt::Displayfor RuleError {
1741fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1742use self::RuleError::*;
1743match *self {
1744DateTimeEnd(ref err) => {
1745 f.write_str("failed to parse end of DST transition rule: ")?;
1746 core::fmt::Display::fmt(err, f)
1747 }
1748DateTimeStart(ref err) => {
1749 f.write_str("failed to parse start of DST transition rule: ")?;
1750 core::fmt::Display::fmt(err, f)
1751 }
1752ExpectedEnd => f.write_str(
1753"expected end of DST rule after parsing the start \
1754 of the DST rule",
1755 ),
1756 }
1757 }
1758}
17591760#[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}
17671768impl core::fmt::Displayfor DateTimeError {
1769fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1770use self::DateTimeError::*;
1771match *self {
1772Date(ref err) => core::fmt::Display::fmt(err, f),
1773ExpectedTime => f.write_str(
1774"expected time specification after `/` following a date
1775 specification in a POSIX time zone DST transition rule",
1776 ),
1777Time(ref err) => core::fmt::Display::fmt(err, f),
1778 }
1779 }
1780}
17811782impl From<DateError> for DateTimeError {
1783fn from(err: DateError) -> DateTimeError {
1784 DateTimeError::Date(err)
1785 }
1786}
17871788impl From<TimeError> for DateTimeError {
1789fn from(err: TimeError) -> DateTimeError {
1790 DateTimeError::Time(err)
1791 }
1792}
17931794#[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}
18041805impl core::fmt::Displayfor DateError {
1806fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1807use self::DateError::*;
1808match *self {
1809ExpectedJulianNoLeap => 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 ),
1814ExpectedMonthWeekWeekday => 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 ),
1819JulianLeap(ref err) => core::fmt::Display::fmt(err, f),
1820JulianNoLeap(ref err) => core::fmt::Display::fmt(err, f),
1821UnexpectedByte => 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 ),
1825WeekdayOfMonth(ref err) => core::fmt::Display::fmt(err, f),
1826 }
1827 }
1828}
18291830impl From<JulianLeapError> for DateError {
1831fn from(err: JulianLeapError) -> DateError {
1832 DateError::JulianLeap(err)
1833 }
1834}
18351836impl From<JulianNoLeapError> for DateError {
1837fn from(err: JulianNoLeapError) -> DateError {
1838 DateError::JulianNoLeap(err)
1839 }
1840}
18411842impl From<WeekdayOfMonthError> for DateError {
1843fn from(err: WeekdayOfMonthError) -> DateError {
1844 DateError::WeekdayOfMonth(err)
1845 }
1846}
18471848#[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}
18541855impl core::fmt::Displayfor JulianNoLeapError {
1856fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1857use self::JulianNoLeapError::*;
1858match *self {
1859Parse(ref err) => {
1860 f.write_str("invalid one-based Julian day digits: ")?;
1861 core::fmt::Display::fmt(err, f)
1862 }
1863Range => f.write_str(
1864"parsed one-based Julian day, but it's not in supported \
1865 range of `1..=365`",
1866 ),
1867 }
1868 }
1869}
18701871#[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}
18771878impl core::fmt::Displayfor JulianLeapError {
1879fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1880use self::JulianLeapError::*;
1881match *self {
1882Parse(ref err) => {
1883 f.write_str("invalid zero-based Julian day digits: ")?;
1884 core::fmt::Display::fmt(err, f)
1885 }
1886Range => f.write_str(
1887"parsed zero-based Julian day, but it's not in supported \
1888 range of `0..=365`",
1889 ),
1890 }
1891 }
1892}
18931894#[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}
19001901impl core::fmt::Displayfor AbbreviationError {
1902fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1903use self::AbbreviationError::*;
1904match *self {
1905Quoted(ref err) => core::fmt::Display::fmt(err, f),
1906Unquoted(ref err) => core::fmt::Display::fmt(err, f),
1907 }
1908 }
1909}
19101911#[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}
19181919impl core::fmt::Displayfor UnquotedAbbreviationError {
1920fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1921use self::UnquotedAbbreviationError::*;
1922match *self {
1923InvalidUtf8 => f.write_str(
1924"unquoted time zone abbreviation must be valid UTF-8",
1925 ),
1926TooLong => 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!(
1927f,
1928"expected unquoted time zone abbreviation with at most \
1929 {} bytes, but found an abbreviation that is longer",
1930 REASONABLE_ABBREVIATION_MAX,
1931 ),
1932TooShort => 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}
19391940#[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}
19501951impl core::fmt::Displayfor QuotedAbbreviationError {
1952fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1953use self::QuotedAbbreviationError::*;
1954match *self {
1955InvalidUtf8 => f.write_str(
1956"quoted time zone abbreviation must be valid UTF-8",
1957 ),
1958TooLong => 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!(
1959f,
1960"expected quoted time zone abbreviation with at most \
1961 {} bytes, but found an abbreviation that is longer",
1962 REASONABLE_ABBREVIATION_MAX,
1963 ),
1964TooShort => 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 ),
1968UnexpectedEnd => 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 ),
1973UnexpectedEndAfterOpening => 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 ),
1978UnexpectedLastByte => 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}
19861987#[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}
19981999impl core::fmt::Displayfor WeekdayOfMonthError {
2000fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2001use self::WeekdayOfMonthError::*;
2002match *self {
2003ExpectedDayOfWeekAfterWeek => f.write_str(
2004"expected day-of-week after week in POSIX time zone rule",
2005 ),
2006ExpectedDotAfterMonth => {
2007f.write_str("expected `.` after month in POSIX time zone rule")
2008 }
2009ExpectedWeekAfterMonth => f.write_str(
2010"expected week after month in POSIX time zone rule",
2011 ),
2012ExpectedDotAfterWeek => {
2013f.write_str("expected `.` after week in POSIX time zone rule")
2014 }
2015Month(ref err) => core::fmt::Display::fmt(err, f),
2016WeekOfMonth(ref err) => core::fmt::Display::fmt(err, f),
2017Weekday(ref err) => core::fmt::Display::fmt(err, f),
2018 }
2019 }
2020}
20212022impl From<MonthError> for WeekdayOfMonthError {
2023fn from(err: MonthError) -> WeekdayOfMonthError {
2024 WeekdayOfMonthError::Month(err)
2025 }
2026}
20272028impl From<WeekOfMonthError> for WeekdayOfMonthError {
2029fn from(err: WeekOfMonthError) -> WeekdayOfMonthError {
2030 WeekdayOfMonthError::WeekOfMonth(err)
2031 }
2032}
20332034impl From<WeekdayError> for WeekdayOfMonthError {
2035fn from(err: WeekdayError) -> WeekdayOfMonthError {
2036 WeekdayOfMonthError::Weekday(err)
2037 }
2038}
20392040#[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}
20512052impl core::fmt::Displayfor TimeError {
2053fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2054use self::TimeError::*;
2055match *self {
2056HourIana(ref err) => core::fmt::Display::fmt(err, f),
2057HourPosix(ref err) => core::fmt::Display::fmt(err, f),
2058IncompleteMinutes => f.write_str(
2059"incomplete time zone transition time in \
2060 POSIX time zone string (missing minutes)",
2061 ),
2062IncompleteSeconds => f.write_str(
2063"incomplete time zone transition time in \
2064 POSIX time zone string (missing seconds)",
2065 ),
2066Minute(ref err) => core::fmt::Display::fmt(err, f),
2067Second(ref err) => core::fmt::Display::fmt(err, f),
2068OptionalSign(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}
20772078impl From<HourIanaError> for TimeError {
2079fn from(err: HourIanaError) -> TimeError {
2080 TimeError::HourIana(err)
2081 }
2082}
20832084impl From<HourPosixError> for TimeError {
2085fn from(err: HourPosixError) -> TimeError {
2086 TimeError::HourPosix(err)
2087 }
2088}
20892090impl From<MinuteError> for TimeError {
2091fn from(err: MinuteError) -> TimeError {
2092 TimeError::Minute(err)
2093 }
2094}
20952096impl From<OptionalSignError> for TimeError {
2097fn from(err: OptionalSignError) -> TimeError {
2098 TimeError::OptionalSign(err)
2099 }
2100}
21012102impl From<SecondError> for TimeError {
2103fn from(err: SecondError) -> TimeError {
2104 TimeError::Second(err)
2105 }
2106}
21072108#[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}
21142115impl core::fmt::Displayfor MonthError {
2116fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2117use self::MonthError::*;
2118match *self {
2119Parse(ref err) => {
2120 f.write_str("invalid month digits: ")?;
2121 core::fmt::Display::fmt(err, f)
2122 }
2123Range => f.write_str(
2124"parsed month, but it's not in supported \
2125 range of `1..=12`",
2126 ),
2127 }
2128 }
2129}
21302131#[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}
21372138impl core::fmt::Displayfor WeekOfMonthError {
2139fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2140use self::WeekOfMonthError::*;
2141match *self {
2142Parse(ref err) => {
2143 f.write_str("invalid week-of-month digits: ")?;
2144 core::fmt::Display::fmt(err, f)
2145 }
2146Range => f.write_str(
2147"parsed week-of-month, but it's not in supported \
2148 range of `1..=5`",
2149 ),
2150 }
2151 }
2152}
21532154#[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}
21602161impl core::fmt::Displayfor WeekdayError {
2162fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2163use self::WeekdayError::*;
2164match *self {
2165Parse(ref err) => {
2166 f.write_str("invalid weekday digits: ")?;
2167 core::fmt::Display::fmt(err, f)
2168 }
2169Range => 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}
21762177#[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}
21832184impl core::fmt::Displayfor HourIanaError {
2185fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2186use self::HourIanaError::*;
2187match *self {
2188Parse(ref err) => {
2189 f.write_str("invalid hour digits: ")?;
2190 core::fmt::Display::fmt(err, f)
2191 }
2192Range => f.write_str(
2193"parsed hours, but it's not in supported \
2194 range of `-167..=167`",
2195 ),
2196 }
2197 }
2198}
21992200#[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}
22062207impl core::fmt::Displayfor HourPosixError {
2208fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2209use self::HourPosixError::*;
2210match *self {
2211Parse(ref err) => {
2212 f.write_str("invalid hour digits: ")?;
2213 core::fmt::Display::fmt(err, f)
2214 }
2215Range => f.write_str(
2216"parsed hours, but it's not in supported \
2217 range of `0..=24`",
2218 ),
2219 }
2220 }
2221}
22222223#[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}
22292230impl core::fmt::Displayfor MinuteError {
2231fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2232use self::MinuteError::*;
2233match *self {
2234Parse(ref err) => {
2235 f.write_str("invalid minute digits: ")?;
2236 core::fmt::Display::fmt(err, f)
2237 }
2238Range => f.write_str(
2239"parsed minutes, but it's not in supported \
2240 range of `0..=59`",
2241 ),
2242 }
2243 }
2244}
22452246#[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}
22522253impl core::fmt::Displayfor SecondError {
2254fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2255use self::SecondError::*;
2256match *self {
2257Parse(ref err) => {
2258 f.write_str("invalid second digits: ")?;
2259 core::fmt::Display::fmt(err, f)
2260 }
2261Range => f.write_str(
2262"parsed seconds, but it's not in supported \
2263 range of `0..=59`",
2264 ),
2265 }
2266 }
2267}
22682269#[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}
22772278impl core::fmt::Displayfor NumberError {
2279fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2280use self::NumberError::*;
2281match *self {
2282Empty => f.write_str("invalid number, no digits found"),
2283ExpectedLength => f.write_str(
2284"expected a fixed number of digits, \
2285 but found incorrect number",
2286 ),
2287InvalidDigit => f.write_str("expected digit in range `0..=9`"),
2288TooBig => f.write_str(
2289"parsed number too big to fit into a 32-bit signed integer",
2290 ),
2291 }
2292 }
2293}
22942295#[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}
23012302impl core::fmt::Displayfor OptionalSignError {
2303fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2304use self::OptionalSignError::*;
2305match *self {
2306ExpectedDigitAfterMinus => f.write_str(
2307"expected digit after `-` sign, \
2308 but got end of input",
2309 ),
2310ExpectedDigitAfterPlus => f.write_str(
2311"expected digit after `+` sign, \
2312 but got end of input",
2313 ),
2314 }
2315 }
2316}
23172318#[cfg(test)]
2319mod tests {
2320use crate::civil::date;
23212322use super::*;
23232324fn posix_time_zone(input: impl AsRef<[u8]>) -> TimeZone {
2325let input = input.as_ref();
2326let tz = TimeZone::parse(input).unwrap();
2327 tz
2328 }
23292330fn parser(s: &str) -> Parser<'_> {
2331 Parser::new(s)
2332 }
23332334fn astr(s: &'static str) -> Abbreviation {
2335 Abbreviation::array(s)
2336 }
23372338fn off(seconds: i32) -> Offset {
2339 Offset::from_seconds(seconds).unwrap()
2340 }
23412342#[test]
2343fn parse() {
2344let p = parser("NZST-12NZDT,J60,J300");
2345assert_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 );
23662367let p = Parser::new("NZST-12NZDT,J60,J300WAT");
2368assert!(p.parse().is_err());
2369 }
23702371#[test]
2372fn parse_posix_time_zone() {
2373let p = Parser::new("NZST-12NZDT,M9.5.0,M4.1.0/3");
2374assert_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 );
24032404let p = Parser::new("NZST-12NZDT,M9.5.0,M4.1.0/3WAT");
2405assert_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 );
24342435let p = Parser::new("NZST-12NZDT,J60,J300");
2436assert_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 );
24572458let p = Parser::new("NZST-12NZDT,J60,J300WAT");
2459assert_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 }
24812482#[test]
2483fn parse_posix_dst() {
2484let p = Parser::new("NZDT,M9.5.0,M4.1.0/3");
2485assert_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 );
25102511let p = Parser::new("NZDT,J60,J300");
2512assert_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 );
25292530let p = Parser::new("NZDT-7,J60,J300");
2531assert_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 );
25482549let p = Parser::new("NZDT+7,J60,J300");
2550assert_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 );
25672568let p = Parser::new("NZDT7,J60,J300");
2569assert_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 );
25862587let p = Parser::new("NZDT7,");
2588assert!(p.parse_posix_dst(off(12 * 60 * 60)).is_err());
25892590let p = Parser::new("NZDT7!");
2591assert!(p.parse_posix_dst(off(12 * 60 * 60)).is_err());
2592 }
25932594#[test]
2595fn parse_abbreviation() {
2596let p = Parser::new("ABC");
2597assert_eq!(p.parse_abbreviation().unwrap(), "ABC");
25982599let p = Parser::new("<ABC>");
2600assert_eq!(p.parse_abbreviation().unwrap(), "ABC");
26012602let p = Parser::new("<+09>");
2603assert_eq!(p.parse_abbreviation().unwrap(), "+09");
26042605let p = Parser::new("+09");
2606assert!(p.parse_abbreviation().is_err());
2607 }
26082609#[test]
2610fn parse_unquoted_abbreviation() {
2611let p = Parser::new("ABC");
2612assert_eq!(p.parse_unquoted_abbreviation().unwrap(), "ABC");
26132614let p = Parser::new("ABCXYZ");
2615assert_eq!(p.parse_unquoted_abbreviation().unwrap(), "ABCXYZ");
26162617let p = Parser::new("ABC123");
2618assert_eq!(p.parse_unquoted_abbreviation().unwrap(), "ABC");
26192620let tz = "a".repeat(6);
2621let p = Parser::new(&tz);
2622assert_eq!(p.parse_unquoted_abbreviation().unwrap(), &*tz);
26232624let p = Parser::new("a");
2625assert!(p.parse_unquoted_abbreviation().is_err());
26262627let p = Parser::new("ab");
2628assert!(p.parse_unquoted_abbreviation().is_err());
26292630let p = Parser::new("ab1");
2631assert!(p.parse_unquoted_abbreviation().is_err());
26322633let tz = "a".repeat(31);
2634#[cfg(feature = "alloc")]
2635{
2636let p = Parser::new(&tz);
2637assert_eq!(p.parse_unquoted_abbreviation().unwrap(), &*tz);
2638 }
2639#[cfg(not(feature = "alloc"))]
2640{
2641let p = Parser::new(&tz);
2642assert!(p.parse_unquoted_abbreviation().is_err());
2643 }
26442645let p = Parser::new(b"ab\xFFcd");
2646assert!(p.parse_unquoted_abbreviation().is_err());
2647 }
26482649#[test]
2650fn 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.
26542655let p = Parser::new("ABC>");
2656assert_eq!(p.parse_quoted_abbreviation().unwrap(), "ABC");
26572658let p = Parser::new("ABCXYZ>");
2659assert_eq!(p.parse_quoted_abbreviation().unwrap(), "ABCXYZ");
26602661let p = Parser::new("ABC>123");
2662assert_eq!(p.parse_quoted_abbreviation().unwrap(), "ABC");
26632664let p = Parser::new("ABC123>");
2665assert_eq!(p.parse_quoted_abbreviation().unwrap(), "ABC123");
26662667let p = Parser::new("ab1>");
2668assert_eq!(p.parse_quoted_abbreviation().unwrap(), "ab1");
26692670let p = Parser::new("+09>");
2671assert_eq!(p.parse_quoted_abbreviation().unwrap(), "+09");
26722673let p = Parser::new("-09>");
2674assert_eq!(p.parse_quoted_abbreviation().unwrap(), "-09");
26752676let tz = alloc::format!("{}>", "a".repeat(6));
2677let p = Parser::new(&tz);
2678assert_eq!(
2679 p.parse_quoted_abbreviation().unwrap(),
2680 tz.trim_end_matches(">")
2681 );
26822683let p = Parser::new("a>");
2684assert!(p.parse_quoted_abbreviation().is_err());
26852686let p = Parser::new("ab>");
2687assert!(p.parse_quoted_abbreviation().is_err());
26882689let tz = alloc::format!("{}>", "a".repeat(31));
2690#[cfg(feature = "alloc")]
2691{
2692let p = Parser::new(&tz);
2693assert_eq!(
2694 p.parse_quoted_abbreviation().unwrap(),
2695 tz.trim_end_matches(">")
2696 );
2697 }
2698#[cfg(not(feature = "alloc"))]
2699{
2700let p = Parser::new(&tz);
2701assert!(p.parse_quoted_abbreviation().is_err());
2702 }
27032704let p = Parser::new(b"ab\xFFcd>");
2705assert!(p.parse_quoted_abbreviation().is_err());
27062707let p = Parser::new("ABC");
2708assert!(p.parse_quoted_abbreviation().is_err());
27092710let p = Parser::new("ABC!>");
2711assert!(p.parse_quoted_abbreviation().is_err());
2712 }
27132714#[test]
2715fn parse_posix_offset() {
2716let p = Parser::new("5");
2717assert_eq!(p.parse_posix_offset().unwrap().seconds(), -5 * 60 * 60);
27182719let p = Parser::new("+5");
2720assert_eq!(p.parse_posix_offset().unwrap().seconds(), -5 * 60 * 60);
27212722let p = Parser::new("-5");
2723assert_eq!(p.parse_posix_offset().unwrap().seconds(), 5 * 60 * 60);
27242725let p = Parser::new("-12:34:56");
2726assert_eq!(
2727 p.parse_posix_offset().unwrap().seconds(),
272812 * 60 * 60 + 34 * 60 + 56,
2729 );
27302731let p = Parser::new("a");
2732assert!(p.parse_posix_offset().is_err());
27332734let p = Parser::new("-");
2735assert!(p.parse_posix_offset().is_err());
27362737let p = Parser::new("+");
2738assert!(p.parse_posix_offset().is_err());
27392740let p = Parser::new("-a");
2741assert!(p.parse_posix_offset().is_err());
27422743let p = Parser::new("+a");
2744assert!(p.parse_posix_offset().is_err());
27452746let p = Parser::new("-25");
2747assert!(p.parse_posix_offset().is_err());
27482749let p = Parser::new("+25");
2750assert!(p.parse_posix_offset().is_err());
27512752// 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.
2759let p = Parser { ianav3plus: true, ..Parser::new("25") };
2760assert!(p.parse_posix_offset().is_err());
2761let p = Parser { ianav3plus: true, ..Parser::new("+25") };
2762assert!(p.parse_posix_offset().is_err());
2763let p = Parser { ianav3plus: true, ..Parser::new("-25") };
2764assert!(p.parse_posix_offset().is_err());
2765 }
27662767#[test]
2768fn parse_rule() {
2769let p = Parser::new("M9.5.0,M4.1.0/3");
2770assert_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 );
27912792let p = Parser::new("M9.5.0");
2793assert!(p.parse_rule().is_err());
27942795let p = Parser::new(",M9.5.0,M4.1.0/3");
2796assert!(p.parse_rule().is_err());
27972798let p = Parser::new("M9.5.0/");
2799assert!(p.parse_rule().is_err());
28002801let p = Parser::new("M9.5.0,M4.1.0/");
2802assert!(p.parse_rule().is_err());
2803 }
28042805#[test]
2806fn parse_posix_datetime() {
2807let p = Parser::new("J1");
2808assert_eq!(
2809 p.parse_posix_datetime().unwrap(),
2810 DayTime {
2811 date: Day::JulianOne(1),
2812 time: TransitionCivilTime { second: 2 * 60 * 60 }
2813 },
2814 );
28152816let p = Parser::new("J1/3");
2817assert_eq!(
2818 p.parse_posix_datetime().unwrap(),
2819 DayTime {
2820 date: Day::JulianOne(1),
2821 time: TransitionCivilTime { second: 3 * 60 * 60 }
2822 },
2823 );
28242825let p = Parser::new("M4.1.0/3");
2826assert_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 );
28372838let p = Parser::new("1/3:45:05");
2839assert_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 );
28482849let p = Parser::new("a");
2850assert!(p.parse_posix_datetime().is_err());
28512852let p = Parser::new("J1/");
2853assert!(p.parse_posix_datetime().is_err());
28542855let p = Parser::new("1/");
2856assert!(p.parse_posix_datetime().is_err());
28572858let p = Parser::new("M4.1.0/");
2859assert!(p.parse_posix_datetime().is_err());
2860 }
28612862#[test]
2863fn parse_posix_date() {
2864let p = Parser::new("J1");
2865assert_eq!(p.parse_posix_date().unwrap(), Day::JulianOne(1));
2866let p = Parser::new("J365");
2867assert_eq!(p.parse_posix_date().unwrap(), Day::JulianOne(365));
28682869let p = Parser::new("0");
2870assert_eq!(p.parse_posix_date().unwrap(), Day::JulianZero(0));
2871let p = Parser::new("1");
2872assert_eq!(p.parse_posix_date().unwrap(), Day::JulianZero(1));
2873let p = Parser::new("365");
2874assert_eq!(p.parse_posix_date().unwrap(), Day::JulianZero(365));
28752876let p = Parser::new("M9.5.0");
2877assert_eq!(
2878 p.parse_posix_date().unwrap(),
2879 Day::WeekdayOfMonth {
2880 month: 9,
2881 week: 5,
2882 weekday: Weekday::Sunday
2883 },
2884 );
2885let p = Parser::new("M9.5.6");
2886assert_eq!(
2887 p.parse_posix_date().unwrap(),
2888 Day::WeekdayOfMonth {
2889 month: 9,
2890 week: 5,
2891 weekday: Weekday::Saturday
2892 },
2893 );
2894let p = Parser::new("M09.5.6");
2895assert_eq!(
2896 p.parse_posix_date().unwrap(),
2897 Day::WeekdayOfMonth {
2898 month: 9,
2899 week: 5,
2900 weekday: Weekday::Saturday
2901 },
2902 );
2903let p = Parser::new("M12.1.1");
2904assert_eq!(
2905 p.parse_posix_date().unwrap(),
2906 Day::WeekdayOfMonth {
2907 month: 12,
2908 week: 1,
2909 weekday: Weekday::Monday
2910 },
2911 );
29122913let p = Parser::new("a");
2914assert!(p.parse_posix_date().is_err());
29152916let p = Parser::new("j");
2917assert!(p.parse_posix_date().is_err());
29182919let p = Parser::new("m");
2920assert!(p.parse_posix_date().is_err());
29212922let p = Parser::new("n");
2923assert!(p.parse_posix_date().is_err());
29242925let p = Parser::new("J366");
2926assert!(p.parse_posix_date().is_err());
29272928let p = Parser::new("366");
2929assert!(p.parse_posix_date().is_err());
2930 }
29312932#[test]
2933fn parse_posix_julian_day_no_leap() {
2934let p = Parser::new("1");
2935assert_eq!(p.parse_posix_julian_day_no_leap().unwrap(), 1);
29362937let p = Parser::new("001");
2938assert_eq!(p.parse_posix_julian_day_no_leap().unwrap(), 1);
29392940let p = Parser::new("365");
2941assert_eq!(p.parse_posix_julian_day_no_leap().unwrap(), 365);
29422943let p = Parser::new("3655");
2944assert_eq!(p.parse_posix_julian_day_no_leap().unwrap(), 365);
29452946let p = Parser::new("0");
2947assert!(p.parse_posix_julian_day_no_leap().is_err());
29482949let p = Parser::new("366");
2950assert!(p.parse_posix_julian_day_no_leap().is_err());
2951 }
29522953#[test]
2954fn parse_posix_julian_day_with_leap() {
2955let p = Parser::new("0");
2956assert_eq!(p.parse_posix_julian_day_with_leap().unwrap(), 0);
29572958let p = Parser::new("1");
2959assert_eq!(p.parse_posix_julian_day_with_leap().unwrap(), 1);
29602961let p = Parser::new("001");
2962assert_eq!(p.parse_posix_julian_day_with_leap().unwrap(), 1);
29632964let p = Parser::new("365");
2965assert_eq!(p.parse_posix_julian_day_with_leap().unwrap(), 365);
29662967let p = Parser::new("3655");
2968assert_eq!(p.parse_posix_julian_day_with_leap().unwrap(), 365);
29692970let p = Parser::new("366");
2971assert!(p.parse_posix_julian_day_with_leap().is_err());
2972 }
29732974#[test]
2975fn parse_weekday_of_month() {
2976let p = Parser::new("9.5.0");
2977assert_eq!(
2978 p.parse_weekday_of_month().unwrap(),
2979 (9, 5, Weekday::Sunday)
2980 );
29812982let p = Parser::new("9.1.6");
2983assert_eq!(
2984 p.parse_weekday_of_month().unwrap(),
2985 (9, 1, Weekday::Saturday)
2986 );
29872988let p = Parser::new("09.1.6");
2989assert_eq!(
2990 p.parse_weekday_of_month().unwrap(),
2991 (9, 1, Weekday::Saturday)
2992 );
29932994let p = Parser::new("9");
2995assert!(p.parse_weekday_of_month().is_err());
29962997let p = Parser::new("9.");
2998assert!(p.parse_weekday_of_month().is_err());
29993000let p = Parser::new("9.5");
3001assert!(p.parse_weekday_of_month().is_err());
30023003let p = Parser::new("9.5.");
3004assert!(p.parse_weekday_of_month().is_err());
30053006let p = Parser::new("0.5.0");
3007assert!(p.parse_weekday_of_month().is_err());
30083009let p = Parser::new("13.5.0");
3010assert!(p.parse_weekday_of_month().is_err());
30113012let p = Parser::new("9.0.0");
3013assert!(p.parse_weekday_of_month().is_err());
30143015let p = Parser::new("9.6.0");
3016assert!(p.parse_weekday_of_month().is_err());
30173018let p = Parser::new("9.5.7");
3019assert!(p.parse_weekday_of_month().is_err());
3020 }
30213022#[test]
3023fn parse_posix_time() {
3024let p = Parser::new("5");
3025assert_eq!(p.parse_posix_time().unwrap().second, 5 * 60 * 60);
30263027let p = Parser::new("22");
3028assert_eq!(p.parse_posix_time().unwrap().second, 22 * 60 * 60);
30293030let p = Parser::new("02");
3031assert_eq!(p.parse_posix_time().unwrap().second, 2 * 60 * 60);
30323033let p = Parser::new("5:45");
3034assert_eq!(
3035 p.parse_posix_time().unwrap().second,
30365 * 60 * 60 + 45 * 60
3037);
30383039let p = Parser::new("5:45:12");
3040assert_eq!(
3041 p.parse_posix_time().unwrap().second,
30425 * 60 * 60 + 45 * 60 + 12
3043);
30443045let p = Parser::new("5:45:129");
3046assert_eq!(
3047 p.parse_posix_time().unwrap().second,
30485 * 60 * 60 + 45 * 60 + 12
3049);
30503051let p = Parser::new("5:45:12:");
3052assert_eq!(
3053 p.parse_posix_time().unwrap().second,
30545 * 60 * 60 + 45 * 60 + 12
3055);
30563057let p = Parser { ianav3plus: true, ..Parser::new("+5:45:12") };
3058assert_eq!(
3059 p.parse_posix_time().unwrap().second,
30605 * 60 * 60 + 45 * 60 + 12
3061);
30623063let p = Parser { ianav3plus: true, ..Parser::new("-5:45:12") };
3064assert_eq!(
3065 p.parse_posix_time().unwrap().second,
3066 -(5 * 60 * 60 + 45 * 60 + 12)
3067 );
30683069let p = Parser { ianav3plus: true, ..Parser::new("-167:45:12") };
3070assert_eq!(
3071 p.parse_posix_time().unwrap().second,
3072 -(167 * 60 * 60 + 45 * 60 + 12),
3073 );
30743075let p = Parser::new("25");
3076assert!(p.parse_posix_time().is_err());
30773078let p = Parser::new("12:2");
3079assert!(p.parse_posix_time().is_err());
30803081let p = Parser::new("12:");
3082assert!(p.parse_posix_time().is_err());
30833084let p = Parser::new("12:23:5");
3085assert!(p.parse_posix_time().is_err());
30863087let p = Parser::new("12:23:");
3088assert!(p.parse_posix_time().is_err());
30893090let p = Parser { ianav3plus: true, ..Parser::new("168") };
3091assert!(p.parse_posix_time().is_err());
30923093let p = Parser { ianav3plus: true, ..Parser::new("-168") };
3094assert!(p.parse_posix_time().is_err());
30953096let p = Parser { ianav3plus: true, ..Parser::new("+168") };
3097assert!(p.parse_posix_time().is_err());
3098 }
30993100#[test]
3101fn parse_month() {
3102let p = Parser::new("1");
3103assert_eq!(p.parse_month().unwrap(), 1);
31043105// 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.
3109let p = Parser::new("01");
3110assert_eq!(p.parse_month().unwrap(), 1);
31113112let p = Parser::new("12");
3113assert_eq!(p.parse_month().unwrap(), 12);
31143115let p = Parser::new("0");
3116assert!(p.parse_month().is_err());
31173118let p = Parser::new("00");
3119assert!(p.parse_month().is_err());
31203121let p = Parser::new("001");
3122assert!(p.parse_month().is_err());
31233124let p = Parser::new("13");
3125assert!(p.parse_month().is_err());
3126 }
31273128#[test]
3129fn parse_week() {
3130let p = Parser::new("1");
3131assert_eq!(p.parse_week().unwrap(), 1);
31323133let p = Parser::new("5");
3134assert_eq!(p.parse_week().unwrap(), 5);
31353136let p = Parser::new("55");
3137assert_eq!(p.parse_week().unwrap(), 5);
31383139let p = Parser::new("0");
3140assert!(p.parse_week().is_err());
31413142let p = Parser::new("6");
3143assert!(p.parse_week().is_err());
31443145let p = Parser::new("00");
3146assert!(p.parse_week().is_err());
31473148let p = Parser::new("01");
3149assert!(p.parse_week().is_err());
31503151let p = Parser::new("05");
3152assert!(p.parse_week().is_err());
3153 }
31543155#[test]
3156fn parse_weekday() {
3157let p = Parser::new("0");
3158assert_eq!(p.parse_weekday().unwrap(), Weekday::Sunday);
31593160let p = Parser::new("1");
3161assert_eq!(p.parse_weekday().unwrap(), Weekday::Monday);
31623163let p = Parser::new("6");
3164assert_eq!(p.parse_weekday().unwrap(), Weekday::Saturday);
31653166let p = Parser::new("00");
3167assert_eq!(p.parse_weekday().unwrap(), Weekday::Sunday);
31683169let p = Parser::new("06");
3170assert_eq!(p.parse_weekday().unwrap(), Weekday::Sunday);
31713172let p = Parser::new("60");
3173assert_eq!(p.parse_weekday().unwrap(), Weekday::Saturday);
31743175let p = Parser::new("7");
3176assert!(p.parse_weekday().is_err());
3177 }
31783179#[test]
3180fn parse_hour_posix() {
3181let p = Parser::new("5");
3182assert_eq!(p.parse_hour_posix().unwrap(), 5);
31833184let p = Parser::new("0");
3185assert_eq!(p.parse_hour_posix().unwrap(), 0);
31863187let p = Parser::new("00");
3188assert_eq!(p.parse_hour_posix().unwrap(), 0);
31893190let p = Parser::new("24");
3191assert_eq!(p.parse_hour_posix().unwrap(), 24);
31923193let p = Parser::new("100");
3194assert_eq!(p.parse_hour_posix().unwrap(), 10);
31953196let p = Parser::new("25");
3197assert!(p.parse_hour_posix().is_err());
31983199let p = Parser::new("99");
3200assert!(p.parse_hour_posix().is_err());
3201 }
32023203#[test]
3204fn parse_hour_ianav3plus() {
3205let new = |input| Parser { ianav3plus: true, ..Parser::new(input) };
32063207let p = new("5");
3208assert_eq!(p.parse_hour_ianav3plus().unwrap(), 5);
32093210let p = new("0");
3211assert_eq!(p.parse_hour_ianav3plus().unwrap(), 0);
32123213let p = new("00");
3214assert_eq!(p.parse_hour_ianav3plus().unwrap(), 0);
32153216let p = new("000");
3217assert_eq!(p.parse_hour_ianav3plus().unwrap(), 0);
32183219let p = new("24");
3220assert_eq!(p.parse_hour_ianav3plus().unwrap(), 24);
32213222let p = new("100");
3223assert_eq!(p.parse_hour_ianav3plus().unwrap(), 100);
32243225let p = new("1000");
3226assert_eq!(p.parse_hour_ianav3plus().unwrap(), 100);
32273228let p = new("167");
3229assert_eq!(p.parse_hour_ianav3plus().unwrap(), 167);
32303231let p = new("168");
3232assert!(p.parse_hour_ianav3plus().is_err());
32333234let p = new("999");
3235assert!(p.parse_hour_ianav3plus().is_err());
3236 }
32373238#[test]
3239fn parse_minute() {
3240let p = Parser::new("00");
3241assert_eq!(p.parse_minute().unwrap(), 0);
32423243let p = Parser::new("24");
3244assert_eq!(p.parse_minute().unwrap(), 24);
32453246let p = Parser::new("59");
3247assert_eq!(p.parse_minute().unwrap(), 59);
32483249let p = Parser::new("599");
3250assert_eq!(p.parse_minute().unwrap(), 59);
32513252let p = Parser::new("0");
3253assert!(p.parse_minute().is_err());
32543255let p = Parser::new("1");
3256assert!(p.parse_minute().is_err());
32573258let p = Parser::new("9");
3259assert!(p.parse_minute().is_err());
32603261let p = Parser::new("60");
3262assert!(p.parse_minute().is_err());
3263 }
32643265#[test]
3266fn parse_second() {
3267let p = Parser::new("00");
3268assert_eq!(p.parse_second().unwrap(), 0);
32693270let p = Parser::new("24");
3271assert_eq!(p.parse_second().unwrap(), 24);
32723273let p = Parser::new("59");
3274assert_eq!(p.parse_second().unwrap(), 59);
32753276let p = Parser::new("599");
3277assert_eq!(p.parse_second().unwrap(), 59);
32783279let p = Parser::new("0");
3280assert!(p.parse_second().is_err());
32813282let p = Parser::new("1");
3283assert!(p.parse_second().is_err());
32843285let p = Parser::new("9");
3286assert!(p.parse_second().is_err());
32873288let p = Parser::new("60");
3289assert!(p.parse_second().is_err());
3290 }
32913292#[test]
3293fn parse_number_with_exactly_n_digits() {
3294let p = Parser::new("1");
3295assert_eq!(p.parse_number_with_exactly_n_digits(1).unwrap(), 1);
32963297let p = Parser::new("12");
3298assert_eq!(p.parse_number_with_exactly_n_digits(2).unwrap(), 12);
32993300let p = Parser::new("123");
3301assert_eq!(p.parse_number_with_exactly_n_digits(2).unwrap(), 12);
33023303let p = Parser::new("");
3304assert!(p.parse_number_with_exactly_n_digits(1).is_err());
33053306let p = Parser::new("1");
3307assert!(p.parse_number_with_exactly_n_digits(2).is_err());
33083309let p = Parser::new("12");
3310assert!(p.parse_number_with_exactly_n_digits(3).is_err());
3311 }
33123313#[test]
3314fn parse_number_with_upto_n_digits() {
3315let p = Parser::new("1");
3316assert_eq!(p.parse_number_with_upto_n_digits(1).unwrap(), 1);
33173318let p = Parser::new("1");
3319assert_eq!(p.parse_number_with_upto_n_digits(2).unwrap(), 1);
33203321let p = Parser::new("12");
3322assert_eq!(p.parse_number_with_upto_n_digits(2).unwrap(), 12);
33233324let p = Parser::new("12");
3325assert_eq!(p.parse_number_with_upto_n_digits(3).unwrap(), 12);
33263327let p = Parser::new("123");
3328assert_eq!(p.parse_number_with_upto_n_digits(2).unwrap(), 12);
33293330let p = Parser::new("");
3331assert!(p.parse_number_with_upto_n_digits(1).is_err());
33323333let p = Parser::new("a");
3334assert!(p.parse_number_with_upto_n_digits(1).is_err());
3335 }
33363337#[test]
3338fn to_dst_civil_datetime_utc_range() {
3339let tz = posix_time_zone("WART4WARST,J1/-3,J365/20");
3340let 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.
3344dst: 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 };
3348assert_eq!(tz.dst_info_utc(2024), Some(dst_info));
33493350let tz = posix_time_zone("WART4WARST,J1/-4,J365/21");
3351let 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 };
3356assert_eq!(tz.dst_info_utc(2024), Some(dst_info));
33573358let tz = posix_time_zone("EST5EDT,M3.2.0,M11.1.0");
3359let 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 };
3364assert_eq!(tz.dst_info_utc(2024), Some(dst_info));
3365 }
33663367// See: https://github.com/BurntSushi/jiff/issues/386
3368#[test]
3369fn regression_permanent_dst() {
3370let tz = posix_time_zone("XXX-2<+01>-1,0/0,J365/23");
3371let 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 };
3376assert_eq!(tz.dst_info_utc(2087), Some(dst_info));
3377 }
33783379#[test]
3380fn reasonable() {
3381assert!(TimeZone::parse(b"EST5").is_ok());
3382assert!(TimeZone::parse(b"EST5EDT").is_err());
3383assert!(TimeZone::parse(b"EST5EDT,J1,J365").is_ok());
33843385let tz = posix_time_zone("EST24EDT,J1,J365");
3386assert_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 );
34073408let tz = posix_time_zone("EST-24EDT,J1,J365");
3409assert_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 }
34313432#[test]
3433fn 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.
3436let to_datetime = |daytime: &DayTime, year: i16| {
3437 daytime.to_datetime(year, Offset::UTC)
3438 };
34393440let tz = posix_time_zone("EST5EDT,J1,J365/5:12:34");
3441assert_eq!(
3442 to_datetime(&tz.rule().start, 2023),
3443 date(2023, 1, 1).at(2, 0, 0, 0),
3444 );
3445assert_eq!(
3446 to_datetime(&tz.rule().end, 2023),
3447 date(2023, 12, 31).at(5, 12, 34, 0),
3448 );
34493450let tz = posix_time_zone("EST+5EDT,M3.2.0/2,M11.1.0/2");
3451assert_eq!(
3452 to_datetime(&tz.rule().start, 2024),
3453 date(2024, 3, 10).at(2, 0, 0, 0),
3454 );
3455assert_eq!(
3456 to_datetime(&tz.rule().end, 2024),
3457 date(2024, 11, 3).at(2, 0, 0, 0),
3458 );
34593460let tz = posix_time_zone("EST+5EDT,M1.1.1,M12.5.2");
3461assert_eq!(
3462 to_datetime(&tz.rule().start, 2024),
3463 date(2024, 1, 1).at(2, 0, 0, 0),
3464 );
3465assert_eq!(
3466 to_datetime(&tz.rule().end, 2024),
3467 date(2024, 12, 31).at(2, 0, 0, 0),
3468 );
34693470let tz = posix_time_zone("EST5EDT,0/0,J365/25");
3471assert_eq!(
3472 to_datetime(&tz.rule().start, 2024),
3473 date(2024, 1, 1).at(0, 0, 0, 0),
3474 );
3475assert_eq!(
3476 to_datetime(&tz.rule().end, 2024),
3477 date(2024, 12, 31).at(23, 59, 59, 999_999_999),
3478 );
34793480let tz = posix_time_zone("XXX3EDT4,0/0,J365/23");
3481assert_eq!(
3482 to_datetime(&tz.rule().start, 2024),
3483 date(2024, 1, 1).at(0, 0, 0, 0),
3484 );
3485assert_eq!(
3486 to_datetime(&tz.rule().end, 2024),
3487 date(2024, 12, 31).at(23, 0, 0, 0),
3488 );
34893490let tz = posix_time_zone("XXX3EDT4,0/0,365");
3491assert_eq!(
3492 to_datetime(&tz.rule().end, 2023),
3493 date(2023, 12, 31).at(23, 59, 59, 999_999_999),
3494 );
3495assert_eq!(
3496 to_datetime(&tz.rule().end, 2024),
3497 date(2024, 12, 31).at(2, 0, 0, 0),
3498 );
34993500let tz = posix_time_zone("XXX3EDT4,J1/-167:59:59,J365/167:59:59");
3501assert_eq!(
3502 to_datetime(&tz.rule().start, 2024),
3503 date(2024, 1, 1).at(0, 0, 0, 0),
3504 );
3505assert_eq!(
3506 to_datetime(&tz.rule().end, 2024),
3507 date(2024, 12, 31).at(23, 59, 59, 999_999_999),
3508 );
3509 }
35103511#[test]
3512fn posix_date_time_spec_time() {
3513let tz = posix_time_zone("EST5EDT,J1,J365/5:12:34");
3514assert_eq!(tz.rule().start.time, TransitionCivilTime::DEFAULT);
3515assert_eq!(
3516 tz.rule().end.time,
3517 TransitionCivilTime { second: 5 * 60 * 60 + 12 * 60 + 34 },
3518 );
3519 }
35203521#[test]
3522fn posix_date_spec_to_date() {
3523let tz = posix_time_zone("EST+5EDT,M3.2.0/2,M11.1.0/2");
3524let start = tz.rule().start.date.to_date(2023);
3525assert_eq!(start, Some(date(2023, 3, 12)));
3526let end = tz.rule().end.date.to_date(2023);
3527assert_eq!(end, Some(date(2023, 11, 5)));
3528let start = tz.rule().start.date.to_date(2024);
3529assert_eq!(start, Some(date(2024, 3, 10)));
3530let end = tz.rule().end.date.to_date(2024);
3531assert_eq!(end, Some(date(2024, 11, 3)));
35323533let tz = posix_time_zone("EST+5EDT,J60,J365");
3534let start = tz.rule().start.date.to_date(2023);
3535assert_eq!(start, Some(date(2023, 3, 1)));
3536let end = tz.rule().end.date.to_date(2023);
3537assert_eq!(end, Some(date(2023, 12, 31)));
3538let start = tz.rule().start.date.to_date(2024);
3539assert_eq!(start, Some(date(2024, 3, 1)));
3540let end = tz.rule().end.date.to_date(2024);
3541assert_eq!(end, Some(date(2024, 12, 31)));
35423543let tz = posix_time_zone("EST+5EDT,59,365");
3544let start = tz.rule().start.date.to_date(2023);
3545assert_eq!(start, Some(date(2023, 3, 1)));
3546let end = tz.rule().end.date.to_date(2023);
3547assert_eq!(end, None);
3548let start = tz.rule().start.date.to_date(2024);
3549assert_eq!(start, Some(date(2024, 2, 29)));
3550let end = tz.rule().end.date.to_date(2024);
3551assert_eq!(end, Some(date(2024, 12, 31)));
35523553let tz = posix_time_zone("EST+5EDT,M1.1.1,M12.5.2");
3554let start = tz.rule().start.date.to_date(2024);
3555assert_eq!(start, Some(date(2024, 1, 1)));
3556let end = tz.rule().end.date.to_date(2024);
3557assert_eq!(end, Some(date(2024, 12, 31)));
3558 }
35593560#[test]
3561fn posix_time_spec_to_civil_time() {
3562let tz = posix_time_zone("EST5EDT,J1,J365/5:12:34");
3563assert_eq!(
3564 tz.dst.as_ref().unwrap().rule.start.time.second,
35652 * 60 * 60,
3566 );
3567assert_eq!(
3568 tz.dst.as_ref().unwrap().rule.end.time.second,
35695 * 60 * 60 + 12 * 60 + 34,
3570 );
35713572let tz = posix_time_zone("EST5EDT,J1/23:59:59,J365/24:00:00");
3573assert_eq!(
3574 tz.dst.as_ref().unwrap().rule.start.time.second,
357523 * 60 * 60 + 59 * 60 + 59,
3576 );
3577assert_eq!(
3578 tz.dst.as_ref().unwrap().rule.end.time.second,
357924 * 60 * 60,
3580 );
35813582let tz = posix_time_zone("EST5EDT,J1/-1,J365/167:00:00");
3583assert_eq!(
3584 tz.dst.as_ref().unwrap().rule.start.time.second,
3585 -1 * 60 * 60,
3586 );
3587assert_eq!(
3588 tz.dst.as_ref().unwrap().rule.end.time.second,
3589167 * 60 * 60,
3590 );
3591 }
35923593#[test]
3594fn parse_iana() {
3595// Ref: https://github.com/chronotope/chrono/issues/1153
3596let p = TimeZone::parse(b"CRAZY5SHORT,M12.5.0/50,0/2").unwrap();
3597assert_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 );
36223623assert!(TimeZone::parse(b"America/New_York").is_err());
3624assert!(TimeZone::parse(b":America/New_York").is_err());
3625 }
36263627// See: https://github.com/BurntSushi/jiff/issues/407
3628#[test]
3629fn parse_empty_is_err() {
3630assert!(TimeZone::parse(b"").is_err());
3631 }
36323633// See: https://github.com/BurntSushi/jiff/issues/407
3634#[test]
3635fn parse_weird_is_err() {
3636let s =
3637b"AAAAAAAAAAAAAAACAAAAAAAAAAAAQA8AACAAAAAAAAAAAAAAAAACAAAAAAAAAAA";
3638assert!(TimeZone::parse(s).is_err());
36393640let s =
3641b"<AAAAAAAAAAAAAAACAAAAAAAAAAAAQA>8<AACAAAAAAAAAAAAAAAAACAAAAAAAAAAA>";
3642assert!(TimeZone::parse(s).is_err());
36433644let s = b"PPPPPPPPPPPPPPPPPPPPnoofPPPAAA6DaPPPPPPPPPPPPPPPPPPPPPnoofPPPPP,n";
3645assert!(TimeZone::parse(s).is_err());
36463647let s = b"oooooooooovooooooooooooooooool9<ooooo2o-o-oooooookoorooooooooroo8";
3648assert!(TimeZone::parse(s).is_err());
3649 }
36503651#[test]
3652fn parse_long() {
3653let ts = Timestamp::new(1782939639, 0).unwrap();
36543655let p = posix_time_zone("EST5EDT,M3.2.0,M11.1.0");
3656assert_eq!(p.next_transition(ts).unwrap().abbreviation(), "EST");
3657assert_eq!(p.previous_transition(ts).unwrap().abbreviation(), "EDT");
36583659let p = posix_time_zone("ABCDEF5abcdef,M3.2.0,M11.1.0");
3660assert_eq!(p.next_transition(ts).unwrap().abbreviation(), "ABCDEF");
3661assert_eq!(
3662 p.previous_transition(ts).unwrap().abbreviation(),
3663"abcdef"
3664);
36653666#[cfg(not(feature = "alloc"))]
3667{
3668let core_only_over_max = "ABCDEFGHIJ5abcdefghij,M3.2.0,M11.1.0";
3669assert!(TimeZone::parse(core_only_over_max).is_err());
3670 }
36713672#[cfg(feature = "alloc")]
3673{
3674let 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 ";
3690let p = posix_time_zone(alloc_max);
3691assert_eq!(
3692 p.next_transition(ts).unwrap().abbreviation(),
3693"ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3694 ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3695 ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3696 ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3697 ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWX\
3698 ABCDE\
3699 ",
3700 );
3701assert_eq!(
3702 p.previous_transition(ts).unwrap().abbreviation(),
3703"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3704 abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3705 abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3706 abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3707 abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx\
3708 abcde\
3709 ",
3710 );
37113712let 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 ";
3728assert!(TimeZone::parse(alloc_over_max).is_err());
3729 }
3730 }
37313732#[test]
3733fn extremes() {
3734assert!(TimeZone::parse(b"XXX25YYY,M3.2.0,M11.1.0").is_err());
3735assert!(TimeZone::parse(b"XXX-25YYY,M3.2.0,M11.1.0").is_err());
3736assert!(
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!
3740assert!(
3741 TimeZone::parse(b"XXX-24:59:59YYY-25:59:59,M3.2.0,M11.1.0")
3742 .is_err()
3743 );
37443745let p = TimeZone::parse(b"XXX24:59:59YYY,M3.2.0,M11.1.0").unwrap();
3746// in std
3747let ts = Timestamp::from_second(1783116302 + 6 * 30 * 86400).unwrap();
3748assert_eq!(p.to_offset(ts), Offset::from_seconds(-89_999).unwrap());
3749// in dst
3750let ts = Timestamp::from_second(1783116302).unwrap();
3751assert_eq!(p.to_offset(ts), Offset::from_seconds(-86_399).unwrap());
37523753let p = TimeZone::parse(b"XXX-24:59:59YYY,M3.2.0,M11.1.0").unwrap();
3754// in std
3755let ts = Timestamp::from_second(1783116302 + 6 * 30 * 86400).unwrap();
3756assert_eq!(p.to_offset(ts), Offset::from_seconds(89_999).unwrap());
3757// in dst
3758let ts = Timestamp::from_second(1783116302).unwrap();
3759// And this is why `Offset::MAX` is set to the value it's at!
3760assert_eq!(p.to_offset(ts), Offset::MAX);
3761 }
37623763#[test]
3764fn 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.
3773assert!(
3774 TzEnv::parse("EST5EDT")
3775 .unwrap_err()
3776 .is_missing_dst_transition_rule()
3777 );
3778assert!(
3779 TzEnv::parse("EST5EDT4")
3780 .unwrap_err()
3781 .is_missing_dst_transition_rule()
3782 );
37833784let tz = TzEnv::parse(":EST5EDT").unwrap();
3785assert_eq!(
3786 tz,
3787 TzEnv::Implementation(TimeZoneId::new("EST5EDT").unwrap())
3788 );
37893790// We require implementation strings to be UTF-8, because we're
3791 // sensible.
3792assert!(TzEnv::parse(b":EST5\xFFEDT").is_err());
3793 }
3794}