1/*!
2This module provides facilities for parsing time zone offsets.
34The parsing here follows primarily from [RFC 3339] and [ISO 8601], but also
5from [Temporal's hybrid grammar].
67[RFC 3339]: https://www.rfc-editor.org/rfc/rfc3339
8[ISO 8601]: https://www.iso.org/iso-8601-date-and-time-format.html
9[Temporal's hybrid grammar]: https://tc39.es/proposal-temporal/#sec-temporal-iso8601grammar
10*/
1112// Here's the specific part of Temporal's grammar that is implemented below:
13//
14// DateTimeUTCOffset :::
15// UTCDesignator
16// UTCOffsetSubMinutePrecision
17//
18// TimeZoneUTCOffsetName :::
19// UTCOffsetMinutePrecision
20//
21// UTCDesignator ::: one of
22// Z z
23//
24// UTCOffsetSubMinutePrecision :::
25// UTCOffsetMinutePrecision
26// UTCOffsetWithSubMinuteComponents[+Extended]
27// UTCOffsetWithSubMinuteComponents[~Extended]
28//
29// UTCOffsetMinutePrecision :::
30// TemporalSign Hour
31// TemporalSign Hour TimeSeparator[+Extended] MinuteSecond
32// TemporalSign Hour TimeSeparator[~Extended] MinuteSecond
33//
34// UTCOffsetWithSubMinuteComponents[Extended] :::
35// TemporalSign Hour
36// TimeSeparator[?Extended] MinuteSecond
37// TimeSeparator[?Extended] MinuteSecond
38// TemporalDecimalFraction[opt]
39//
40// TimeSeparator[Extended] :::
41// [+Extended] :
42// [~Extended] [empty]
43//
44// TemporalSign :::
45// ASCIISign
46// <MINUS>
47//
48// ASCIISign ::: one of
49// + -
50//
51// Hour :::
52// 0 DecimalDigit
53// 1 DecimalDigit
54// 20
55// 21
56// 22
57// 23
58//
59// MinuteSecond :::
60// 0 DecimalDigit
61// 1 DecimalDigit
62// 2 DecimalDigit
63// 3 DecimalDigit
64// 4 DecimalDigit
65// 5 DecimalDigit
66//
67// DecimalDigit :: one of
68// 0 1 2 3 4 5 6 7 8 9
69//
70// TemporalDecimalFraction :::
71// TemporalDecimalSeparator DecimalDigit
72// TemporalDecimalSeparator DecimalDigit DecimalDigit
73// TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
74// TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
75// DecimalDigit
76// TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
77// DecimalDigit DecimalDigit
78// TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
79// DecimalDigit DecimalDigit DecimalDigit
80// TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
81// DecimalDigit DecimalDigit DecimalDigit
82// DecimalDigit
83// TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
84// DecimalDigit DecimalDigit DecimalDigit
85// DecimalDigit DecimalDigit
86// TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
87// DecimalDigit DecimalDigit DecimalDigit
88// DecimalDigit DecimalDigit DecimalDigit
89// TemporalDecimalSeparator ::: one of
90// . ,
91//
92// The quick summary of the above is that offsets up to nanosecond precision
93// are supported. The general format is `{+,-}HH[:MM[:SS[.NNNNNNNNN]]]`. But
94// ISO 8601 extended or basic formats are also supported. For example, the
95// basic format `-0530` is equivalent to the extended format `-05:30`.
96//
97// Note that even though we support parsing up to nanosecond precision, Jiff
98// currently only supports offsets up to second precision. I don't think there
99// is any real practical need for any greater precision, but I don't think it
100// would be too hard to switch an `Offset` from an `i32` representation in
101// seconds to a `i64` representation in nanoseconds. (Since it only needs to
102// support a span of time of about 52 hours or so.)
103104use jcore::{bounds::Sign, constantsas c};
105106use crate::{
107 error::{Error, ErrorContext, fmt::offset::Erroras E},
108 fmt::{
109Parsed,
110buffer::ArrayBuffer,
111 temporal::{PiecesNumericOffset, PiecesOffset},
112util::parse_temporal_fraction,
113 },
114tz::Offset,
115 util::{b, parse},
116};
117118/// An offset that has been parsed from a datetime string.
119///
120/// This represents either a Zulu offset (corresponding to UTC with an unknown
121/// time zone offset), or a specific numeric offset given in hours, minutes,
122/// seconds and nanoseconds (with everything except hours being optional).
123#[derive(#[automatically_derived]impl ::core::fmt::Debug for ParsedOffset {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"ParsedOffset kind", &&self.kind)
}
}Debug)]
124pub(crate) struct ParsedOffset {
125/// The kind of offset parsed.
126kind: ParsedOffsetKind,
127}
128129impl ParsedOffset {
130/// Convert a parsed offset into a Jiff offset.
131 ///
132 /// If the offset was parsed from a Zulu designator, then the offset
133 /// returned is indistinguishable from `+00` or `-00`.
134 ///
135 /// # Errors
136 ///
137 /// A variety of parsing errors are possible.
138 ///
139 /// Also, beyond normal range checks on the allowed components of a UTC
140 /// offset, this does rounding based on the fractional nanosecond part. As
141 /// a result, if the parsed value would be rounded to a value not in bounds
142 /// for a Jiff offset, this returns an error.
143pub(crate) fn to_offset(&self) -> Result<Offset, Error> {
144match self.kind {
145 ParsedOffsetKind::Zulu => Ok(Offset::UTC),
146 ParsedOffsetKind::Numeric(ref numeric) => numeric.to_offset(),
147 }
148 }
149150/// Convert a parsed offset to a more structured representation.
151 ///
152 /// This is like `to_offset`, but preserves `Z` and `-00:00` versus
153 /// `+00:00`. This does still attempt to create an `Offset`, and that
154 /// construction can fail.
155pub(crate) fn to_pieces_offset(&self) -> Result<PiecesOffset, Error> {
156match self.kind {
157 ParsedOffsetKind::Zulu => Ok(PiecesOffset::Zulu),
158 ParsedOffsetKind::Numeric(ref numeric) => {
159let mut off = PiecesNumericOffset::from(numeric.to_offset()?);
160if numeric.sign.is_negative() {
161off = off.with_negative_zero();
162 }
163Ok(PiecesOffset::from(off))
164 }
165 }
166 }
167168/// Whether this parsed offset corresponds to Zulu time or not.
169 ///
170 /// This is useful in error reporting for parsing civil times. Namely, we
171 /// report an error when parsing a civil time with a Zulu offset since it
172 /// is almost always the wrong thing to do.
173pub(crate) fn is_zulu(&self) -> bool {
174#[allow(non_exhaustive_omitted_patterns)] match self.kind {
ParsedOffsetKind::Zulu => true,
_ => false,
}matches!(self.kind, ParsedOffsetKind::Zulu)175 }
176177/// Whether the parsed offset had an explicit sub-minute component or not.
178pub(crate) fn has_subminute(&self) -> bool {
179let ParsedOffsetKind::Numeric(ref numeric) = self.kind else {
180return false;
181 };
182numeric.seconds.is_some()
183 }
184}
185186impl core::fmt::Displayfor ParsedOffset {
187fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
188match self.kind {
189 ParsedOffsetKind::Zulu => f.write_str("Z"),
190 ParsedOffsetKind::Numeric(ref numeric) => {
191 core::fmt::Display::fmt(numeric, f)
192 }
193 }
194 }
195}
196197/// The kind of a parsed offset.
198#[derive(#[automatically_derived]impl ::core::fmt::Debug for ParsedOffsetKind {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Zulu => ::core::fmt::Formatter::write_str(f, "Zulu"),
Self::Numeric(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Numeric", &__self_0),
}
}
}Debug)]
199enum ParsedOffsetKind {
200/// The zulu offset, corresponding to UTC in a context where the offset for
201 /// civil time is unknown or unavailable.
202Zulu,
203/// The specific numeric offset.
204Numeric(Numeric),
205}
206207/// A numeric representation of a UTC offset.
208struct Numeric {
209/// The sign that was parsed from the numeric UTC offset. This is always
210 /// either `1` or `-1`, never `0`.
211sign: Sign,
212/// The hours component. This is non-optional because every UTC offset must
213 /// have at least hours.
214hours: i8,
215/// The minutes component.
216minutes: Option<i8>,
217/// The seconds component. This is only possible when subminute resolution
218 /// is enabled.
219seconds: Option<i8>,
220/// The nanoseconds fractional component. This is only possible when
221 /// subminute resolution is enabled.
222nanoseconds: Option<i32>,
223}
224225impl Numeric {
226/// Convert a parsed numeric offset into a Jiff offset.
227 ///
228 /// This does rounding based on the fractional nanosecond part. As a
229 /// result, if the parsed value would be rounded to a value not in bounds
230 /// for a Jiff offset, this returns an error.
231fn to_offset(&self) -> Result<Offset, Error> {
232let mut seconds = i32::from(self.hours) * c::SECS_PER_HOUR_32;
233if let Some(part_minutes) = self.minutes {
234seconds += i32::from(part_minutes) * c::SECS_PER_MIN_32;
235 }
236if let Some(part_seconds) = self.seconds {
237seconds += i32::from(part_seconds);
238 }
239if let Some(part_nanoseconds) = self.nanoseconds {
240if part_nanoseconds >= 500_000_000 {
241seconds += 1;
242 }
243 }
244// This can only fail if rounding because of a fractional second
245 // would lead to a number of seconds that is out of bounds. In which
246 // case, we report it as a precision loss.
247Ok(Offset::from_seconds(self.sign * seconds)
248 .map_err(|_| E::PrecisionLoss)?)
249 }
250}
251252// This impl is just used for error messages when converting a `Numeric` to an
253// `Offset` fails.
254impl core::fmt::Displayfor Numeric {
255fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
256let mut buf = ArrayBuffer::<19>::default();
257let mut bbuf = buf.as_borrowed();
258259bbuf.write_ascii_char(if self.sign.is_negative() {
260b'-'
261} else {
262b'+'
263});
264bbuf.write_int_pad2(self.hours.unsigned_abs());
265if let Some(minutes) = self.minutes {
266bbuf.write_ascii_char(b':');
267bbuf.write_int_pad2(minutes.unsigned_abs());
268 }
269if let Some(seconds) = self.seconds {
270if self.minutes.is_none() {
271bbuf.write_str(":00");
272 }
273bbuf.write_ascii_char(b':');
274bbuf.write_int_pad2(seconds.unsigned_abs());
275 }
276if let Some(nanos) = self.nanoseconds {
277if nanos != 0 {
278if self.minutes.is_none() {
279bbuf.write_str(":00");
280 }
281if self.seconds.is_none() {
282bbuf.write_str(":00");
283 }
284bbuf.write_ascii_char(b'.');
285bbuf.write_fraction(None, nanos.unsigned_abs());
286 }
287 }
288f.write_str(bbuf.filled())
289 }
290}
291292// We give a succinct Debug impl (identical to Display) to make snapshot
293// testing a bit nicer.
294impl core::fmt::Debugfor Numeric {
295fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
296 core::fmt::Display::fmt(self, f)
297 }
298}
299300/// A parser for UTC offsets.
301///
302/// At time of writing, the typical configuration for offset parsing is to
303/// enable Zulu support and subminute precision. But when parsing zoned
304/// datetimes, and specifically, offsets within time zone annotations (the RFC
305/// 9557 extension to RFC 3339), then neither zulu nor subminute support are
306/// enabled.
307///
308/// N.B. I'm not actually totally clear on why zulu/subminute aren't allowed in
309/// time zone annotations, but that's what Temporal's grammar seems to dictate.
310/// One might argue that this is what RFCs 3339 and 9557 require, but the
311/// Temporal grammar is already recognizing a superset anyway.
312#[derive(#[automatically_derived]impl ::core::fmt::Debug for Parser {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_fields_finish(f,
"Parser zulu require_minute require_second subminute subsecond colon",
&[&self.zulu, &self.require_minute, &self.require_second,
&self.subminute, &self.subsecond, &&self.colon])
}
}Debug)]
313pub(crate) struct Parser {
314 zulu: bool,
315 require_minute: bool,
316 require_second: bool,
317 subminute: bool,
318 subsecond: bool,
319 colon: Colon,
320}
321322impl Parser {
323/// Create a new UTC offset parser with the default configuration.
324pub(crate) const fn new() -> Parser {
325Parser {
326 zulu: true,
327 require_minute: false,
328 require_second: false,
329 subminute: true,
330 subsecond: true,
331 colon: Colon::Optional,
332 }
333 }
334335/// When enabled, the `z` and `Z` designators are recognized as a "zulu"
336 /// indicator for UTC when the civil time offset is unknown or unavailable.
337 ///
338 /// When disabled, neither `z` nor `Z` will be recognized and a parser
339 /// error will occur if one is found.
340 ///
341 /// This is enabled by default.
342pub(crate) const fn zulu(self, yes: bool) -> Parser {
343Parser { zulu: yes, ..self }
344 }
345346/// When enabled, the minute component of a time zone offset is required.
347 /// If no minutes are found, then an error is returned.
348 ///
349 /// This is disabled by default.
350pub(crate) const fn require_minute(self, yes: bool) -> Parser {
351Parser { require_minute: yes, ..self }
352 }
353354/// When enabled, the second component of a time zone offset is required.
355 /// If no seconds (or minutes) are found, then an error is returned.
356 ///
357 /// When `subminute` is disabled, this setting has no effect.
358 ///
359 /// This is disabled by default.
360pub(crate) const fn require_second(self, yes: bool) -> Parser {
361Parser { require_second: yes, ..self }
362 }
363364/// When enabled, offsets with precision greater than integral minutes
365 /// are supported. Specifically, when enabled, nanosecond precision is
366 /// supported.
367 ///
368 /// When disabled, offsets must be integral minutes. And the `subsecond`
369 /// option is ignored.
370pub(crate) const fn subminute(self, yes: bool) -> Parser {
371Parser { subminute: yes, ..self }
372 }
373374/// When enabled, offsets with precision greater than integral seconds
375 /// are supported. Specifically, when enabled, nanosecond precision is
376 /// supported. Note though that when a fractional second is found, it is
377 /// used to round to the nearest second. (Jiff's `Offset` type only has
378 /// second resolution.)
379 ///
380 /// When disabled, offsets must be integral seconds (or integrate minutes
381 /// if the `subminute` option is disabled as well).
382 ///
383 /// This is ignored if `subminute` is disabled.
384pub(crate) const fn subsecond(self, yes: bool) -> Parser {
385Parser { subsecond: yes, ..self }
386 }
387388/// Sets how to handle parsing of colons in a time zone offset.
389 ///
390 /// This is set to `Colon::Optional` by default.
391pub(crate) const fn colon(self, colon: Colon) -> Parser {
392Parser { colon, ..self }
393 }
394395/// Parse an offset from the beginning of `input`.
396 ///
397 /// If no offset could be found or it was otherwise invalid, then an error
398 /// is returned.
399 ///
400 /// In general, parsing stops when, after all required components are seen,
401 /// an optional component is not present (either because of the end of the
402 /// input or because of a character that cannot possibly begin said optional
403 /// component). This does mean that there are some corner cases where error
404 /// messages will not be as good as they possibly can be. But there are
405 /// two exceptions here:
406 ///
407 /// 1. When Zulu support is disabled and a `Z` or `z` are found, then an
408 /// error is returned indicating that `Z` was recognized but specifically
409 /// not allowed.
410 /// 2. When subminute precision is disabled and a `:` is found after the
411 /// minutes component, then an error is returned indicating that the
412 /// seconds component was recognized but specifically not allowed.
413 ///
414 /// Otherwise, for example, if `input` is `-0512:34`, then the `-0512`
415 /// will be parsed as `-5 hours, 12 minutes` with an offset of `5`.
416 /// Presumably, whatever higher level parser is invoking this routine will
417 /// then see an unexpected `:`. But it's likely that a better error message
418 /// would call out the fact that mixed basic and extended formats (from
419 /// ISO 8601) aren't allowed, and that the offset needs to be written as
420 /// either `-05:12:34` or `-051234`. But... these are odd corner cases, so
421 /// we abide them.
422pub(crate) fn parse<'i>(
423&self,
424mut input: &'i [u8],
425 ) -> Result<Parsed<'i, ParsedOffset>, Error> {
426if input.is_empty() {
427return Err(Error::from(E::EndOfInput));
428 }
429430if input[0] == b'Z' || input[0] == b'z' {
431if !self.zulu {
432return Err(Error::from(E::UnexpectedLetterOffsetNoZulu(
433input[0],
434 )));
435 }
436input = &input[1..];
437let value = ParsedOffset { kind: ParsedOffsetKind::Zulu };
438return Ok(Parsed { value, input });
439 }
440let Parsed { value: numeric, input } = self.parse_numeric(input)?;
441let value = ParsedOffset { kind: ParsedOffsetKind::Numeric(numeric) };
442Ok(Parsed { value, input })
443 }
444445/// Like `parse`, but will return `None` if `input` cannot possibly start
446 /// with an offset.
447 ///
448 /// Basically, if `input` is empty, or is not one of `z`, `Z`, `+` or `-`
449 /// then this returns `None`.
450#[cfg_attr(feature = "perf-inline", inline(always))]
451pub(crate) fn parse_optional<'i>(
452&self,
453 input: &'i [u8],
454 ) -> Result<Parsed<'i, Option<ParsedOffset>>, Error> {
455let Some(first) = input.first().copied() else {
456return Ok(Parsed { value: None, input });
457 };
458if !#[allow(non_exhaustive_omitted_patterns)] match first {
b'z' | b'Z' | b'+' | b'-' => true,
_ => false,
}matches!(first, b'z' | b'Z' | b'+' | b'-') {
459return Ok(Parsed { value: None, input });
460 }
461let Parsed { value, input } = self.parse(input)?;
462Ok(Parsed { value: Some(value), input })
463 }
464465/// Parses a numeric offset from the beginning of `input`.
466 ///
467 /// The beginning of the input is expected to start with a `+` or a `-`.
468 /// Any other case (including an empty string) will result in an error.
469#[cfg_attr(feature = "perf-inline", inline(always))]
470fn parse_numeric<'i>(
471&self,
472 input: &'i [u8],
473 ) -> Result<Parsed<'i, Numeric>, Error> {
474// Parse sign component.
475let Parsed { value: sign, input } =
476self.parse_sign(input).context(E::InvalidSign)?;
477478// Parse hours component.
479let Parsed { value: hours, input } =
480self.parse_hours(input).context(E::InvalidHours)?;
481let extended = match self.colon {
482 Colon::Optional => input.starts_with(b":"),
483 Colon::Required => {
484if !input.is_empty() && !input.starts_with(b":") {
485return Err(Error::from(E::NoColonAfterHours));
486 }
487true
488}
489 Colon::Absent => {
490if !input.is_empty() && input.starts_with(b":") {
491return Err(Error::from(E::ColonAfterHours));
492 }
493false
494}
495 };
496497// Start building up our numeric offset value.
498let mut numeric = Numeric {
499sign,
500hours,
501 minutes: None,
502 seconds: None,
503 nanoseconds: None,
504 };
505506// Parse optional separator after hours.
507let Parsed { value: has_minutes, input } = self
508.parse_separator(input, extended)
509 .context(E::SeparatorAfterHours)?;
510if !has_minutes {
511return if self.require_minute
512 || (self.subminute && self.require_second)
513 {
514Err(Error::from(E::MissingMinuteAfterHour))
515 } else {
516Ok(Parsed { value: numeric, input })
517 };
518 }
519520// Parse minutes component.
521let Parsed { value: minutes, input } =
522self.parse_minutes(input).context(E::InvalidMinutes)?;
523numeric.minutes = Some(minutes);
524525// If subminute resolution is not supported, then we're done here.
526if !self.subminute {
527// While we generally try to "stop" parsing once we're done
528 // seeing things we expect, in this case, if we see a colon, it
529 // almost certainly indicates that someone has tried to provide
530 // more precision than is supported. So we return an error here.
531 // If this winds up being problematic, we can make this error
532 // configurable or remove it altogether (unfortunate).
533return if input.get(0).map_or(false, |&b| b == b':') {
534Err(Error::from(E::SubminutePrecisionNotEnabled))
535 } else {
536Ok(Parsed { value: numeric, input })
537 };
538 }
539540// Parse optional separator after minutes.
541let Parsed { value: has_seconds, input } = self
542.parse_separator(input, extended)
543 .context(E::SeparatorAfterMinutes)?;
544if !has_seconds {
545return if self.require_second {
546Err(Error::from(E::MissingSecondAfterMinute))
547 } else {
548Ok(Parsed { value: numeric, input })
549 };
550 }
551552// Parse seconds component.
553let Parsed { value: seconds, input } =
554self.parse_seconds(input).context(E::InvalidSeconds)?;
555numeric.seconds = Some(seconds);
556557// If subsecond resolution is not supported, then we're done here.
558if !self.subsecond {
559if input.get(0).map_or(false, |&b| b == b'.' || b == b',') {
560return Err(Error::from(E::SubsecondPrecisionNotEnabled));
561 }
562return Ok(Parsed { value: numeric, input });
563 }
564565// Parse an optional fractional component.
566let Parsed { value: nanoseconds, input } =
567 parse_temporal_fraction(input)
568 .context(E::InvalidSecondsFractional)?;
569// OK because `parse_temporal_fraction` guarantees `0..=999_999_999`.
570numeric.nanoseconds = nanoseconds.map(|n| i32::try_from(n).unwrap());
571Ok(Parsed { value: numeric, input })
572 }
573574#[cfg_attr(feature = "perf-inline", inline(always))]
575fn parse_sign<'i>(
576&self,
577 input: &'i [u8],
578 ) -> Result<Parsed<'i, Sign>, Error> {
579let sign = input.get(0).copied().ok_or(E::EndOfInputNumeric)?;
580let sign = if sign == b'+' {
581 Sign::Positive582 } else if sign == b'-' {
583 Sign::Negative584 } else {
585return Err(Error::from(E::InvalidSignPlusOrMinus));
586 };
587Ok(Parsed { value: sign, input: &input[1..] })
588 }
589590#[cfg_attr(feature = "perf-inline", inline(always))]
591fn parse_hours<'i>(
592&self,
593 input: &'i [u8],
594 ) -> Result<Parsed<'i, i8>, Error> {
595let (hours, input) =
596 parse::split(input, 2).ok_or(E::EndOfInputHour)?;
597let hours =
598 parse::bi64::<b::OffsetHours>(hours).context(E::ParseHours)?;
599Ok(Parsed { value: hours, input })
600 }
601602#[cfg_attr(feature = "perf-inline", inline(always))]
603fn parse_minutes<'i>(
604&self,
605 input: &'i [u8],
606 ) -> Result<Parsed<'i, i8>, Error> {
607let (minutes, input) =
608 parse::split(input, 2).ok_or(E::EndOfInputMinute)?;
609let minutes = parse::bi64::<b::OffsetMinutes>(minutes)
610 .context(E::ParseMinutes)?;
611Ok(Parsed { value: minutes, input })
612 }
613614#[cfg_attr(feature = "perf-inline", inline(always))]
615fn parse_seconds<'i>(
616&self,
617 input: &'i [u8],
618 ) -> Result<Parsed<'i, i8>, Error> {
619let (seconds, input) =
620 parse::split(input, 2).ok_or(E::EndOfInputSecond)?;
621let seconds = parse::bi64::<b::OffsetSeconds>(seconds)
622 .context(E::ParseSeconds)?;
623Ok(Parsed { value: seconds, input })
624 }
625626/// Parses a separator between hours/minutes or minutes/seconds. When
627 /// `true` is returned, we expect to parse the next component. When `false`
628 /// is returned, then no separator was found and there is no expectation of
629 /// finding another component.
630 ///
631 /// When in extended mode, true is returned if and only if a separator is
632 /// found.
633 ///
634 /// When in basic mode (not extended), then a subsequent component is only
635 /// expected when `input` begins with two ASCII digits.
636#[cfg_attr(feature = "perf-inline", inline(always))]
637fn parse_separator<'i>(
638&self,
639mut input: &'i [u8],
640 extended: bool,
641 ) -> Result<Parsed<'i, bool>, Error> {
642if !extended {
643let expected =
644input.len() >= 2 && input[..2].iter().all(u8::is_ascii_digit);
645return Ok(Parsed { value: expected, input });
646 }
647let is_separator = input.get(0).map_or(false, |&b| b == b':');
648if is_separator {
649input = &input[1..];
650 }
651Ok(Parsed { value: is_separator, input })
652 }
653}
654655/// How to handle parsing of colons in a time zone offset.
656#[derive(#[automatically_derived]impl ::core::fmt::Debug for Colon {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Colon::Optional => "Optional",
Colon::Required => "Required",
Colon::Absent => "Absent",
})
}
}Debug)]
657pub(crate) enum Colon {
658/// Colons may be present or not. When present, colons must be used
659 /// consistently. For example, `+05:3015` and `-0530:15` are not allowed.
660Optional,
661/// Colons must be present.
662Required,
663/// Colons must be absent.
664Absent,
665}
666667#[cfg(test)]
668mod tests {
669use super::*;
670671#[test]
672fn ok_zulu() {
673let p = |input| Parser::new().parse(input).unwrap();
674675insta::assert_debug_snapshot!(p(b"Z"), @r###"
676 Parsed {
677 value: ParsedOffset {
678 kind: Zulu,
679 },
680 input: "",
681 }
682 "###);
683insta::assert_debug_snapshot!(p(b"z"), @r###"
684 Parsed {
685 value: ParsedOffset {
686 kind: Zulu,
687 },
688 input: "",
689 }
690 "###);
691 }
692693#[test]
694fn ok_numeric() {
695let p = |input| Parser::new().parse(input).unwrap();
696697insta::assert_debug_snapshot!(p(b"-05"), @r###"
698 Parsed {
699 value: ParsedOffset {
700 kind: Numeric(
701 -05,
702 ),
703 },
704 input: "",
705 }
706 "###);
707 }
708709// Successful parse tests where the offset ends at the end of the string.
710#[test]
711fn ok_numeric_complete() {
712let p = |input| Parser::new().parse_numeric(input).unwrap();
713714insta::assert_debug_snapshot!(p(b"-05"), @r###"
715 Parsed {
716 value: -05,
717 input: "",
718 }
719 "###);
720insta::assert_debug_snapshot!(p(b"+05"), @r###"
721 Parsed {
722 value: +05,
723 input: "",
724 }
725 "###);
726727insta::assert_debug_snapshot!(p(b"+25:59"), @r###"
728 Parsed {
729 value: +25:59,
730 input: "",
731 }
732 "###);
733insta::assert_debug_snapshot!(p(b"+2559"), @r###"
734 Parsed {
735 value: +25:59,
736 input: "",
737 }
738 "###);
739740insta::assert_debug_snapshot!(p(b"+25:59:59"), @r###"
741 Parsed {
742 value: +25:59:59,
743 input: "",
744 }
745 "###);
746insta::assert_debug_snapshot!(p(b"+255959"), @r###"
747 Parsed {
748 value: +25:59:59,
749 input: "",
750 }
751 "###);
752753insta::assert_debug_snapshot!(p(b"+25:59:59.999"), @r###"
754 Parsed {
755 value: +25:59:59.999,
756 input: "",
757 }
758 "###);
759insta::assert_debug_snapshot!(p(b"+25:59:59,999"), @r###"
760 Parsed {
761 value: +25:59:59.999,
762 input: "",
763 }
764 "###);
765insta::assert_debug_snapshot!(p(b"+255959.999"), @r###"
766 Parsed {
767 value: +25:59:59.999,
768 input: "",
769 }
770 "###);
771insta::assert_debug_snapshot!(p(b"+255959,999"), @r###"
772 Parsed {
773 value: +25:59:59.999,
774 input: "",
775 }
776 "###);
777778insta::assert_debug_snapshot!(p(b"+25:59:59.999999999"), @r###"
779 Parsed {
780 value: +25:59:59.999999999,
781 input: "",
782 }
783 "###);
784 }
785786// Successful parse tests where the offset ends before the end of the
787 // string.
788#[test]
789fn ok_numeric_incomplete() {
790let p = |input| Parser::new().parse_numeric(input).unwrap();
791792insta::assert_debug_snapshot!(p(b"-05a"), @r###"
793 Parsed {
794 value: -05,
795 input: "a",
796 }
797 "###);
798insta::assert_debug_snapshot!(p(b"-05:12a"), @r###"
799 Parsed {
800 value: -05:12,
801 input: "a",
802 }
803 "###);
804insta::assert_debug_snapshot!(p(b"-05:12."), @r###"
805 Parsed {
806 value: -05:12,
807 input: ".",
808 }
809 "###);
810insta::assert_debug_snapshot!(p(b"-05:12,"), @r###"
811 Parsed {
812 value: -05:12,
813 input: ",",
814 }
815 "###);
816insta::assert_debug_snapshot!(p(b"-0512a"), @r###"
817 Parsed {
818 value: -05:12,
819 input: "a",
820 }
821 "###);
822insta::assert_debug_snapshot!(p(b"-0512:"), @r###"
823 Parsed {
824 value: -05:12,
825 input: ":",
826 }
827 "###);
828insta::assert_debug_snapshot!(p(b"-05:12:34a"), @r###"
829 Parsed {
830 value: -05:12:34,
831 input: "a",
832 }
833 "###);
834insta::assert_debug_snapshot!(p(b"-05:12:34.9a"), @r###"
835 Parsed {
836 value: -05:12:34.9,
837 input: "a",
838 }
839 "###);
840insta::assert_debug_snapshot!(p(b"-05:12:34.9."), @r###"
841 Parsed {
842 value: -05:12:34.9,
843 input: ".",
844 }
845 "###);
846insta::assert_debug_snapshot!(p(b"-05:12:34.9,"), @r###"
847 Parsed {
848 value: -05:12:34.9,
849 input: ",",
850 }
851 "###);
852 }
853854// An empty string is invalid. The parser is written from the perspective
855 // that if it's called, then the caller expects a numeric UTC offset at
856 // that position.
857#[test]
858fn err_numeric_empty() {
859insta::assert_snapshot!(
860 Parser::new().parse_numeric(b"").unwrap_err(),
861 @"failed to parse sign in UTC numeric offset: expected UTC numeric offset, but found end of input",
862 );
863 }
864865// A numeric offset always has to begin with a '+' or a '-'.
866#[test]
867fn err_numeric_notsign() {
868insta::assert_snapshot!(
869 Parser::new().parse_numeric(b"*").unwrap_err(),
870 @"failed to parse sign in UTC numeric offset: expected `+` or `-` sign at start of UTC numeric offset",
871 );
872 }
873874// The hours component must be at least two bytes.
875#[test]
876fn err_numeric_hours_too_short() {
877insta::assert_snapshot!(
878 Parser::new().parse_numeric(b"+a").unwrap_err(),
879 @"failed to parse hours in UTC numeric offset: expected two digit hour after sign, but found end of input",
880 );
881 }
882883// The hours component must be at least two ASCII digits.
884#[test]
885fn err_numeric_hours_invalid_digits() {
886insta::assert_snapshot!(
887 Parser::new().parse_numeric(b"+ab").unwrap_err(),
888 @"failed to parse hours in UTC numeric offset: failed to parse hours (requires a two digit integer): invalid digit, expected 0-9 but got a",
889 );
890 }
891892// The hours component must be in range.
893#[test]
894fn err_numeric_hours_out_of_range() {
895insta::assert_snapshot!(
896 Parser::new().parse_numeric(b"-26").unwrap_err(),
897 @"failed to parse hours in UTC numeric offset: failed to parse hours (requires a two digit integer): parameter 'time zone offset hours' is not in the required range of -25..=25",
898 );
899 }
900901// The minutes component must be at least two bytes.
902#[test]
903fn err_numeric_minutes_too_short() {
904insta::assert_snapshot!(
905 Parser::new().parse_numeric(b"+05:a").unwrap_err(),
906 @"failed to parse minutes in UTC numeric offset: expected two digit minute after hours, but found end of input",
907 );
908 }
909910// The minutes component must be at least two ASCII digits.
911#[test]
912fn err_numeric_minutes_invalid_digits() {
913insta::assert_snapshot!(
914 Parser::new().parse_numeric(b"+05:ab").unwrap_err(),
915 @"failed to parse minutes in UTC numeric offset: failed to parse minutes (requires a two digit integer): invalid digit, expected 0-9 but got a",
916 );
917 }
918919// The minutes component must be in range.
920#[test]
921fn err_numeric_minutes_out_of_range() {
922insta::assert_snapshot!(
923 Parser::new().parse_numeric(b"-05:60").unwrap_err(),
924 @"failed to parse minutes in UTC numeric offset: failed to parse minutes (requires a two digit integer): parameter 'time zone offset minutes' is not in the required range of -59..=59",
925 );
926 }
927928// The seconds component must be at least two bytes.
929#[test]
930fn err_numeric_seconds_too_short() {
931insta::assert_snapshot!(
932 Parser::new().parse_numeric(b"+05:30:a").unwrap_err(),
933 @"failed to parse seconds in UTC numeric offset: expected two digit second after minutes, but found end of input",
934 );
935 }
936937// The seconds component must be at least two ASCII digits.
938#[test]
939fn err_numeric_seconds_invalid_digits() {
940insta::assert_snapshot!(
941 Parser::new().parse_numeric(b"+05:30:ab").unwrap_err(),
942 @"failed to parse seconds in UTC numeric offset: failed to parse seconds (requires a two digit integer): invalid digit, expected 0-9 but got a",
943 );
944 }
945946// The seconds component must be in range.
947#[test]
948fn err_numeric_seconds_out_of_range() {
949insta::assert_snapshot!(
950 Parser::new().parse_numeric(b"-05:30:60").unwrap_err(),
951 @"failed to parse seconds in UTC numeric offset: failed to parse seconds (requires a two digit integer): parameter 'time zone offset seconds' is not in the required range of -59..=59",
952 );
953 }
954955// The fraction component, if present as indicated by a separator, must be
956 // non-empty.
957#[test]
958fn err_numeric_fraction_non_empty() {
959insta::assert_snapshot!(
960 Parser::new().parse_numeric(b"-05:30:44.").unwrap_err(),
961 @"failed to parse fractional seconds in UTC numeric offset: found decimal after seconds component, but did not find any digits after decimal",
962 );
963insta::assert_snapshot!(
964 Parser::new().parse_numeric(b"-05:30:44,").unwrap_err(),
965 @"failed to parse fractional seconds in UTC numeric offset: found decimal after seconds component, but did not find any digits after decimal",
966 );
967968// Instead of end-of-string, add invalid digit.
969insta::assert_snapshot!(
970 Parser::new().parse_numeric(b"-05:30:44.a").unwrap_err(),
971 @"failed to parse fractional seconds in UTC numeric offset: found decimal after seconds component, but did not find any digits after decimal",
972 );
973insta::assert_snapshot!(
974 Parser::new().parse_numeric(b"-05:30:44,a").unwrap_err(),
975 @"failed to parse fractional seconds in UTC numeric offset: found decimal after seconds component, but did not find any digits after decimal",
976 );
977978// And also test basic format.
979insta::assert_snapshot!(
980 Parser::new().parse_numeric(b"-053044.a").unwrap_err(),
981 @"failed to parse fractional seconds in UTC numeric offset: found decimal after seconds component, but did not find any digits after decimal",
982 );
983insta::assert_snapshot!(
984 Parser::new().parse_numeric(b"-053044,a").unwrap_err(),
985 @"failed to parse fractional seconds in UTC numeric offset: found decimal after seconds component, but did not find any digits after decimal",
986 );
987 }
988989// A special case where it is clear that sub-minute precision has been
990 // requested, but that it is has been forcefully disabled. This error is
991 // meant to make what is likely a subtle failure mode more explicit.
992#[test]
993fn err_numeric_subminute_disabled_but_desired() {
994insta::assert_snapshot!(
995 Parser::new().subminute(false).parse_numeric(b"-05:59:32").unwrap_err(),
996 @"subminute precision for UTC numeric offset is not enabled in this context (must provide only integral minutes)",
997 );
998 }
9991000// Another special case where Zulu parsing has been explicitly disabled,
1001 // but a Zulu string was found.
1002#[test]
1003fn err_zulu_disabled_but_desired() {
1004insta::assert_snapshot!(
1005 Parser::new().zulu(false).parse(b"Z").unwrap_err(),
1006 @"found `Z` where a numeric UTC offset was expected (this context does not permit the Zulu offset)",
1007 );
1008insta::assert_snapshot!(
1009 Parser::new().zulu(false).parse(b"z").unwrap_err(),
1010 @"found `z` where a numeric UTC offset was expected (this context does not permit the Zulu offset)",
1011 );
1012 }
10131014// Once a `Numeric` has been parsed, it is almost possible to assume that
1015 // it can be infallibly converted to an `Offset`. The one case where this
1016 // isn't true is when there is a fractional nanosecond part along with
1017 // maximal
1018#[test]
1019fn err_numeric_too_big_for_offset() {
1020let numeric = Numeric {
1021 sign: Sign::Positive,
1022 hours: b::OffsetHours::MAX,
1023 minutes: Some(b::OffsetMinutes::MAX),
1024 seconds: Some(b::OffsetSeconds::MAX),
1025 nanoseconds: Some(499_999_999),
1026 };
1027assert_eq!(numeric.to_offset().unwrap(), Offset::MAX);
10281029let numeric = Numeric {
1030 sign: Sign::Positive,
1031 hours: b::OffsetHours::MAX,
1032 minutes: Some(b::OffsetMinutes::MAX),
1033 seconds: Some(b::OffsetSeconds::MAX),
1034 nanoseconds: Some(500_000_000),
1035 };
1036insta::assert_snapshot!(
1037 numeric.to_offset().unwrap_err(),
1038 @"due to precision loss from fractional seconds, time zone offset is rounded to a value that is out of bounds",
1039 );
1040 }
10411042// Same as numeric_too_big_for_offset, but at the minimum boundary.
1043#[test]
1044fn err_numeric_too_small_for_offset() {
1045let numeric = Numeric {
1046 sign: Sign::Negative,
1047 hours: b::OffsetHours::MAX,
1048 minutes: Some(b::OffsetMinutes::MAX),
1049 seconds: Some(b::OffsetSeconds::MAX),
1050 nanoseconds: Some(499_999_999),
1051 };
1052assert_eq!(numeric.to_offset().unwrap(), Offset::MIN);
10531054let numeric = Numeric {
1055 sign: Sign::Negative,
1056 hours: b::OffsetHours::MAX,
1057 minutes: Some(b::OffsetMinutes::MAX),
1058 seconds: Some(b::OffsetSeconds::MAX),
1059 nanoseconds: Some(500_000_000),
1060 };
1061insta::assert_snapshot!(
1062 numeric.to_offset().unwrap_err(),
1063 @"due to precision loss from fractional seconds, time zone offset is rounded to a value that is out of bounds",
1064 );
1065 }
1066}