Debian Codegraph @

debian/rust-vendor/jiff/src/fmt/offset.rs

raw
1 /*!
2 This module provides facilities for parsing time zone offsets.
3
4 The parsing here follows primarily from [RFC 3339] and [ISO 8601], but also
5 from [Temporal's hybrid grammar].
6
7 [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 */
11
12 // 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.)
103
104 use jcore::{bounds::Sign, constants as c};
105
106 use crate::{
107 error::{fmt::offset::Error as E, Error, ErrorContext},
108 fmt::{
109 buffer::ArrayBuffer,
110 temporal::{PiecesNumericOffset, PiecesOffset},
111 util::parse_temporal_fraction,
112 Parsed,
113 },
114 tz::Offset,
115 util::{b, parse},
116 };
117
118 /// 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(Debug)]
124 pub(crate) struct ParsedOffset {
125 /// The kind of offset parsed.
126 kind: ParsedOffsetKind,
127 }
128
129 impl 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.
143 pub(crate) fn to_offset(&self) -> Result<Offset, Error> {
144 match self.kind {
145 ParsedOffsetKind::Zulu => Ok(Offset::UTC),
146 ParsedOffsetKind::Numeric(ref numeric) => numeric.to_offset(),
147 }
148 }
149
150 /// 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.
155 pub(crate) fn to_pieces_offset(&self) -> Result<PiecesOffset, Error> {
156 match self.kind {
157 ParsedOffsetKind::Zulu => Ok(PiecesOffset::Zulu),
158 ParsedOffsetKind::Numeric(ref numeric) => {
159 let mut off = PiecesNumericOffset::from(numeric.to_offset()?);
160 if numeric.sign.is_negative() {
161 off = off.with_negative_zero();
162 }
163 Ok(PiecesOffset::from(off))
164 }
165 }
166 }
167
168 /// 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.
173 pub(crate) fn is_zulu(&self) -> bool {
174 matches!(self.kind, ParsedOffsetKind::Zulu)
175 }
176
177 /// Whether the parsed offset had an explicit sub-minute component or not.
178 pub(crate) fn has_subminute(&self) -> bool {
179 let ParsedOffsetKind::Numeric(ref numeric) = self.kind else {
180 return false;
181 };
182 numeric.seconds.is_some()
183 }
184 }
185
186 impl core::fmt::Display for ParsedOffset {
187 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
188 match 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 }
196
197 /// The kind of a parsed offset.
198 #[derive(Debug)]
199 enum ParsedOffsetKind {
200 /// The zulu offset, corresponding to UTC in a context where the offset for
201 /// civil time is unknown or unavailable.
202 Zulu,
203 /// The specific numeric offset.
204 Numeric(Numeric),
205 }
206
207 /// A numeric representation of a UTC offset.
208 struct Numeric {
209 /// The sign that was parsed from the numeric UTC offset. This is always
210 /// either `1` or `-1`, never `0`.
211 sign: Sign,
212 /// The hours component. This is non-optional because every UTC offset must
213 /// have at least hours.
214 hours: i8,
215 /// The minutes component.
216 minutes: Option<i8>,
217 /// The seconds component. This is only possible when subminute resolution
218 /// is enabled.
219 seconds: Option<i8>,
220 /// The nanoseconds fractional component. This is only possible when
221 /// subminute resolution is enabled.
222 nanoseconds: Option<i32>,
223 }
224
225 impl 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.
231 fn to_offset(&self) -> Result<Offset, Error> {
232 let mut seconds = i32::from(self.hours) * c::SECS_PER_HOUR_32;
233 if let Some(part_minutes) = self.minutes {
234 seconds += i32::from(part_minutes) * c::SECS_PER_MIN_32;
235 }
236 if let Some(part_seconds) = self.seconds {
237 seconds += i32::from(part_seconds);
238 }
239 if let Some(part_nanoseconds) = self.nanoseconds {
240 if part_nanoseconds >= 500_000_000 {
241 seconds += 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.
247 Ok(Offset::from_seconds(self.sign * seconds)
248 .map_err(|_| E::PrecisionLoss)?)
249 }
250 }
251
252 // This impl is just used for error messages when converting a `Numeric` to an
253 // `Offset` fails.
254 impl core::fmt::Display for Numeric {
255 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
256 let mut buf = ArrayBuffer::<19>::default();
257 let mut bbuf = buf.as_borrowed();
258
259 bbuf.write_ascii_char(if self.sign.is_negative() {
260 b'-'
261 } else {
262 b'+'
263 });
264 bbuf.write_int_pad2(self.hours.unsigned_abs());
265 if let Some(minutes) = self.minutes {
266 bbuf.write_ascii_char(b':');
267 bbuf.write_int_pad2(minutes.unsigned_abs());
268 }
269 if let Some(seconds) = self.seconds {
270 if self.minutes.is_none() {
271 bbuf.write_str(":00");
272 }
273 bbuf.write_ascii_char(b':');
274 bbuf.write_int_pad2(seconds.unsigned_abs());
275 }
276 if let Some(nanos) = self.nanoseconds {
277 if nanos != 0 {
278 if self.minutes.is_none() {
279 bbuf.write_str(":00");
280 }
281 if self.seconds.is_none() {
282 bbuf.write_str(":00");
283 }
284 bbuf.write_ascii_char(b'.');
285 bbuf.write_fraction(None, nanos.unsigned_abs());
286 }
287 }
288 f.write_str(bbuf.filled())
289 }
290 }
291
292 // We give a succinct Debug impl (identical to Display) to make snapshot
293 // testing a bit nicer.
294 impl core::fmt::Debug for Numeric {
295 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
296 core::fmt::Display::fmt(self, f)
297 }
298 }
299
300 /// 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(Debug)]
313 pub(crate) struct Parser {
314 zulu: bool,
315 require_minute: bool,
316 require_second: bool,
317 subminute: bool,
318 subsecond: bool,
319 colon: Colon,
320 }
321
322 impl Parser {
323 /// Create a new UTC offset parser with the default configuration.
324 pub(crate) const fn new() -> Parser {
325 Parser {
326 zulu: true,
327 require_minute: false,
328 require_second: false,
329 subminute: true,
330 subsecond: true,
331 colon: Colon::Optional,
332 }
333 }
334
335 /// 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.
342 pub(crate) const fn zulu(self, yes: bool) -> Parser {
343 Parser { zulu: yes, ..self }
344 }
345
346 /// 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.
350 pub(crate) const fn require_minute(self, yes: bool) -> Parser {
351 Parser { require_minute: yes, ..self }
352 }
353
354 /// 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.
360 pub(crate) const fn require_second(self, yes: bool) -> Parser {
361 Parser { require_second: yes, ..self }
362 }
363
364 /// 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.
370 pub(crate) const fn subminute(self, yes: bool) -> Parser {
371 Parser { subminute: yes, ..self }
372 }
373
374 /// 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.
384 pub(crate) const fn subsecond(self, yes: bool) -> Parser {
385 Parser { subsecond: yes, ..self }
386 }
387
388 /// Sets how to handle parsing of colons in a time zone offset.
389 ///
390 /// This is set to `Colon::Optional` by default.
391 pub(crate) const fn colon(self, colon: Colon) -> Parser {
392 Parser { colon, ..self }
393 }
394
395 /// 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.
422 pub(crate) fn parse<'i>(
423 &self,
424 mut input: &'i [u8],
425 ) -> Result<Parsed<'i, ParsedOffset>, Error> {
426 if input.is_empty() {
427 return Err(Error::from(E::EndOfInput));
428 }
429
430 if input[0] == b'Z' || input[0] == b'z' {
431 if !self.zulu {
432 return Err(Error::from(E::UnexpectedLetterOffsetNoZulu(
433 input[0],
434 )));
435 }
436 input = &input[1..];
437 let value = ParsedOffset { kind: ParsedOffsetKind::Zulu };
438 return Ok(Parsed { value, input });
439 }
440 let Parsed { value: numeric, input } = self.parse_numeric(input)?;
441 let value = ParsedOffset { kind: ParsedOffsetKind::Numeric(numeric) };
442 Ok(Parsed { value, input })
443 }
444
445 /// 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))]
451 pub(crate) fn parse_optional<'i>(
452 &self,
453 input: &'i [u8],
454 ) -> Result<Parsed<'i, Option<ParsedOffset>>, Error> {
455 let Some(first) = input.first().copied() else {
456 return Ok(Parsed { value: None, input });
457 };
458 if !matches!(first, b'z' | b'Z' | b'+' | b'-') {
459 return Ok(Parsed { value: None, input });
460 }
461 let Parsed { value, input } = self.parse(input)?;
462 Ok(Parsed { value: Some(value), input })
463 }
464
465 /// 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))]
470 fn parse_numeric<'i>(
471 &self,
472 input: &'i [u8],
473 ) -> Result<Parsed<'i, Numeric>, Error> {
474 // Parse sign component.
475 let Parsed { value: sign, input } =
476 self.parse_sign(input).context(E::InvalidSign)?;
477
478 // Parse hours component.
479 let Parsed { value: hours, input } =
480 self.parse_hours(input).context(E::InvalidHours)?;
481 let extended = match self.colon {
482 Colon::Optional => input.starts_with(b":"),
483 Colon::Required => {
484 if !input.is_empty() && !input.starts_with(b":") {
485 return Err(Error::from(E::NoColonAfterHours));
486 }
487 true
488 }
489 Colon::Absent => {
490 if !input.is_empty() && input.starts_with(b":") {
491 return Err(Error::from(E::ColonAfterHours));
492 }
493 false
494 }
495 };
496
497 // Start building up our numeric offset value.
498 let mut numeric = Numeric {
499 sign,
500 hours,
501 minutes: None,
502 seconds: None,
503 nanoseconds: None,
504 };
505
506 // Parse optional separator after hours.
507 let Parsed { value: has_minutes, input } = self
508 .parse_separator(input, extended)
509 .context(E::SeparatorAfterHours)?;
510 if !has_minutes {
511 return if self.require_minute
512 || (self.subminute && self.require_second)
513 {
514 Err(Error::from(E::MissingMinuteAfterHour))
515 } else {
516 Ok(Parsed { value: numeric, input })
517 };
518 }
519
520 // Parse minutes component.
521 let Parsed { value: minutes, input } =
522 self.parse_minutes(input).context(E::InvalidMinutes)?;
523 numeric.minutes = Some(minutes);
524
525 // If subminute resolution is not supported, then we're done here.
526 if !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).
533 return if input.get(0).map_or(false, |&b| b == b':') {
534 Err(Error::from(E::SubminutePrecisionNotEnabled))
535 } else {
536 Ok(Parsed { value: numeric, input })
537 };
538 }
539
540 // Parse optional separator after minutes.
541 let Parsed { value: has_seconds, input } = self
542 .parse_separator(input, extended)
543 .context(E::SeparatorAfterMinutes)?;
544 if !has_seconds {
545 return if self.require_second {
546 Err(Error::from(E::MissingSecondAfterMinute))
547 } else {
548 Ok(Parsed { value: numeric, input })
549 };
550 }
551
552 // Parse seconds component.
553 let Parsed { value: seconds, input } =
554 self.parse_seconds(input).context(E::InvalidSeconds)?;
555 numeric.seconds = Some(seconds);
556
557 // If subsecond resolution is not supported, then we're done here.
558 if !self.subsecond {
559 if input.get(0).map_or(false, |&b| b == b'.' || b == b',') {
560 return Err(Error::from(E::SubsecondPrecisionNotEnabled));
561 }
562 return Ok(Parsed { value: numeric, input });
563 }
564
565 // Parse an optional fractional component.
566 let Parsed { value: nanoseconds, input } =
567 parse_temporal_fraction(input)
568 .context(E::InvalidSecondsFractional)?;
569 // OK because `parse_temporal_fraction` guarantees `0..=999_999_999`.
570 numeric.nanoseconds = nanoseconds.map(|n| i32::try_from(n).unwrap());
571 Ok(Parsed { value: numeric, input })
572 }
573
574 #[cfg_attr(feature = "perf-inline", inline(always))]
575 fn parse_sign<'i>(
576 &self,
577 input: &'i [u8],
578 ) -> Result<Parsed<'i, Sign>, Error> {
579 let sign = input.get(0).copied().ok_or(E::EndOfInputNumeric)?;
580 let sign = if sign == b'+' {
581 Sign::Positive
582 } else if sign == b'-' {
583 Sign::Negative
584 } else {
585 return Err(Error::from(E::InvalidSignPlusOrMinus));
586 };
587 Ok(Parsed { value: sign, input: &input[1..] })
588 }
589
590 #[cfg_attr(feature = "perf-inline", inline(always))]
591 fn parse_hours<'i>(
592 &self,
593 input: &'i [u8],
594 ) -> Result<Parsed<'i, i8>, Error> {
595 let (hours, input) =
596 parse::split(input, 2).ok_or(E::EndOfInputHour)?;
597 let hours =
598 parse::bi64::<b::OffsetHours>(hours).context(E::ParseHours)?;
599 Ok(Parsed { value: hours, input })
600 }
601
602 #[cfg_attr(feature = "perf-inline", inline(always))]
603 fn parse_minutes<'i>(
604 &self,
605 input: &'i [u8],
606 ) -> Result<Parsed<'i, i8>, Error> {
607 let (minutes, input) =
608 parse::split(input, 2).ok_or(E::EndOfInputMinute)?;
609 let minutes = parse::bi64::<b::OffsetMinutes>(minutes)
610 .context(E::ParseMinutes)?;
611 Ok(Parsed { value: minutes, input })
612 }
613
614 #[cfg_attr(feature = "perf-inline", inline(always))]
615 fn parse_seconds<'i>(
616 &self,
617 input: &'i [u8],
618 ) -> Result<Parsed<'i, i8>, Error> {
619 let (seconds, input) =
620 parse::split(input, 2).ok_or(E::EndOfInputSecond)?;
621 let seconds = parse::bi64::<b::OffsetSeconds>(seconds)
622 .context(E::ParseSeconds)?;
623 Ok(Parsed { value: seconds, input })
624 }
625
626 /// 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))]
637 fn parse_separator<'i>(
638 &self,
639 mut input: &'i [u8],
640 extended: bool,
641 ) -> Result<Parsed<'i, bool>, Error> {
642 if !extended {
643 let expected =
644 input.len() >= 2 && input[..2].iter().all(u8::is_ascii_digit);
645 return Ok(Parsed { value: expected, input });
646 }
647 let is_separator = input.get(0).map_or(false, |&b| b == b':');
648 if is_separator {
649 input = &input[1..];
650 }
651 Ok(Parsed { value: is_separator, input })
652 }
653 }
654
655 /// How to handle parsing of colons in a time zone offset.
656 #[derive(Debug)]
657 pub(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.
660 Optional,
661 /// Colons must be present.
662 Required,
663 /// Colons must be absent.
664 Absent,
665 }
666
667 #[cfg(test)]
668 mod tests {
669 use super::*;
670
671 #[test]
672 fn ok_zulu() {
673 let p = |input| Parser::new().parse(input).unwrap();
674
675 insta::assert_debug_snapshot!(p(b"Z"), @r###"
676 Parsed {
677 value: ParsedOffset {
678 kind: Zulu,
679 },
680 input: "",
681 }
682 "###);
683 insta::assert_debug_snapshot!(p(b"z"), @r###"
684 Parsed {
685 value: ParsedOffset {
686 kind: Zulu,
687 },
688 input: "",
689 }
690 "###);
691 }
692
693 #[test]
694 fn ok_numeric() {
695 let p = |input| Parser::new().parse(input).unwrap();
696
697 insta::assert_debug_snapshot!(p(b"-05"), @r###"
698 Parsed {
699 value: ParsedOffset {
700 kind: Numeric(
701 -05,
702 ),
703 },
704 input: "",
705 }
706 "###);
707 }
708
709 // Successful parse tests where the offset ends at the end of the string.
710 #[test]
711 fn ok_numeric_complete() {
712 let p = |input| Parser::new().parse_numeric(input).unwrap();
713
714 insta::assert_debug_snapshot!(p(b"-05"), @r###"
715 Parsed {
716 value: -05,
717 input: "",
718 }
719 "###);
720 insta::assert_debug_snapshot!(p(b"+05"), @r###"
721 Parsed {
722 value: +05,
723 input: "",
724 }
725 "###);
726
727 insta::assert_debug_snapshot!(p(b"+25:59"), @r###"
728 Parsed {
729 value: +25:59,
730 input: "",
731 }
732 "###);
733 insta::assert_debug_snapshot!(p(b"+2559"), @r###"
734 Parsed {
735 value: +25:59,
736 input: "",
737 }
738 "###);
739
740 insta::assert_debug_snapshot!(p(b"+25:59:59"), @r###"
741 Parsed {
742 value: +25:59:59,
743 input: "",
744 }
745 "###);
746 insta::assert_debug_snapshot!(p(b"+255959"), @r###"
747 Parsed {
748 value: +25:59:59,
749 input: "",
750 }
751 "###);
752
753 insta::assert_debug_snapshot!(p(b"+25:59:59.999"), @r###"
754 Parsed {
755 value: +25:59:59.999,
756 input: "",
757 }
758 "###);
759 insta::assert_debug_snapshot!(p(b"+25:59:59,999"), @r###"
760 Parsed {
761 value: +25:59:59.999,
762 input: "",
763 }
764 "###);
765 insta::assert_debug_snapshot!(p(b"+255959.999"), @r###"
766 Parsed {
767 value: +25:59:59.999,
768 input: "",
769 }
770 "###);
771 insta::assert_debug_snapshot!(p(b"+255959,999"), @r###"
772 Parsed {
773 value: +25:59:59.999,
774 input: "",
775 }
776 "###);
777
778 insta::assert_debug_snapshot!(p(b"+25:59:59.999999999"), @r###"
779 Parsed {
780 value: +25:59:59.999999999,
781 input: "",
782 }
783 "###);
784 }
785
786 // Successful parse tests where the offset ends before the end of the
787 // string.
788 #[test]
789 fn ok_numeric_incomplete() {
790 let p = |input| Parser::new().parse_numeric(input).unwrap();
791
792 insta::assert_debug_snapshot!(p(b"-05a"), @r###"
793 Parsed {
794 value: -05,
795 input: "a",
796 }
797 "###);
798 insta::assert_debug_snapshot!(p(b"-05:12a"), @r###"
799 Parsed {
800 value: -05:12,
801 input: "a",
802 }
803 "###);
804 insta::assert_debug_snapshot!(p(b"-05:12."), @r###"
805 Parsed {
806 value: -05:12,
807 input: ".",
808 }
809 "###);
810 insta::assert_debug_snapshot!(p(b"-05:12,"), @r###"
811 Parsed {
812 value: -05:12,
813 input: ",",
814 }
815 "###);
816 insta::assert_debug_snapshot!(p(b"-0512a"), @r###"
817 Parsed {
818 value: -05:12,
819 input: "a",
820 }
821 "###);
822 insta::assert_debug_snapshot!(p(b"-0512:"), @r###"
823 Parsed {
824 value: -05:12,
825 input: ":",
826 }
827 "###);
828 insta::assert_debug_snapshot!(p(b"-05:12:34a"), @r###"
829 Parsed {
830 value: -05:12:34,
831 input: "a",
832 }
833 "###);
834 insta::assert_debug_snapshot!(p(b"-05:12:34.9a"), @r###"
835 Parsed {
836 value: -05:12:34.9,
837 input: "a",
838 }
839 "###);
840 insta::assert_debug_snapshot!(p(b"-05:12:34.9."), @r###"
841 Parsed {
842 value: -05:12:34.9,
843 input: ".",
844 }
845 "###);
846 insta::assert_debug_snapshot!(p(b"-05:12:34.9,"), @r###"
847 Parsed {
848 value: -05:12:34.9,
849 input: ",",
850 }
851 "###);
852 }
853
854 // 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]
858 fn err_numeric_empty() {
859 insta::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 }
864
865 // A numeric offset always has to begin with a '+' or a '-'.
866 #[test]
867 fn err_numeric_notsign() {
868 insta::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 }
873
874 // The hours component must be at least two bytes.
875 #[test]
876 fn err_numeric_hours_too_short() {
877 insta::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 }
882
883 // The hours component must be at least two ASCII digits.
884 #[test]
885 fn err_numeric_hours_invalid_digits() {
886 insta::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 }
891
892 // The hours component must be in range.
893 #[test]
894 fn err_numeric_hours_out_of_range() {
895 insta::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 }
900
901 // The minutes component must be at least two bytes.
902 #[test]
903 fn err_numeric_minutes_too_short() {
904 insta::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 }
909
910 // The minutes component must be at least two ASCII digits.
911 #[test]
912 fn err_numeric_minutes_invalid_digits() {
913 insta::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 }
918
919 // The minutes component must be in range.
920 #[test]
921 fn err_numeric_minutes_out_of_range() {
922 insta::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 }
927
928 // The seconds component must be at least two bytes.
929 #[test]
930 fn err_numeric_seconds_too_short() {
931 insta::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 }
936
937 // The seconds component must be at least two ASCII digits.
938 #[test]
939 fn err_numeric_seconds_invalid_digits() {
940 insta::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 }
945
946 // The seconds component must be in range.
947 #[test]
948 fn err_numeric_seconds_out_of_range() {
949 insta::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 }
954
955 // The fraction component, if present as indicated by a separator, must be
956 // non-empty.
957 #[test]
958 fn err_numeric_fraction_non_empty() {
959 insta::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 );
963 insta::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 );
967
968 // Instead of end-of-string, add invalid digit.
969 insta::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 );
973 insta::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 );
977
978 // And also test basic format.
979 insta::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 );
983 insta::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 }
988
989 // 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]
993 fn err_numeric_subminute_disabled_but_desired() {
994 insta::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 }
999
1000 // Another special case where Zulu parsing has been explicitly disabled,
1001 // but a Zulu string was found.
1002 #[test]
1003 fn err_zulu_disabled_but_desired() {
1004 insta::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 );
1008 insta::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 }
1013
1014 // 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]
1019 fn err_numeric_too_big_for_offset() {
1020 let 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 };
1027 assert_eq!(numeric.to_offset().unwrap(), Offset::MAX);
1028
1029 let 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 };
1036 insta::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 }
1041
1042 // Same as numeric_too_big_for_offset, but at the minimum boundary.
1043 #[test]
1044 fn err_numeric_too_small_for_offset() {
1045 let 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 };
1052 assert_eq!(numeric.to_offset().unwrap(), Offset::MIN);
1053
1054 let 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 };
1061 insta::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 }