Skip to main content

jiff/fmt/temporal/
parser.rs

1use jcore::{bounds::Sign, constants as c};
2
3use crate::{
4    SignedDuration, Timestamp, Unit, ZonedDateTime,
5    civil::{Date, DateTime, ISOWeekDate, Time, Weekday},
6    error::{Error, ErrorContext, fmt::temporal::Error as E},
7    fmt::{
8        Parsed,
9        offset::{self, ParsedOffset},
10        rfc9557::{self, ParsedAnnotations},
11        temporal::Pieces,
12        util::{DurationUnits, parse_temporal_fraction},
13    },
14    span::Span,
15    tz::{
16        AmbiguousZonedDateTime, Disambiguation, Offset, OffsetConflict,
17        TimeZone, TimeZoneDatabase,
18    },
19    util::{b, escape, parse},
20};
21
22/// The datetime components parsed from a string.
23#[derive(#[automatically_derived]impl<'i> ::core::fmt::Debug for ParsedDateTime<'i> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "ParsedDateTime date time offset annotations", &self.date,
            &self.time, &self.offset, &&self.annotations)
    }
}Debug)]
24pub(super) struct ParsedDateTime<'i> {
25    /// A required civil date.
26    date: ParsedDate,
27    /// An optional civil time.
28    time: Option<ParsedTime>,
29    /// An optional UTC offset.
30    offset: Option<ParsedOffset>,
31    /// An optional RFC 9557 annotations parsed.
32    ///
33    /// An empty `ParsedAnnotations` is valid and possible, so this bakes
34    /// optionality into the type and doesn't need to be an `Option` itself.
35    annotations: ParsedAnnotations<'i>,
36}
37
38impl<'i> ParsedDateTime<'i> {
39    #[cfg_attr(feature = "perf-inline", inline(always))]
40    pub(super) fn to_pieces(&self) -> Result<Pieces<'i>, Error> {
41        let mut pieces = Pieces::from(self.date.date);
42        if let Some(ref time) = self.time {
43            pieces = pieces.with_time(time.time);
44        }
45        if let Some(ref offset) = self.offset {
46            pieces = pieces.with_offset(offset.to_pieces_offset()?);
47        }
48        if let Some(ann) = self.annotations.to_time_zone_annotation()? {
49            pieces = pieces.with_time_zone_annotation(ann);
50        }
51        Ok(pieces)
52    }
53
54    #[cfg_attr(feature = "perf-inline", inline(always))]
55    pub(super) fn to_zoned_datetime(
56        &self,
57        db: &TimeZoneDatabase,
58        offset_conflict: OffsetConflict,
59        disambiguation: Disambiguation,
60    ) -> Result<ZonedDateTime, Error> {
61        self.to_ambiguous_zoned_datetime(db, offset_conflict)?
62            .disambiguate(disambiguation)
63    }
64
65    #[cfg_attr(feature = "perf-inline", inline(always))]
66    fn to_ambiguous_zoned_datetime(
67        &self,
68        db: &TimeZoneDatabase,
69        offset_conflict: OffsetConflict,
70    ) -> Result<AmbiguousZonedDateTime, Error> {
71        let time = self.time.as_ref().map_or(Time::midnight(), |p| p.time);
72        let dt = DateTime::from_parts(self.date.date, time);
73
74        // We always require a time zone when parsing a zoned instant.
75        let tz_annotation = self
76            .annotations
77            .to_time_zone_annotation()?
78            .ok_or(E::MissingTimeZoneAnnotation)?;
79        let tz = tz_annotation.to_time_zone_with(db)?;
80
81        // If there's no offset, then our only choice, regardless of conflict
82        // resolution preference, is to use the time zone. That is, there is no
83        // possible conflict.
84        let Some(ref parsed_offset) = self.offset else {
85            return Ok(tz.into_ambiguous_zoned_datetime(dt));
86        };
87        if parsed_offset.is_zulu() {
88            // When `Z` is used, that means the offset to local time is not
89            // known. In this case, there really can't be a conflict because
90            // there is an explicit acknowledgment that the offset could be
91            // anything. So we just always accept `Z` as if it were `UTC` and
92            // respect that. If we didn't have this special check, we'd fall
93            // below and the `Z` would just be treated as `+00:00`, which would
94            // likely result in `OffsetConflict::Reject` raising an error.
95            // (Unless the actual correct offset at the time is `+00:00` for
96            // the time zone parsed.)
97            return OffsetConflict::AlwaysOffset.resolve(dt, Offset::UTC, tz);
98        }
99        let offset = parsed_offset.to_offset()?;
100        let is_equal = |parsed: Offset, candidate: Offset| {
101            // If they're equal down to the second, then no amount of rounding
102            // or whatever should change that.
103            if parsed == candidate {
104                return true;
105            }
106            // If the candidate offset we're considering is a whole minute,
107            // then we never need rounding.
108            //
109            // Alternatively, if the parsed offset has an explicit sub-minute
110            // component (even if it's zero), we should use exact equality.
111            // (The error message for this case when "reject" offset
112            // conflict resolution is used is not the best. But this case
113            // is stupidly rare, so I'm not sure it's worth the effort to
114            // improve the error message. I'd be open to a simple patch
115            // though.)
116            if candidate.seconds() % c::SECS_PER_MIN_32 == 0
117                || parsed_offset.has_subminute()
118            {
119                return parsed == candidate;
120            }
121            let Ok(candidate) = candidate.round(Unit::Minute) else {
122                // This is a degenerate case and this is the only sensible
123                // thing to do.
124                return parsed == candidate;
125            };
126            parsed == candidate
127        };
128        offset_conflict.resolve_with(dt, offset, tz, is_equal)
129    }
130
131    #[cfg_attr(feature = "perf-inline", inline(always))]
132    pub(super) fn to_timestamp(&self) -> Result<Timestamp, Error> {
133        let time = self
134            .time
135            .as_ref()
136            .map(|p| p.time)
137            .ok_or(E::MissingTimeInTimestamp)?;
138        let parsed_offset =
139            self.offset.as_ref().ok_or(E::MissingOffsetInTimestamp)?;
140        let offset = parsed_offset.to_offset()?;
141        let dt = DateTime::from_parts(self.date.date, time);
142        let timestamp = offset
143            .to_timestamp(dt)
144            .context(E::ConvertDateTimeToTimestamp { offset })?;
145        Ok(timestamp)
146    }
147
148    #[cfg_attr(feature = "perf-inline", inline(always))]
149    pub(super) fn to_datetime(&self) -> Result<DateTime, Error> {
150        if self.offset.as_ref().map_or(false, |o| o.is_zulu()) {
151            return Err(Error::from(E::CivilDateTimeZulu));
152        }
153        Ok(DateTime::from_parts(self.date.date, self.time()))
154    }
155
156    #[cfg_attr(feature = "perf-inline", inline(always))]
157    pub(super) fn to_date(&self) -> Result<Date, Error> {
158        if self.offset.as_ref().map_or(false, |o| o.is_zulu()) {
159            return Err(Error::from(E::CivilDateTimeZulu));
160        }
161        Ok(self.date.date)
162    }
163
164    #[cfg_attr(feature = "perf-inline", inline(always))]
165    fn time(&self) -> Time {
166        self.time.as_ref().map(|p| p.time).unwrap_or(Time::midnight())
167    }
168}
169
170impl<'i> core::fmt::Display for ParsedDateTime<'i> {
171    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
172        core::fmt::Display::fmt(&self.date, f)?;
173        if let Some(ref time) = self.time {
174            f.write_str("T")?;
175            core::fmt::Display::fmt(&time, f)?;
176        }
177        if let Some(ref offset) = self.offset {
178            core::fmt::Display::fmt(&offset, f)?;
179        }
180        core::fmt::Display::fmt(&self.annotations, f)
181    }
182}
183
184/// The result of parsing a Gregorian calendar civil date.
185#[derive(#[automatically_derived]impl ::core::fmt::Debug for ParsedDate {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "ParsedDate date", &&self.date)
    }
}Debug)]
186pub(super) struct ParsedDate {
187    /// The actual parsed date.
188    date: Date,
189}
190
191impl core::fmt::Display for ParsedDate {
192    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
193        core::fmt::Display::fmt(&self.date, f)
194    }
195}
196
197/// The result of parsing a 24-hour civil time.
198#[derive(#[automatically_derived]impl ::core::fmt::Debug for ParsedTime {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ParsedTime time extended", &self.time, &&self.extended)
    }
}Debug)]
199pub(super) struct ParsedTime {
200    /// The actual parsed time.
201    time: Time,
202    /// Whether the time was parsed in extended format or not.
203    extended: bool,
204}
205
206impl ParsedTime {
207    pub(super) fn to_time(&self) -> Time {
208        self.time
209    }
210}
211
212impl core::fmt::Display for ParsedTime {
213    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
214        core::fmt::Display::fmt(&self.time, f)
215    }
216}
217
218#[derive(#[automatically_derived]impl<'i> ::core::fmt::Debug for ParsedTimeZone<'i> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ParsedTimeZone input kind", &self.input, &&self.kind)
    }
}Debug)]
219pub(super) struct ParsedTimeZone<'i> {
220    /// The original input that the time zone was parsed from.
221    input: escape::Bytes<'i>,
222    /// The kind of time zone parsed.
223    kind: ParsedTimeZoneKind<'i>,
224}
225
226impl<'i> core::fmt::Display for ParsedTimeZone<'i> {
227    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
228        core::fmt::Display::fmt(&self.input, f)
229    }
230}
231
232#[derive(#[automatically_derived]impl<'i> ::core::fmt::Debug for ParsedTimeZoneKind<'i>
    {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Named(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Named",
                    &__self_0),
            Self::Offset(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Offset", &__self_0),
            Self::Posix(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Posix",
                    &__self_0),
        }
    }
}Debug)]
233pub(super) enum ParsedTimeZoneKind<'i> {
234    Named(&'i str),
235    Offset(ParsedOffset),
236    #[cfg(feature = "alloc")]
237    Posix(jcore::tz::posix::TimeZone),
238}
239
240impl<'i> ParsedTimeZone<'i> {
241    pub(super) fn into_time_zone(
242        self,
243        db: &TimeZoneDatabase,
244    ) -> Result<TimeZone, Error> {
245        match self.kind {
246            ParsedTimeZoneKind::Named(iana_name) => {
247                db.get(iana_name).context(E::FailedTzdbLookup)
248            }
249            ParsedTimeZoneKind::Offset(poff) => {
250                let offset =
251                    poff.to_offset().context(E::FailedOffsetNumeric)?;
252                Ok(TimeZone::fixed(offset))
253            }
254            #[cfg(feature = "alloc")]
255            ParsedTimeZoneKind::Posix(posix_tz) => {
256                Ok(TimeZone::from_posix_tz(posix_tz))
257            }
258        }
259    }
260}
261
262/// A parser for Temporal datetimes.
263#[derive(#[automatically_derived]impl ::core::fmt::Debug for DateTimeParser {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "DateTimeParser _priv", &&self._priv)
    }
}Debug)]
264pub(super) struct DateTimeParser {
265    /// There are currently no configuration options for this parser.
266    _priv: (),
267}
268
269impl DateTimeParser {
270    /// Create a new Temporal datetime parser with the default configuration.
271    pub(super) const fn new() -> DateTimeParser {
272        DateTimeParser { _priv: () }
273    }
274
275    // TemporalDateTimeString[ZonedDateTime] :::
276    //   AnnotatedDateTime[?ZonedDateTime]
277    //
278    // AnnotatedDateTime[ZonedDateTime] :::
279    //   [~ZonedDateTime] DateTime TimeZoneAnnotation[opt] Annotations[opt]
280    //   [+ZonedDateTime] DateTime TimeZoneAnnotation Annotations[opt]
281    //
282    // DateTime :::
283    //   Date
284    //   Date DateTimeSeparator TimeSpec DateTimeUTCOffset[opt]
285    #[cfg_attr(feature = "perf-inline", inline(always))]
286    pub(super) fn parse_temporal_datetime<'i>(
287        &self,
288        input: &'i [u8],
289    ) -> Result<Parsed<'i, ParsedDateTime<'i>>, Error> {
290        let Parsed { value: date, input } = self.parse_date_spec(input)?;
291        let Some((&first, tail)) = input.split_first() else {
292            let value = ParsedDateTime {
293                date,
294                time: None,
295                offset: None,
296                annotations: ParsedAnnotations::none(),
297            };
298            return Ok(Parsed { value, input });
299        };
300        let (time, offset, input) = if !#[allow(non_exhaustive_omitted_patterns)] match first {
    b' ' | b'T' | b't' => true,
    _ => false,
}matches!(first, b' ' | b'T' | b't') {
301            (None, None, input)
302        } else {
303            let input = tail;
304            // If there's a separator, then we must parse a time and we are
305            // *allowed* to parse an offset. But without a separator, we don't
306            // support offsets. Just annotations (which are parsed below).
307            let Parsed { value: time, input } = self.parse_time_spec(input)?;
308            let Parsed { value: offset, input } = self.parse_offset(input)?;
309            (Some(time), offset, input)
310        };
311        let Parsed { value: annotations, input } =
312            self.parse_annotations(input)?;
313        let value = ParsedDateTime { date, time, offset, annotations };
314        Ok(Parsed { value, input })
315    }
316
317    // TemporalTimeString :::
318    //   AnnotatedTime
319    //   AnnotatedDateTimeTimeRequired
320    //
321    // AnnotatedTime :::
322    //   TimeDesignator TimeSpec
323    //                  DateTimeUTCOffset[opt]
324    //                  TimeZoneAnnotation[opt]
325    //                  Annotations[opt]
326    //   TimeSpecWithOptionalOffsetNotAmbiguous TimeZoneAnnotation[opt]
327    //                                          Annotations[opt]
328    //
329    // TimeSpecWithOptionalOffsetNotAmbiguous :::
330    //   TimeSpec DateTimeUTCOffsetopt (but not one of ValidMonthDay or DateSpecYearMonth)
331    //
332    // TimeDesignator ::: one of
333    //   T t
334    #[cfg_attr(feature = "perf-inline", inline(always))]
335    pub(super) fn parse_temporal_time<'i>(
336        &self,
337        input: &'i [u8],
338    ) -> Result<Parsed<'i, ParsedTime>, Error> {
339        let mkslice = parse::slicer(input);
340
341        if let Some(input) =
342            input.strip_prefix(b"T").or_else(|| input.strip_prefix(b"t"))
343        {
344            let Parsed { value: time, input } = self.parse_time_spec(input)?;
345            let Parsed { value: offset, input } = self.parse_offset(input)?;
346            if offset.map_or(false, |o| o.is_zulu()) {
347                return Err(Error::from(E::CivilDateTimeZulu));
348            }
349            let Parsed { input, .. } = self.parse_annotations(input)?;
350            return Ok(Parsed { value: time, input });
351        }
352        // We now look for a full datetime and extract the time from that.
353        // We do this before looking for a non-T time-only component because
354        // otherwise things like `2024-06-01T01:02:03` end up having `2024-06`
355        // parsed as a `HHMM-OFFSET` time, and then result in an "ambiguous"
356        // error.
357        //
358        // This is largely a result of us trying to parse a time off of the
359        // beginning of the input without assuming that the time must consume
360        // the entire input.
361        if let Ok(parsed) = self.parse_temporal_datetime(input) {
362            let Parsed { value: dt, input } = parsed;
363            if dt.offset.map_or(false, |o| o.is_zulu()) {
364                return Err(Error::from(E::CivilDateTimeZulu));
365            }
366            let Some(time) = dt.time else {
367                return Err(Error::from(E::MissingTimeInDate));
368            };
369            return Ok(Parsed { value: time, input });
370        }
371
372        // At this point, we look for something that is a time that doesn't
373        // start with a `T`. We need to check that it isn't ambiguous with a
374        // possible date.
375        let Parsed { value: time, input } = self.parse_time_spec(input)?;
376        let Parsed { value: offset, input } = self.parse_offset(input)?;
377        if offset.map_or(false, |o| o.is_zulu()) {
378            return Err(Error::from(E::CivilDateTimeZulu));
379        }
380        // The possible ambiguities occur with the time AND the
381        // optional offset, so try to parse what we have so far as
382        // either a "month-day" or a "year-month." If either succeeds,
383        // then the time is ambiguous and we can report an error.
384        //
385        // ... but this can only happen when the time was parsed in
386        // "basic" mode. i.e., without the `:` separators.
387        if !time.extended {
388            let possibly_ambiguous = mkslice(input);
389            if self.parse_month_day(possibly_ambiguous).is_ok() {
390                return Err(Error::from(E::AmbiguousTimeMonthDay));
391            }
392            if self.parse_year_month(possibly_ambiguous).is_ok() {
393                return Err(Error::from(E::AmbiguousTimeYearMonth));
394            }
395        }
396        // OK... carry on.
397        let Parsed { input, .. } = self.parse_annotations(input)?;
398        Ok(Parsed { value: time, input })
399    }
400
401    #[cfg_attr(feature = "perf-inline", inline(always))]
402    pub(super) fn parse_time_zone<'i>(
403        &self,
404        mut input: &'i [u8],
405    ) -> Result<Parsed<'i, ParsedTimeZone<'i>>, Error> {
406        let &first = input.first().ok_or(E::EmptyTimeZone)?;
407        let original = escape::Bytes(input);
408        if #[allow(non_exhaustive_omitted_patterns)] match first {
    b'+' | b'-' => true,
    _ => false,
}matches!(first, b'+' | b'-') {
409            static P: offset::Parser = offset::Parser::new()
410                .zulu(false)
411                .subminute(true)
412                .subsecond(false);
413            let Parsed { value: offset, input } = P.parse(input)?;
414            let kind = ParsedTimeZoneKind::Offset(offset);
415            let value = ParsedTimeZone { input: original, kind };
416            return Ok(Parsed { value, input });
417        }
418
419        // Creates a "named" parsed time zone, generally meant to
420        // be an IANA time zone identifier. We do this in a couple
421        // different cases below, hence the helper function.
422        let mknamed = |consumed, remaining| {
423            let tzid = core::str::from_utf8(consumed)
424                .map_err(|_| E::InvalidTimeZoneUtf8)?;
425            let kind = ParsedTimeZoneKind::Named(tzid);
426            let value = ParsedTimeZone { input: original, kind };
427            Ok(Parsed { value, input: remaining })
428        };
429        // This part get tricky. The common case is absolutely an IANA time
430        // zone identifier. So we try to parse something that looks like an
431        // IANA tz id.
432        //
433        // In theory, IANA tz ids can never be valid POSIX TZ strings, since
434        // POSIX TZ strings minimally require an offset in them (e.g., `EST5`)
435        // and IANA tz ids aren't supposed to contain numbers. But there are
436        // some legacy IANA tz ids (`EST5EDT`) that do contain numbers.
437        //
438        // However, the legacy IANA tz ids, like `EST5EDT`, are pretty much
439        // nonsense as POSIX TZ strings since there is no DST transition rule.
440        // So in cases of nonsense tz ids, we assume they are IANA tz ids.
441        let mkconsumed = parse::slicer(input);
442        let mut saw_number = false;
443        loop {
444            let Some((&byte, tail)) = input.split_first() else { break };
445            if byte.is_ascii_whitespace() {
446                break;
447            }
448            saw_number = saw_number || byte.is_ascii_digit();
449            input = tail;
450        }
451        let consumed = mkconsumed(input);
452        if !saw_number {
453            return mknamed(consumed, input);
454        }
455        #[cfg(not(feature = "alloc"))]
456        {
457            Err(Error::from(E::AllocPosixTimeZone))
458        }
459        #[cfg(feature = "alloc")]
460        {
461            use jcore::tz::posix;
462
463            match posix::TimeZone::parse_prefix(consumed) {
464                Ok((posix_tz, len)) => {
465                    let kind = ParsedTimeZoneKind::Posix(posix_tz);
466                    let value = ParsedTimeZone { input: original, kind };
467                    Ok(Parsed { value, input: &consumed[len..] })
468                }
469                // We get here for invalid POSIX tz strings, or even if
470                // they are technically valid according to POSIX but not
471                // "reasonable", i.e., `EST5EDT`. Which in that case would
472                // end up doing an IANA tz lookup. (And it might hit because
473                // `EST5EDT` is a legacy IANA tz id. Lol.)
474                Err(_) => mknamed(consumed, input),
475            }
476        }
477    }
478
479    /// Parses an ISO 8601 week date.
480    ///
481    /// Note that this isn't part of the Temporal ISO 8601 spec. We put it here
482    /// because it shares a fair bit of code with parsing regular ISO 8601
483    /// dates.
484    #[cfg_attr(feature = "perf-inline", inline(always))]
485    pub(super) fn parse_iso_week_date<'i>(
486        &self,
487        input: &'i [u8],
488    ) -> Result<Parsed<'i, ISOWeekDate>, Error> {
489        // Parse year component.
490        let Parsed { value: year, input } = self.parse_year(input)?;
491        let extended = input.starts_with(b"-");
492
493        // Parse optional separator.
494        let Parsed { input, .. } = self
495            .parse_date_separator(input, extended)
496            .context(E::FailedSeparatorAfterYear)?;
497
498        // Parse 'W' prefix before week num.
499        let Parsed { input, .. } = self
500            .parse_week_prefix(input)
501            .context(E::FailedWeekNumberPrefixInDate)?;
502
503        // Parse week num component.
504        let Parsed { value: week, input } = self.parse_week_num(input)?;
505
506        // Parse optional separator.
507        let Parsed { input, .. } = self
508            .parse_date_separator(input, extended)
509            .context(E::FailedSeparatorAfterWeekNumber)?;
510
511        // Parse day component.
512        let Parsed { value: weekday, input } = self.parse_weekday(input)?;
513
514        let iso_week_date = ISOWeekDate::new(year, week, weekday)
515            .context(E::InvalidWeekDate)?;
516
517        Ok(Parsed { value: iso_week_date, input: input })
518    }
519
520    // Date :::
521    //   DateYear - DateMonth - DateDay
522    //   DateYear DateMonth DateDay
523    #[cfg_attr(feature = "perf-inline", inline(always))]
524    fn parse_date_spec<'i>(
525        &self,
526        input: &'i [u8],
527    ) -> Result<Parsed<'i, ParsedDate>, Error> {
528        // Parse year component.
529        let Parsed { value: year, input } = self.parse_year(input)?;
530        let extended = input.starts_with(b"-");
531
532        // Parse optional separator.
533        let Parsed { input, .. } = self
534            .parse_date_separator(input, extended)
535            .context(E::FailedSeparatorAfterYear)?;
536
537        // Parse month component.
538        let Parsed { value: month, input } = self.parse_month(input)?;
539
540        // Parse optional separator.
541        let Parsed { input, .. } = self
542            .parse_date_separator(input, extended)
543            .context(E::FailedSeparatorAfterMonth)?;
544
545        // Parse day component.
546        let Parsed { value: day, input } = self.parse_day(input)?;
547
548        let date = Date::new(year, month, day).context(E::InvalidDate)?;
549        let value = ParsedDate { date };
550        Ok(Parsed { value, input })
551    }
552
553    // TimeSpec :::
554    //   TimeHour
555    //   TimeHour : TimeMinute
556    //   TimeHour TimeMinute
557    //   TimeHour : TimeMinute : TimeSecond TimeFraction[opt]
558    //   TimeHour TimeMinute TimeSecond TimeFraction[opt]
559    #[cfg_attr(feature = "perf-inline", inline(always))]
560    fn parse_time_spec<'i>(
561        &self,
562        input: &'i [u8],
563    ) -> Result<Parsed<'i, ParsedTime>, Error> {
564        // Parse hour component.
565        let Parsed { value: hour, input } = self.parse_hour(input)?;
566        let extended = input.starts_with(b":");
567
568        // Parse optional minute component.
569        let Parsed { value: has_minute, input } =
570            self.parse_time_separator(input, extended);
571        if !has_minute {
572            // OK because we know `hour` is in bounds and all combinations of
573            // `hour` with zeros are valid `Time` values.
574            let time = Time::new(hour, 0, 0, 0).unwrap();
575            let value = ParsedTime { time, extended };
576            return Ok(Parsed { value, input });
577        }
578        let Parsed { value: minute, input } = self.parse_minute(input)?;
579
580        // Parse optional second component.
581        let Parsed { value: has_second, input } =
582            self.parse_time_separator(input, extended);
583        if !has_second {
584            // OK because we know `hour` and `minute` are in bounds and all
585            // combinations of `hour` and `minute` with zero seconds/nanos are
586            // valid `Time` values.
587            let time = Time::new(hour, minute, 0, 0).unwrap();
588            let value = ParsedTime { time, extended };
589            return Ok(Parsed { value, input });
590        }
591        let Parsed { value: second, input } = self.parse_second(input)?;
592
593        // Parse an optional fractional component.
594        let Parsed { value: nanosecond, input } =
595            parse_temporal_fraction(input)
596                .context(E::FailedFractionalSecondInTime)?;
597
598        // OK because we know that all our components are in bounds and all
599        // combinations of in-bounds components are valid `Time` values.
600        let time = Time::new(
601            hour,
602            minute,
603            second,
604            // OK because `parse_temporal_fraction` guarantees
605            // `0..=999_999_999`.
606            nanosecond.map(|n| i32::try_from(n).unwrap()).unwrap_or(0),
607        )
608        .unwrap();
609        let value = ParsedTime { time, extended };
610        Ok(Parsed { value, input })
611    }
612
613    // ValidMonthDay :::
614    //   DateMonth -[opt] 0 NonZeroDigit
615    //   DateMonth -[opt] 1 DecimalDigit
616    //   DateMonth -[opt] 2 DecimalDigit
617    //   DateMonth -[opt] 30 but not one of 0230 or 02-30
618    //   DateMonthWithThirtyOneDays -opt 31
619    //
620    // DateMonthWithThirtyOneDays ::: one of
621    //   01 03 05 07 08 10 12
622    //
623    // NOTE: Jiff doesn't have a "month-day" type, but we still have a parsing
624    // function for it so that we can detect ambiguous time strings.
625    #[cfg_attr(feature = "perf-inline", inline(always))]
626    fn parse_month_day<'i>(
627        &self,
628        input: &'i [u8],
629    ) -> Result<Parsed<'i, ()>, Error> {
630        // Parse month component.
631        let Parsed { value: month, mut input } = self.parse_month(input)?;
632
633        // Skip over optional separator.
634        if let Some(tail) = input.strip_prefix(b"-") {
635            input = tail;
636        }
637
638        // Parse day component.
639        let Parsed { value: day, input } = self.parse_day(input)?;
640
641        // Check that the month-day is valid. Since Temporal's month-day
642        // permits 02-29, we use a leap year. The error message here is
643        // probably confusing, but these errors should never be exposed to the
644        // user.
645        let _ = Date::new(2024, month, day).context(E::InvalidMonthDay)?;
646
647        // We have a valid year-month. But we don't return it because we just
648        // need to check validity.
649        Ok(Parsed { value: (), input })
650    }
651
652    // DateSpecYearMonth :::
653    //   DateYear -[opt] DateMonth
654    //
655    // NOTE: Jiff doesn't have a "year-month" type, but we still have a parsing
656    // function for it so that we can detect ambiguous time strings.
657    #[cfg_attr(feature = "perf-inline", inline(always))]
658    fn parse_year_month<'i>(
659        &self,
660        input: &'i [u8],
661    ) -> Result<Parsed<'i, ()>, Error> {
662        // Parse year component.
663        let Parsed { value: year, mut input } = self.parse_year(input)?;
664
665        // Skip over optional separator.
666        if let Some(tail) = input.strip_prefix(b"-") {
667            input = tail;
668        }
669
670        // Parse month component.
671        let Parsed { value: month, input } = self.parse_month(input)?;
672
673        // Check that the year-month is valid. We just use a day of 1, since
674        // every month in every year must have a day 1.
675        let _ = Date::new(year, month, 1).context(E::InvalidYearMonth)?;
676
677        // We have a valid year-month. But we don't return it because we just
678        // need to check validity.
679        Ok(Parsed { value: (), input })
680    }
681
682    // DateYear :::
683    //   DecimalDigit DecimalDigit DecimalDigit DecimalDigit
684    //   TemporalSign DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit
685    //
686    // NOTE: I don't really like the fact that in order to write a negative
687    // year, you need to use the six digit variant. Like, why not allow
688    // `-0001`? I'm not sure why, so for Chesterton's fence reasons, I'm
689    // sticking with the Temporal spec. But I may loosen this in the future. We
690    // should be careful not to introduce any possible ambiguities, though, I
691    // don't think there are any?
692    #[cfg_attr(feature = "perf-inline", inline(always))]
693    fn parse_year<'i>(
694        &self,
695        input: &'i [u8],
696    ) -> Result<Parsed<'i, i16>, Error> {
697        let Parsed { value: sign, input } = self.parse_year_sign(input);
698        if let Some(sign) = sign {
699            return self.parse_signed_year(input, sign);
700        }
701
702        let (year, input) =
703            parse::split(input, 4).ok_or(E::ExpectedFourDigitYear)?;
704        let year =
705            parse::bi64::<b::Year>(year).context(E::ParseYearFourDigit)?;
706        Ok(Parsed { value: year, input })
707    }
708
709    #[cold]
710    #[inline(never)]
711    fn parse_signed_year<'i>(
712        &self,
713        input: &'i [u8],
714        sign: Sign,
715    ) -> Result<Parsed<'i, i16>, Error> {
716        let (year, input) =
717            parse::split(input, 6).ok_or(E::ExpectedSixDigitYear)?;
718        let year =
719            parse::bi64::<b::Year>(year).context(E::ParseYearSixDigit)?;
720        if year == 0 && sign.is_negative() {
721            return Err(Error::from(E::InvalidYearZero));
722        }
723        Ok(Parsed { value: sign * year, input })
724    }
725
726    // DateMonth :::
727    //   0 NonZeroDigit
728    //   10
729    //   11
730    //   12
731    #[cfg_attr(feature = "perf-inline", inline(always))]
732    fn parse_month<'i>(
733        &self,
734        input: &'i [u8],
735    ) -> Result<Parsed<'i, i8>, Error> {
736        let (month, input) =
737            parse::split(input, 2).ok_or(E::ExpectedTwoDigitMonth)?;
738        let month =
739            parse::bi64::<b::Month>(month).context(E::ParseMonthTwoDigit)?;
740        Ok(Parsed { value: month, input })
741    }
742
743    // DateDay :::
744    //   0 NonZeroDigit
745    //   1 DecimalDigit
746    //   2 DecimalDigit
747    //   30
748    //   31
749    #[cfg_attr(feature = "perf-inline", inline(always))]
750    fn parse_day<'i>(&self, input: &'i [u8]) -> Result<Parsed<'i, i8>, Error> {
751        let (day, input) =
752            parse::split(input, 2).ok_or(E::ExpectedTwoDigitDay)?;
753        let day = parse::bi64::<b::Day>(day).context(E::ParseDayTwoDigit)?;
754        Ok(Parsed { value: day, input })
755    }
756
757    // TimeHour :::
758    //   Hour
759    //
760    // Hour :::
761    //   0 DecimalDigit
762    //   1 DecimalDigit
763    //   20
764    //   21
765    //   22
766    //   23
767    #[cfg_attr(feature = "perf-inline", inline(always))]
768    fn parse_hour<'i>(
769        &self,
770        input: &'i [u8],
771    ) -> Result<Parsed<'i, i8>, Error> {
772        let (hour, input) =
773            parse::split(input, 2).ok_or(E::ExpectedTwoDigitHour)?;
774        let hour =
775            parse::bi64::<b::Hour>(hour).context(E::ParseHourTwoDigit)?;
776        Ok(Parsed { value: hour, input })
777    }
778
779    // TimeMinute :::
780    //   MinuteSecond
781    //
782    // MinuteSecond :::
783    //   0 DecimalDigit
784    //   1 DecimalDigit
785    //   2 DecimalDigit
786    //   3 DecimalDigit
787    //   4 DecimalDigit
788    //   5 DecimalDigit
789    #[cfg_attr(feature = "perf-inline", inline(always))]
790    fn parse_minute<'i>(
791        &self,
792        input: &'i [u8],
793    ) -> Result<Parsed<'i, i8>, Error> {
794        let (minute, input) =
795            parse::split(input, 2).ok_or(E::ExpectedTwoDigitMinute)?;
796        let minute = parse::bi64::<b::Minute>(minute)
797            .context(E::ParseMinuteTwoDigit)?;
798        Ok(Parsed { value: minute, input })
799    }
800
801    // TimeSecond :::
802    //   MinuteSecond
803    //   60
804    //
805    // MinuteSecond :::
806    //   0 DecimalDigit
807    //   1 DecimalDigit
808    //   2 DecimalDigit
809    //   3 DecimalDigit
810    //   4 DecimalDigit
811    //   5 DecimalDigit
812    #[cfg_attr(feature = "perf-inline", inline(always))]
813    fn parse_second<'i>(
814        &self,
815        input: &'i [u8],
816    ) -> Result<Parsed<'i, i8>, Error> {
817        let (second, input) =
818            parse::split(input, 2).ok_or(E::ExpectedTwoDigitSecond)?;
819        let mut second = parse::bi64::<b::LeapSecond>(second)
820            .context(E::ParseSecondTwoDigit)?;
821        // NOTE: I believe Temporal allows one to make this configurable. That
822        // is, to reject it. But for now, we just always clamp a leap second.
823        if second == 60 {
824            second = 59;
825        }
826        Ok(Parsed { value: second, input })
827    }
828
829    #[cfg_attr(feature = "perf-inline", inline(always))]
830    fn parse_offset<'i>(
831        &self,
832        input: &'i [u8],
833    ) -> Result<Parsed<'i, Option<ParsedOffset>>, Error> {
834        const P: offset::Parser =
835            offset::Parser::new().zulu(true).subminute(true);
836        P.parse_optional(input)
837    }
838
839    #[cfg_attr(feature = "perf-inline", inline(always))]
840    fn parse_annotations<'i>(
841        &self,
842        input: &'i [u8],
843    ) -> Result<Parsed<'i, ParsedAnnotations<'i>>, Error> {
844        const P: rfc9557::Parser = rfc9557::Parser::new();
845        if input.first().map_or(true, |&b| b != b'[') {
846            let value = ParsedAnnotations::none();
847            return Ok(Parsed { input, value });
848        }
849        P.parse(input)
850    }
851
852    /// Parses the separator that is expected to appear between
853    /// date components.
854    ///
855    /// When in extended mode, a `-` is expected. When not in extended mode,
856    /// no input is consumed and this routine never fails.
857    #[cfg_attr(feature = "perf-inline", inline(always))]
858    fn parse_date_separator<'i>(
859        &self,
860        input: &'i [u8],
861        extended: bool,
862    ) -> Result<Parsed<'i, ()>, Error> {
863        if !extended {
864            // If we see a '-' when not in extended mode, then we can report
865            // a better error message than, e.g., "-3 isn't a valid day."
866            if input.starts_with(b"-") {
867                return Err(Error::from(E::ExpectedNoSeparator));
868            }
869            return Ok(Parsed { value: (), input });
870        }
871        let (&first, input) =
872            input.split_first().ok_or(E::ExpectedSeparatorFoundEndOfInput)?;
873        if first != b'-' {
874            return Err(Error::from(E::ExpectedSeparatorFoundByte {
875                byte: first,
876            }));
877        }
878        Ok(Parsed { value: (), input })
879    }
880
881    /// Parses the separator that is expected to appear between time
882    /// components. When `true` is returned, we expect to parse the next
883    /// component. When `false` is returned, then no separator was found and
884    /// there is no expectation of finding another component.
885    ///
886    /// When in extended mode, true is returned if and only if a separator is
887    /// found.
888    ///
889    /// When in basic mode (not extended), then a subsequent component is only
890    /// expected when `input` begins with two ASCII digits.
891    #[cfg_attr(feature = "perf-inline", inline(always))]
892    fn parse_time_separator<'i>(
893        &self,
894        mut input: &'i [u8],
895        extended: bool,
896    ) -> Parsed<'i, bool> {
897        if !extended {
898            let expected = parse::split(input, 2)
899                .map_or(false, |(prefix, _)| {
900                    prefix.iter().all(u8::is_ascii_digit)
901                });
902            return Parsed { value: expected, input };
903        }
904        let mut is_separator = false;
905        if let Some(tail) = input.strip_prefix(b":") {
906            is_separator = true;
907            input = tail;
908        }
909        Parsed { value: is_separator, input }
910    }
911
912    // TemporalSign :::
913    //   ASCIISign
914    //   <MINUS>
915    //
916    // ASCIISign ::: one of
917    //   + -
918    //
919    // NOTE: We specifically only support ASCII signs. I think Temporal needs
920    // to support `<MINUS>` because of other things in ECMA script that
921    // require it?[1]
922    //
923    // [1]: https://github.com/tc39/proposal-temporal/issues/2843
924    #[cfg_attr(feature = "perf-inline", inline(always))]
925    fn parse_year_sign<'i>(
926        &self,
927        input: &'i [u8],
928    ) -> Parsed<'i, Option<Sign>> {
929        let Some((&sign, tail)) = input.split_first() else {
930            return Parsed { value: None, input };
931        };
932        let sign = if sign == b'+' {
933            Sign::Positive
934        } else if sign == b'-' {
935            Sign::Negative
936        } else {
937            return Parsed { value: None, input };
938        };
939        Parsed { value: Some(sign), input: tail }
940    }
941
942    /// Parses the `W` that is expected to appear before the week component in
943    /// an ISO 8601 week date.
944    #[cfg_attr(feature = "perf-inline", inline(always))]
945    fn parse_week_prefix<'i>(
946        &self,
947        input: &'i [u8],
948    ) -> Result<Parsed<'i, ()>, Error> {
949        let (&first, input) =
950            input.split_first().ok_or(E::ExpectedWeekPrefixFoundEndOfInput)?;
951        if !#[allow(non_exhaustive_omitted_patterns)] match first {
    b'W' | b'w' => true,
    _ => false,
}matches!(first, b'W' | b'w') {
952            return Err(Error::from(E::ExpectedWeekPrefixFoundByte {
953                byte: first,
954            }));
955        }
956        Ok(Parsed { value: (), input })
957    }
958
959    /// Parses the week number that follows a `W` in an ISO week date.
960    #[cfg_attr(feature = "perf-inline", inline(always))]
961    fn parse_week_num<'i>(
962        &self,
963        input: &'i [u8],
964    ) -> Result<Parsed<'i, i8>, Error> {
965        let (week_num, input) =
966            parse::split(input, 2).ok_or(E::ExpectedTwoDigitWeekNumber)?;
967        let week_num = parse::bi64::<b::ISOWeek>(week_num)
968            .context(E::ParseWeekNumberTwoDigit)?;
969        Ok(Parsed { value: week_num, input })
970    }
971
972    /// Parses the weekday (1-indexed, starting with Monday) in an ISO 8601
973    /// week date.
974    #[cfg_attr(feature = "perf-inline", inline(always))]
975    fn parse_weekday<'i>(
976        &self,
977        input: &'i [u8],
978    ) -> Result<Parsed<'i, Weekday>, Error> {
979        let (weekday, input) =
980            parse::split(input, 1).ok_or(E::ExpectedOneDigitWeekday)?;
981        let weekday = parse::bi64::<b::WeekdayMondayOne>(weekday)
982            .context(E::ParseWeekdayOneDigit)?;
983        // OK because we know `weekday` is in bounds from above.
984        let weekday = Weekday::from_monday_one_offset(weekday).unwrap();
985        Ok(Parsed { value: weekday, input })
986    }
987}
988
989/// A parser for Temporal spans.
990///
991/// Note that in Temporal, a "span" is called a "duration."
992#[derive(#[automatically_derived]impl ::core::fmt::Debug for SpanParser {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "SpanParser _priv", &&self._priv)
    }
}Debug)]
993pub(super) struct SpanParser {
994    /// There are currently no configuration options for this parser.
995    _priv: (),
996}
997
998impl SpanParser {
999    /// Create a new Temporal span parser with the default configuration.
1000    pub(super) const fn new() -> SpanParser {
1001        SpanParser { _priv: () }
1002    }
1003
1004    #[cfg_attr(feature = "perf-inline", inline(always))]
1005    pub(super) fn parse_span<I: AsRef<[u8]>>(
1006        &self,
1007        input: I,
1008    ) -> Result<Span, Error> {
1009        #[inline(never)]
1010        fn imp(p: &SpanParser, input: &[u8]) -> Result<Span, Error> {
1011            let mut builder = DurationUnits::default();
1012            let parsed = p.parse_calendar_and_time(input, &mut builder)?;
1013            let parsed = parsed.and_then(|_| builder.to_span())?;
1014            parsed.into_full()
1015        }
1016        imp(self, input.as_ref())
1017    }
1018
1019    #[cfg_attr(feature = "perf-inline", inline(always))]
1020    pub(super) fn parse_signed_duration<I: AsRef<[u8]>>(
1021        &self,
1022        input: I,
1023    ) -> Result<SignedDuration, Error> {
1024        #[inline(never)]
1025        fn imp(p: &SpanParser, input: &[u8]) -> Result<SignedDuration, Error> {
1026            let mut builder = DurationUnits::default();
1027            let parsed = p.parse_time_only(input, &mut builder)?;
1028            let parsed = parsed.and_then(|_| builder.to_signed_duration())?;
1029            parsed.into_full()
1030        }
1031        imp(self, input.as_ref())
1032    }
1033
1034    #[cfg_attr(feature = "perf-inline", inline(always))]
1035    pub(super) fn parse_unsigned_duration<I: AsRef<[u8]>>(
1036        &self,
1037        input: I,
1038    ) -> Result<core::time::Duration, Error> {
1039        #[inline(never)]
1040        fn imp(
1041            p: &SpanParser,
1042            input: &[u8],
1043        ) -> Result<core::time::Duration, Error> {
1044            let mut builder = DurationUnits::default();
1045            let parsed = p.parse_time_only(input, &mut builder)?;
1046            let parsed =
1047                parsed.and_then(|_| builder.to_unsigned_duration())?;
1048            let d = parsed.value;
1049            parsed.into_full_with(format_args!("{0:?}", d)format_args!("{d:?}"))
1050        }
1051        imp(self, input.as_ref())
1052    }
1053
1054    #[cfg_attr(feature = "perf-inline", inline(always))]
1055    fn parse_calendar_and_time<'i>(
1056        &self,
1057        input: &'i [u8],
1058        builder: &mut DurationUnits,
1059    ) -> Result<Parsed<'i, ()>, Error> {
1060        let (sign, input) =
1061            if !input.first().map_or(false, |&b| #[allow(non_exhaustive_omitted_patterns)] match b {
    b'+' | b'-' => true,
    _ => false,
}matches!(b, b'+' | b'-')) {
1062                (Sign::Positive, input)
1063            } else {
1064                let Parsed { value: sign, input } = self.parse_sign(input);
1065                (sign, input)
1066            };
1067
1068        let Parsed { input, .. } = self.parse_duration_designator(input)?;
1069        let Parsed { input, .. } = self.parse_date_units(input, builder)?;
1070        let Parsed { value: has_time, mut input } =
1071            self.parse_time_designator(input);
1072        if has_time {
1073            let parsed = self.parse_time_units(input, builder)?;
1074            input = parsed.input;
1075
1076            if builder.get_min().map_or(true, |min| min > Unit::Hour) {
1077                return Err(Error::from(E::ExpectedTimeUnits));
1078            }
1079        }
1080        builder.set_sign(sign);
1081        Ok(Parsed { value: (), input })
1082    }
1083
1084    #[cfg_attr(feature = "perf-inline", inline(always))]
1085    fn parse_time_only<'i>(
1086        &self,
1087        input: &'i [u8],
1088        builder: &mut DurationUnits,
1089    ) -> Result<Parsed<'i, ()>, Error> {
1090        let (sign, input) =
1091            if !input.first().map_or(false, |&b| #[allow(non_exhaustive_omitted_patterns)] match b {
    b'+' | b'-' => true,
    _ => false,
}matches!(b, b'+' | b'-')) {
1092                (Sign::Positive, input)
1093            } else {
1094                let Parsed { value: sign, input } = self.parse_sign(input);
1095                (sign, input)
1096            };
1097
1098        let Parsed { input, .. } = self.parse_duration_designator(input)?;
1099        let Parsed { value: has_time, input } =
1100            self.parse_time_designator(input);
1101        if !has_time {
1102            return Err(Error::from(E::ExpectedTimeDesignator));
1103        }
1104
1105        let Parsed { input, .. } = self.parse_time_units(input, builder)?;
1106        if builder.get_min().map_or(true, |min| min > Unit::Hour) {
1107            return Err(Error::from(E::ExpectedTimeUnits));
1108        }
1109        builder.set_sign(sign);
1110        Ok(Parsed { value: (), input })
1111    }
1112
1113    /// Parses consecutive units from an ISO 8601 duration string into the
1114    /// `DurationUnits` given.
1115    #[cfg_attr(feature = "perf-inline", inline(always))]
1116    fn parse_date_units<'i>(
1117        &self,
1118        mut input: &'i [u8],
1119        builder: &mut DurationUnits,
1120    ) -> Result<Parsed<'i, ()>, Error> {
1121        loop {
1122            let parsed = self.parse_unit_value(input)?;
1123            input = parsed.input;
1124            let Some(value) = parsed.value else { break };
1125
1126            let parsed = self.parse_unit_date_designator(input)?;
1127            input = parsed.input;
1128            let unit = parsed.value;
1129
1130            builder.set_unit_value(unit, value)?;
1131        }
1132        Ok(Parsed { value: (), input })
1133    }
1134
1135    /// Parses consecutive time units from an ISO 8601 duration string into the
1136    /// `DurationUnits` given.
1137    #[cfg_attr(feature = "perf-inline", inline(always))]
1138    fn parse_time_units<'i>(
1139        &self,
1140        mut input: &'i [u8],
1141        builder: &mut DurationUnits,
1142    ) -> Result<Parsed<'i, ()>, Error> {
1143        loop {
1144            let parsed = self.parse_unit_value(input)?;
1145            input = parsed.input;
1146            let Some(value) = parsed.value else { break };
1147
1148            let parsed = parse_temporal_fraction(input)?;
1149            input = parsed.input;
1150            let fraction = parsed.value;
1151
1152            let parsed = self.parse_unit_time_designator(input)?;
1153            input = parsed.input;
1154            let unit = parsed.value;
1155
1156            builder.set_unit_value(unit, value)?;
1157            if let Some(fraction) = fraction {
1158                builder.set_fraction(fraction)?;
1159                // Once we see a fraction, we are done. We don't permit parsing
1160                // any more units. That is, a fraction can only occur on the
1161                // lowest unit of time.
1162                break;
1163            }
1164        }
1165        Ok(Parsed { value: (), input })
1166    }
1167
1168    #[cfg_attr(feature = "perf-inline", inline(always))]
1169    fn parse_unit_value<'i>(
1170        &self,
1171        input: &'i [u8],
1172    ) -> Result<Parsed<'i, Option<u64>>, Error> {
1173        let (value, input) = parse::u64_prefix(input)?;
1174        Ok(Parsed { value, input })
1175    }
1176
1177    #[cfg_attr(feature = "perf-inline", inline(always))]
1178    fn parse_unit_date_designator<'i>(
1179        &self,
1180        input: &'i [u8],
1181    ) -> Result<Parsed<'i, Unit>, Error> {
1182        let (&first, input) = input
1183            .split_first()
1184            .ok_or(E::ExpectedDateDesignatorFoundEndOfInput)?;
1185        let unit = match first {
1186            b'Y' | b'y' => Unit::Year,
1187            b'M' | b'm' => Unit::Month,
1188            b'W' | b'w' => Unit::Week,
1189            b'D' | b'd' => Unit::Day,
1190            _ => {
1191                return Err(Error::from(E::ExpectedDateDesignatorFoundByte {
1192                    byte: first,
1193                }));
1194            }
1195        };
1196        Ok(Parsed { value: unit, input })
1197    }
1198
1199    #[cfg_attr(feature = "perf-inline", inline(always))]
1200    fn parse_unit_time_designator<'i>(
1201        &self,
1202        input: &'i [u8],
1203    ) -> Result<Parsed<'i, Unit>, Error> {
1204        let (&first, input) = input
1205            .split_first()
1206            .ok_or(E::ExpectedTimeDesignatorFoundEndOfInput)?;
1207        let unit = match first {
1208            b'H' | b'h' => Unit::Hour,
1209            b'M' | b'm' => Unit::Minute,
1210            b'S' | b's' => Unit::Second,
1211            _ => {
1212                return Err(Error::from(E::ExpectedTimeDesignatorFoundByte {
1213                    byte: first,
1214                }));
1215            }
1216        };
1217        Ok(Parsed { value: unit, input })
1218    }
1219
1220    // DurationDesignator ::: one of
1221    //   P p
1222    #[cfg_attr(feature = "perf-inline", inline(always))]
1223    fn parse_duration_designator<'i>(
1224        &self,
1225        input: &'i [u8],
1226    ) -> Result<Parsed<'i, ()>, Error> {
1227        let (&first, input) = input
1228            .split_first()
1229            .ok_or(E::ExpectedDurationDesignatorFoundEndOfInput)?;
1230        if !#[allow(non_exhaustive_omitted_patterns)] match first {
    b'P' | b'p' => true,
    _ => false,
}matches!(first, b'P' | b'p') {
1231            return Err(Error::from(E::ExpectedDurationDesignatorFoundByte {
1232                byte: first,
1233            }));
1234        }
1235        Ok(Parsed { value: (), input })
1236    }
1237
1238    // TimeDesignator ::: one of
1239    //   T t
1240    #[cfg_attr(feature = "perf-inline", inline(always))]
1241    fn parse_time_designator<'i>(&self, input: &'i [u8]) -> Parsed<'i, bool> {
1242        let Some((&first, tail)) = input.split_first() else {
1243            return Parsed { value: false, input };
1244        };
1245        if !#[allow(non_exhaustive_omitted_patterns)] match first {
    b'T' | b't' => true,
    _ => false,
}matches!(first, b'T' | b't') {
1246            return Parsed { value: false, input };
1247        }
1248        Parsed { value: true, input: tail }
1249    }
1250
1251    // TemporalSign :::
1252    //   ASCIISign
1253    //   <MINUS>
1254    //
1255    // NOTE: Like with other things with signs, we don't support the Unicode
1256    // <MINUS> sign. Just ASCII.
1257    #[cold]
1258    #[inline(never)]
1259    fn parse_sign<'i>(&self, input: &'i [u8]) -> Parsed<'i, Sign> {
1260        if let Some(tail) = input.strip_prefix(b"+") {
1261            Parsed { value: Sign::Positive, input: tail }
1262        } else if let Some(tail) = input.strip_prefix(b"-") {
1263            Parsed { value: Sign::Negative, input: tail }
1264        } else {
1265            Parsed { value: Sign::Positive, input }
1266        }
1267    }
1268}
1269
1270#[cfg(feature = "alloc")]
1271#[cfg(test)]
1272mod tests {
1273    use super::*;
1274
1275    #[test]
1276    fn ok_signed_duration() {
1277        let p = |input: &[u8]| {
1278            SpanParser::new().parse_signed_duration(input).unwrap()
1279        };
1280
1281        insta::assert_debug_snapshot!(p(b"PT0s"), @"0s");
1282        insta::assert_debug_snapshot!(p(b"PT0.000000001s"), @"1ns");
1283        insta::assert_debug_snapshot!(p(b"-PT0.000000001s"), @"-1ns");
1284        insta::assert_debug_snapshot!(p(b"-PT0.5s"), @"-500000000ns");
1285        insta::assert_debug_snapshot!(p(b"PT1s"), @"1s");
1286        insta::assert_debug_snapshot!(p(b"PT59s"), @"59s");
1287        insta::assert_debug_snapshot!(p(b"PT60s"), @"60s");
1288        insta::assert_debug_snapshot!(p(b"PT1m"), @"60s");
1289        insta::assert_debug_snapshot!(p(b"PT1m0.000000001s"), @"60s 1ns");
1290        insta::assert_debug_snapshot!(p(b"PT1.25m"), @"75s");
1291        insta::assert_debug_snapshot!(p(b"PT1h"), @"3600s");
1292        insta::assert_debug_snapshot!(p(b"PT1h0.000000001s"), @"3600s 1ns");
1293        insta::assert_debug_snapshot!(p(b"PT1.25h"), @"4500s");
1294
1295        insta::assert_debug_snapshot!(p(b"-PT2562047788015215h30m8.999999999s"), @"-9223372036854775808s 999999999ns");
1296        insta::assert_debug_snapshot!(p(b"PT2562047788015215h30m7.999999999s"), @"9223372036854775807s 999999999ns");
1297
1298        insta::assert_debug_snapshot!(p(b"PT9223372036854775807S"), @"9223372036854775807s");
1299        insta::assert_debug_snapshot!(p(b"-PT9223372036854775808S"), @"-9223372036854775808s");
1300    }
1301
1302    #[test]
1303    fn err_signed_duration() {
1304        let p = |input: &[u8]| {
1305            SpanParser::new().parse_signed_duration(input).unwrap_err()
1306        };
1307
1308        insta::assert_snapshot!(
1309            p(b"P0d"),
1310            @"parsing ISO 8601 duration in this context requires that the duration contain a time component and no components of days or greater",
1311        );
1312        insta::assert_snapshot!(
1313            p(b"PT0d"),
1314            @"expected to find time unit designator suffix (`H`, `M` or `S`), but found `d` instead",
1315        );
1316        insta::assert_snapshot!(
1317            p(b"P0dT1s"),
1318            @"parsing ISO 8601 duration in this context requires that the duration contain a time component and no components of days or greater",
1319        );
1320
1321        insta::assert_snapshot!(
1322            p(b""),
1323            @"expected to find duration beginning with `P` or `p`, but found end of input",
1324        );
1325        insta::assert_snapshot!(
1326            p(b"P"),
1327            @"parsing ISO 8601 duration in this context requires that the duration contain a time component and no components of days or greater",
1328        );
1329        insta::assert_snapshot!(
1330            p(b"PT"),
1331            @"found a time designator (`T` or `t`) in an ISO 8601 duration string, but did not find any time units",
1332        );
1333        insta::assert_snapshot!(
1334            p(b"PTs"),
1335            @"found a time designator (`T` or `t`) in an ISO 8601 duration string, but did not find any time units",
1336        );
1337
1338        insta::assert_snapshot!(
1339            p(b"PT1s1m"),
1340            @"found value with unit minute after unit second, but units must be written from largest to smallest (and they can't be repeated)",
1341        );
1342        insta::assert_snapshot!(
1343            p(b"PT1s1h"),
1344            @"found value with unit hour after unit second, but units must be written from largest to smallest (and they can't be repeated)",
1345        );
1346        insta::assert_snapshot!(
1347            p(b"PT1m1h"),
1348            @"found value with unit hour after unit minute, but units must be written from largest to smallest (and they can't be repeated)",
1349        );
1350
1351        insta::assert_snapshot!(
1352            p(b"-PT9223372036854775809s"),
1353            @"value for seconds is too big (or small) to fit into a signed 64-bit integer",
1354        );
1355        insta::assert_snapshot!(
1356            p(b"PT9223372036854775808s"),
1357            @"value for seconds is too big (or small) to fit into a signed 64-bit integer",
1358        );
1359
1360        insta::assert_snapshot!(
1361            p(b"PT1m9223372036854775807s"),
1362            @"accumulated duration overflowed when adding value to unit second",
1363        );
1364        insta::assert_snapshot!(
1365            p(b"PT2562047788015215.6h"),
1366            @"accumulated duration overflowed when adding fractional value to unit hour",
1367        );
1368    }
1369
1370    #[test]
1371    fn ok_unsigned_duration() {
1372        let p = |input: &[u8]| {
1373            SpanParser::new().parse_unsigned_duration(input).unwrap()
1374        };
1375
1376        insta::assert_debug_snapshot!(p(b"PT0s"), @"0ns");
1377        insta::assert_debug_snapshot!(p(b"PT0.000000001s"), @"1ns");
1378        insta::assert_debug_snapshot!(p(b"PT1s"), @"1s");
1379        insta::assert_debug_snapshot!(p(b"+PT1s"), @"1s");
1380        insta::assert_debug_snapshot!(p(b"PT59s"), @"59s");
1381        insta::assert_debug_snapshot!(p(b"PT60s"), @"60s");
1382        insta::assert_debug_snapshot!(p(b"PT1m"), @"60s");
1383        insta::assert_debug_snapshot!(p(b"PT1m0.000000001s"), @"60.000000001s");
1384        insta::assert_debug_snapshot!(p(b"PT1.25m"), @"75s");
1385        insta::assert_debug_snapshot!(p(b"PT1h"), @"3600s");
1386        insta::assert_debug_snapshot!(p(b"PT1h0.000000001s"), @"3600.000000001s");
1387        insta::assert_debug_snapshot!(p(b"PT1.25h"), @"4500s");
1388
1389        insta::assert_debug_snapshot!(p(b"PT2562047788015215h30m7.999999999s"), @"9223372036854775807.999999999s");
1390        insta::assert_debug_snapshot!(p(b"PT5124095576030431H15.999999999S"), @"18446744073709551615.999999999s");
1391
1392        insta::assert_debug_snapshot!(p(b"PT9223372036854775807S"), @"9223372036854775807s");
1393        insta::assert_debug_snapshot!(p(b"PT9223372036854775808S"), @"9223372036854775808s");
1394        insta::assert_debug_snapshot!(p(b"PT18446744073709551615S"), @"18446744073709551615s");
1395        insta::assert_debug_snapshot!(p(b"PT1M18446744073709551555S"), @"18446744073709551615s");
1396    }
1397
1398    #[test]
1399    fn err_unsigned_duration() {
1400        #[track_caller]
1401        fn p(input: &[u8]) -> crate::Error {
1402            SpanParser::new().parse_unsigned_duration(input).unwrap_err()
1403        }
1404
1405        insta::assert_snapshot!(
1406            p(b"-PT1S"),
1407            @"cannot parse negative duration into unsigned `std::time::Duration`",
1408        );
1409        insta::assert_snapshot!(
1410            p(b"-PT0S"),
1411            @"cannot parse negative duration into unsigned `std::time::Duration`",
1412        );
1413
1414        insta::assert_snapshot!(
1415            p(b"P0d"),
1416            @"parsing ISO 8601 duration in this context requires that the duration contain a time component and no components of days or greater",
1417        );
1418        insta::assert_snapshot!(
1419            p(b"PT0d"),
1420            @"expected to find time unit designator suffix (`H`, `M` or `S`), but found `d` instead",
1421        );
1422        insta::assert_snapshot!(
1423            p(b"P0dT1s"),
1424            @"parsing ISO 8601 duration in this context requires that the duration contain a time component and no components of days or greater",
1425        );
1426
1427        insta::assert_snapshot!(
1428            p(b""),
1429            @"expected to find duration beginning with `P` or `p`, but found end of input",
1430        );
1431        insta::assert_snapshot!(
1432            p(b"P"),
1433            @"parsing ISO 8601 duration in this context requires that the duration contain a time component and no components of days or greater",
1434        );
1435        insta::assert_snapshot!(
1436            p(b"PT"),
1437            @"found a time designator (`T` or `t`) in an ISO 8601 duration string, but did not find any time units",
1438        );
1439        insta::assert_snapshot!(
1440            p(b"PTs"),
1441            @"found a time designator (`T` or `t`) in an ISO 8601 duration string, but did not find any time units",
1442        );
1443
1444        insta::assert_snapshot!(
1445            p(b"PT1s1m"),
1446            @"found value with unit minute after unit second, but units must be written from largest to smallest (and they can't be repeated)",
1447        );
1448        insta::assert_snapshot!(
1449            p(b"PT1s1h"),
1450            @"found value with unit hour after unit second, but units must be written from largest to smallest (and they can't be repeated)",
1451        );
1452        insta::assert_snapshot!(
1453            p(b"PT1m1h"),
1454            @"found value with unit hour after unit minute, but units must be written from largest to smallest (and they can't be repeated)",
1455        );
1456
1457        insta::assert_snapshot!(
1458            p(b"-PT9223372036854775809S"),
1459            @"cannot parse negative duration into unsigned `std::time::Duration`",
1460        );
1461        insta::assert_snapshot!(
1462            p(b"PT18446744073709551616S"),
1463            @"number too big to parse into 64-bit integer",
1464        );
1465
1466        insta::assert_snapshot!(
1467            p(b"PT5124095576030431H16.999999999S"),
1468            @"accumulated duration overflowed when adding value to unit second",
1469        );
1470        insta::assert_snapshot!(
1471            p(b"PT1M18446744073709551556S"),
1472            @"accumulated duration overflowed when adding value to unit second",
1473        );
1474        insta::assert_snapshot!(
1475            p(b"PT5124095576030431.5H"),
1476            @"accumulated duration overflowed when adding fractional value to unit hour",
1477        );
1478    }
1479
1480    #[test]
1481    fn ok_temporal_duration_basic() {
1482        let p = |input: &[u8]| SpanParser::new().parse_span(input).unwrap();
1483
1484        insta::assert_debug_snapshot!(p(b"P5d"), @"5d");
1485        insta::assert_debug_snapshot!(p(b"-P5d"), @"5d ago");
1486        insta::assert_debug_snapshot!(p(b"+P5d"), @"5d");
1487        insta::assert_debug_snapshot!(p(b"P5DT1s"), @"5d 1s");
1488        insta::assert_debug_snapshot!(p(b"PT1S"), @"1s");
1489        insta::assert_debug_snapshot!(p(b"PT0S"), @"0s");
1490        insta::assert_debug_snapshot!(p(b"P0Y"), @"0s");
1491        insta::assert_debug_snapshot!(p(b"P1Y1M1W1DT1H1M1S"), @"1y 1mo 1w 1d 1h 1m 1s");
1492        insta::assert_debug_snapshot!(p(b"P1y1m1w1dT1h1m1s"), @"1y 1mo 1w 1d 1h 1m 1s");
1493    }
1494
1495    #[test]
1496    fn ok_temporal_duration_fractional() {
1497        let p = |input: &[u8]| SpanParser::new().parse_span(input).unwrap();
1498
1499        insta::assert_debug_snapshot!(p(b"PT0.5h"), @"30m");
1500        insta::assert_debug_snapshot!(p(b"PT0.123456789h"), @"7m 24s 444ms 440µs 400ns");
1501        insta::assert_debug_snapshot!(p(b"PT1.123456789h"), @"1h 7m 24s 444ms 440µs 400ns");
1502
1503        insta::assert_debug_snapshot!(p(b"PT0.5m"), @"30s");
1504        insta::assert_debug_snapshot!(p(b"PT0.123456789m"), @"7s 407ms 407µs 340ns");
1505        insta::assert_debug_snapshot!(p(b"PT1.123456789m"), @"1m 7s 407ms 407µs 340ns");
1506
1507        insta::assert_debug_snapshot!(p(b"PT0.5s"), @"500ms");
1508        insta::assert_debug_snapshot!(p(b"-PT0.5s"), @"500ms ago");
1509        insta::assert_debug_snapshot!(
1510            p(b"-PT0.000000001s"),
1511            @"1ns ago",
1512        );
1513        insta::assert_debug_snapshot!(p(b"PT0.123456789s"), @"123ms 456µs 789ns");
1514        insta::assert_debug_snapshot!(p(b"PT1.123456789s"), @"1s 123ms 456µs 789ns");
1515
1516        // The tests below all have a whole second value that exceeds the
1517        // maximum allowed seconds in a span. But they should still parse
1518        // correctly by spilling over into milliseconds, microseconds and
1519        // nanoseconds.
1520        insta::assert_debug_snapshot!(p(b"PT1902545624836.854775807s"), @"631107417600s 631107417600000ms 631107417600000000µs 9223372036854775807ns");
1521        insta::assert_debug_snapshot!(p(b"PT175307616h10518456960m640330789636.854775807s"), @"175307616h 10518456960m 631107417600s 9223372036854ms 775µs 807ns");
1522        insta::assert_debug_snapshot!(p(b"-PT1902545624836.854775807s"), @"631107417600s 631107417600000ms 631107417600000000µs 9223372036854775807ns ago");
1523        insta::assert_debug_snapshot!(p(b"-PT175307616h10518456960m640330789636.854775807s"), @"175307616h 10518456960m 631107417600s 9223372036854ms 775µs 807ns ago");
1524    }
1525
1526    #[test]
1527    fn ok_temporal_duration_unbalanced() {
1528        let p = |input: &[u8]| SpanParser::new().parse_span(input).unwrap();
1529
1530        insta::assert_debug_snapshot!(
1531            p(b"PT175307616h10518456960m1774446656760s"), @"175307616h 10518456960m 631107417600s 631107417600000ms 512231821560000000µs");
1532        insta::assert_debug_snapshot!(
1533            p(b"Pt843517082H"), @"175307616h 10518456960m 631107417600s 631107417600000ms 512231824800000000µs");
1534        insta::assert_debug_snapshot!(
1535            p(b"Pt843517081H"), @"175307616h 10518456960m 631107417600s 631107417600000ms 512231821200000000µs");
1536
1537        // The excess from a unit over its limit should be combined with
1538        // smaller units instead of one clobbering the other.
1539        insta::assert_debug_snapshot!(p(b"PT175307617h1m"), @"175307616h 61m");
1540        insta::assert_debug_snapshot!(p(b"-PT175307617h1m"), @"175307616h 61m ago");
1541        insta::assert_debug_snapshot!(p(b"PT175307617h1.5m"), @"175307616h 61m 30s");
1542        insta::assert_debug_snapshot!(p(b"PT10518456961m1s"), @"10518456960m 61s");
1543    }
1544
1545    #[test]
1546    fn ok_temporal_datetime_basic() {
1547        let p = |input| {
1548            DateTimeParser::new().parse_temporal_datetime(input).unwrap()
1549        };
1550
1551        insta::assert_debug_snapshot!(p(b"2024-06-01"), @r#"
1552        Parsed {
1553            value: ParsedDateTime {
1554                date: ParsedDate {
1555                    date: 2024-06-01,
1556                },
1557                time: None,
1558                offset: None,
1559                annotations: ParsedAnnotations {
1560                    time_zone: None,
1561                },
1562            },
1563            input: "",
1564        }
1565        "#);
1566        insta::assert_debug_snapshot!(p(b"2024-06-01[America/New_York]"), @r#"
1567        Parsed {
1568            value: ParsedDateTime {
1569                date: ParsedDate {
1570                    date: 2024-06-01,
1571                },
1572                time: None,
1573                offset: None,
1574                annotations: ParsedAnnotations {
1575                    time_zone: Some(
1576                        Named {
1577                            critical: false,
1578                            name: "America/New_York",
1579                        },
1580                    ),
1581                },
1582            },
1583            input: "",
1584        }
1585        "#);
1586        insta::assert_debug_snapshot!(p(b"2024-06-01T01:02:03"), @r#"
1587        Parsed {
1588            value: ParsedDateTime {
1589                date: ParsedDate {
1590                    date: 2024-06-01,
1591                },
1592                time: Some(
1593                    ParsedTime {
1594                        time: 01:02:03,
1595                        extended: true,
1596                    },
1597                ),
1598                offset: None,
1599                annotations: ParsedAnnotations {
1600                    time_zone: None,
1601                },
1602            },
1603            input: "",
1604        }
1605        "#);
1606        insta::assert_debug_snapshot!(p(b"2024-06-01T01:02:03-05"), @r#"
1607        Parsed {
1608            value: ParsedDateTime {
1609                date: ParsedDate {
1610                    date: 2024-06-01,
1611                },
1612                time: Some(
1613                    ParsedTime {
1614                        time: 01:02:03,
1615                        extended: true,
1616                    },
1617                ),
1618                offset: Some(
1619                    ParsedOffset {
1620                        kind: Numeric(
1621                            -05,
1622                        ),
1623                    },
1624                ),
1625                annotations: ParsedAnnotations {
1626                    time_zone: None,
1627                },
1628            },
1629            input: "",
1630        }
1631        "#);
1632        insta::assert_debug_snapshot!(p(b"2024-06-01T01:02:03-05[America/New_York]"), @r#"
1633        Parsed {
1634            value: ParsedDateTime {
1635                date: ParsedDate {
1636                    date: 2024-06-01,
1637                },
1638                time: Some(
1639                    ParsedTime {
1640                        time: 01:02:03,
1641                        extended: true,
1642                    },
1643                ),
1644                offset: Some(
1645                    ParsedOffset {
1646                        kind: Numeric(
1647                            -05,
1648                        ),
1649                    },
1650                ),
1651                annotations: ParsedAnnotations {
1652                    time_zone: Some(
1653                        Named {
1654                            critical: false,
1655                            name: "America/New_York",
1656                        },
1657                    ),
1658                },
1659            },
1660            input: "",
1661        }
1662        "#);
1663        insta::assert_debug_snapshot!(p(b"2024-06-01T01:02:03Z[America/New_York]"), @r#"
1664        Parsed {
1665            value: ParsedDateTime {
1666                date: ParsedDate {
1667                    date: 2024-06-01,
1668                },
1669                time: Some(
1670                    ParsedTime {
1671                        time: 01:02:03,
1672                        extended: true,
1673                    },
1674                ),
1675                offset: Some(
1676                    ParsedOffset {
1677                        kind: Zulu,
1678                    },
1679                ),
1680                annotations: ParsedAnnotations {
1681                    time_zone: Some(
1682                        Named {
1683                            critical: false,
1684                            name: "America/New_York",
1685                        },
1686                    ),
1687                },
1688            },
1689            input: "",
1690        }
1691        "#);
1692        insta::assert_debug_snapshot!(p(b"2024-06-01T01:02:03-01[America/New_York]"), @r#"
1693        Parsed {
1694            value: ParsedDateTime {
1695                date: ParsedDate {
1696                    date: 2024-06-01,
1697                },
1698                time: Some(
1699                    ParsedTime {
1700                        time: 01:02:03,
1701                        extended: true,
1702                    },
1703                ),
1704                offset: Some(
1705                    ParsedOffset {
1706                        kind: Numeric(
1707                            -01,
1708                        ),
1709                    },
1710                ),
1711                annotations: ParsedAnnotations {
1712                    time_zone: Some(
1713                        Named {
1714                            critical: false,
1715                            name: "America/New_York",
1716                        },
1717                    ),
1718                },
1719            },
1720            input: "",
1721        }
1722        "#);
1723    }
1724
1725    #[test]
1726    fn ok_temporal_datetime_incomplete() {
1727        let p = |input| {
1728            DateTimeParser::new().parse_temporal_datetime(input).unwrap()
1729        };
1730
1731        insta::assert_debug_snapshot!(p(b"2024-06-01T01"), @r#"
1732        Parsed {
1733            value: ParsedDateTime {
1734                date: ParsedDate {
1735                    date: 2024-06-01,
1736                },
1737                time: Some(
1738                    ParsedTime {
1739                        time: 01:00:00,
1740                        extended: false,
1741                    },
1742                ),
1743                offset: None,
1744                annotations: ParsedAnnotations {
1745                    time_zone: None,
1746                },
1747            },
1748            input: "",
1749        }
1750        "#);
1751        insta::assert_debug_snapshot!(p(b"2024-06-01T0102"), @r#"
1752        Parsed {
1753            value: ParsedDateTime {
1754                date: ParsedDate {
1755                    date: 2024-06-01,
1756                },
1757                time: Some(
1758                    ParsedTime {
1759                        time: 01:02:00,
1760                        extended: false,
1761                    },
1762                ),
1763                offset: None,
1764                annotations: ParsedAnnotations {
1765                    time_zone: None,
1766                },
1767            },
1768            input: "",
1769        }
1770        "#);
1771        insta::assert_debug_snapshot!(p(b"2024-06-01T01:02"), @r#"
1772        Parsed {
1773            value: ParsedDateTime {
1774                date: ParsedDate {
1775                    date: 2024-06-01,
1776                },
1777                time: Some(
1778                    ParsedTime {
1779                        time: 01:02:00,
1780                        extended: true,
1781                    },
1782                ),
1783                offset: None,
1784                annotations: ParsedAnnotations {
1785                    time_zone: None,
1786                },
1787            },
1788            input: "",
1789        }
1790        "#);
1791    }
1792
1793    #[test]
1794    fn ok_temporal_datetime_separator() {
1795        let p = |input| {
1796            DateTimeParser::new().parse_temporal_datetime(input).unwrap()
1797        };
1798
1799        insta::assert_debug_snapshot!(p(b"2024-06-01t01:02:03"), @r#"
1800        Parsed {
1801            value: ParsedDateTime {
1802                date: ParsedDate {
1803                    date: 2024-06-01,
1804                },
1805                time: Some(
1806                    ParsedTime {
1807                        time: 01:02:03,
1808                        extended: true,
1809                    },
1810                ),
1811                offset: None,
1812                annotations: ParsedAnnotations {
1813                    time_zone: None,
1814                },
1815            },
1816            input: "",
1817        }
1818        "#);
1819        insta::assert_debug_snapshot!(p(b"2024-06-01 01:02:03"), @r#"
1820        Parsed {
1821            value: ParsedDateTime {
1822                date: ParsedDate {
1823                    date: 2024-06-01,
1824                },
1825                time: Some(
1826                    ParsedTime {
1827                        time: 01:02:03,
1828                        extended: true,
1829                    },
1830                ),
1831                offset: None,
1832                annotations: ParsedAnnotations {
1833                    time_zone: None,
1834                },
1835            },
1836            input: "",
1837        }
1838        "#);
1839    }
1840
1841    #[test]
1842    fn ok_temporal_time_basic() {
1843        let p =
1844            |input| DateTimeParser::new().parse_temporal_time(input).unwrap();
1845
1846        insta::assert_debug_snapshot!(p(b"01:02:03"), @r#"
1847        Parsed {
1848            value: ParsedTime {
1849                time: 01:02:03,
1850                extended: true,
1851            },
1852            input: "",
1853        }
1854        "#);
1855        insta::assert_debug_snapshot!(p(b"130113"), @r#"
1856        Parsed {
1857            value: ParsedTime {
1858                time: 13:01:13,
1859                extended: false,
1860            },
1861            input: "",
1862        }
1863        "#);
1864        insta::assert_debug_snapshot!(p(b"T01:02:03"), @r#"
1865        Parsed {
1866            value: ParsedTime {
1867                time: 01:02:03,
1868                extended: true,
1869            },
1870            input: "",
1871        }
1872        "#);
1873        insta::assert_debug_snapshot!(p(b"T010203"), @r#"
1874        Parsed {
1875            value: ParsedTime {
1876                time: 01:02:03,
1877                extended: false,
1878            },
1879            input: "",
1880        }
1881        "#);
1882    }
1883
1884    #[test]
1885    fn ok_temporal_time_from_full_datetime() {
1886        let p =
1887            |input| DateTimeParser::new().parse_temporal_time(input).unwrap();
1888
1889        insta::assert_debug_snapshot!(p(b"2024-06-01T01:02:03"), @r#"
1890        Parsed {
1891            value: ParsedTime {
1892                time: 01:02:03,
1893                extended: true,
1894            },
1895            input: "",
1896        }
1897        "#);
1898        insta::assert_debug_snapshot!(p(b"2024-06-01T01:02:03.123"), @r#"
1899        Parsed {
1900            value: ParsedTime {
1901                time: 01:02:03.123,
1902                extended: true,
1903            },
1904            input: "",
1905        }
1906        "#);
1907        insta::assert_debug_snapshot!(p(b"2024-06-01T01"), @r#"
1908        Parsed {
1909            value: ParsedTime {
1910                time: 01:00:00,
1911                extended: false,
1912            },
1913            input: "",
1914        }
1915        "#);
1916        insta::assert_debug_snapshot!(p(b"2024-06-01T0102"), @r#"
1917        Parsed {
1918            value: ParsedTime {
1919                time: 01:02:00,
1920                extended: false,
1921            },
1922            input: "",
1923        }
1924        "#);
1925        insta::assert_debug_snapshot!(p(b"2024-06-01T010203"), @r#"
1926        Parsed {
1927            value: ParsedTime {
1928                time: 01:02:03,
1929                extended: false,
1930            },
1931            input: "",
1932        }
1933        "#);
1934        insta::assert_debug_snapshot!(p(b"2024-06-01T010203-05"), @r#"
1935        Parsed {
1936            value: ParsedTime {
1937                time: 01:02:03,
1938                extended: false,
1939            },
1940            input: "",
1941        }
1942        "#);
1943        insta::assert_debug_snapshot!(
1944            p(b"2024-06-01T010203-05[America/New_York]"), @r#"
1945        Parsed {
1946            value: ParsedTime {
1947                time: 01:02:03,
1948                extended: false,
1949            },
1950            input: "",
1951        }
1952        "#);
1953        insta::assert_debug_snapshot!(
1954            p(b"2024-06-01T010203[America/New_York]"), @r#"
1955        Parsed {
1956            value: ParsedTime {
1957                time: 01:02:03,
1958                extended: false,
1959            },
1960            input: "",
1961        }
1962        "#);
1963    }
1964
1965    #[test]
1966    fn err_temporal_time_ambiguous() {
1967        let p = |input| {
1968            DateTimeParser::new().parse_temporal_time(input).unwrap_err()
1969        };
1970
1971        insta::assert_snapshot!(
1972            p(b"010203"),
1973            @"parsed time is ambiguous with a month-day date",
1974        );
1975        insta::assert_snapshot!(
1976            p(b"130112"),
1977            @"parsed time is ambiguous with a year-month date",
1978        );
1979    }
1980
1981    #[test]
1982    fn err_temporal_time_missing_time() {
1983        let p = |input| {
1984            DateTimeParser::new().parse_temporal_time(input).unwrap_err()
1985        };
1986
1987        insta::assert_snapshot!(
1988            p(b"2024-06-01[America/New_York]"),
1989            @"successfully parsed date, but no time component was found",
1990        );
1991        // 2099 is not a valid time, but 2099-12-01 is a valid date, so this
1992        // carves a path where a full datetime parse is OK, but a basic
1993        // time-only parse is not.
1994        insta::assert_snapshot!(
1995            p(b"2099-12-01[America/New_York]"),
1996            @"successfully parsed date, but no time component was found",
1997        );
1998        // Like above, but this time we use an invalid date. As a result, we
1999        // get an error reported not on the invalid date, but on how it is an
2000        // invalid time. (Because we're asking for a time here.)
2001        insta::assert_snapshot!(
2002            p(b"2099-13-01[America/New_York]"),
2003            @"failed to parse two digit integer as minute: parameter 'minute' is not in the required range of 0..=59",
2004        );
2005    }
2006
2007    #[test]
2008    fn err_temporal_time_zulu() {
2009        let p = |input| {
2010            DateTimeParser::new().parse_temporal_time(input).unwrap_err()
2011        };
2012
2013        insta::assert_snapshot!(
2014            p(b"T00:00:00Z"),
2015            @"cannot parse civil date/time from string with a Zulu offset, parse as a `jiff::Timestamp` first and convert to a civil date/time instead",
2016        );
2017        insta::assert_snapshot!(
2018            p(b"00:00:00Z"),
2019            @"cannot parse civil date/time from string with a Zulu offset, parse as a `jiff::Timestamp` first and convert to a civil date/time instead",
2020        );
2021        insta::assert_snapshot!(
2022            p(b"000000Z"),
2023            @"cannot parse civil date/time from string with a Zulu offset, parse as a `jiff::Timestamp` first and convert to a civil date/time instead",
2024        );
2025        insta::assert_snapshot!(
2026            p(b"2099-12-01T00:00:00Z"),
2027            @"cannot parse civil date/time from string with a Zulu offset, parse as a `jiff::Timestamp` first and convert to a civil date/time instead",
2028        );
2029    }
2030
2031    #[test]
2032    fn ok_date_basic() {
2033        let p = |input| DateTimeParser::new().parse_date_spec(input).unwrap();
2034
2035        insta::assert_debug_snapshot!(p(b"2010-03-14"), @r#"
2036        Parsed {
2037            value: ParsedDate {
2038                date: 2010-03-14,
2039            },
2040            input: "",
2041        }
2042        "#);
2043        insta::assert_debug_snapshot!(p(b"20100314"), @r#"
2044        Parsed {
2045            value: ParsedDate {
2046                date: 2010-03-14,
2047            },
2048            input: "",
2049        }
2050        "#);
2051        insta::assert_debug_snapshot!(p(b"2010-03-14T01:02:03"), @r#"
2052        Parsed {
2053            value: ParsedDate {
2054                date: 2010-03-14,
2055            },
2056            input: "T01:02:03",
2057        }
2058        "#);
2059        insta::assert_debug_snapshot!(p(b"-009999-03-14"), @r#"
2060        Parsed {
2061            value: ParsedDate {
2062                date: -009999-03-14,
2063            },
2064            input: "",
2065        }
2066        "#);
2067        insta::assert_debug_snapshot!(p(b"+009999-03-14"), @r#"
2068        Parsed {
2069            value: ParsedDate {
2070                date: 9999-03-14,
2071            },
2072            input: "",
2073        }
2074        "#);
2075    }
2076
2077    #[test]
2078    fn err_date_empty() {
2079        insta::assert_snapshot!(
2080            DateTimeParser::new().parse_date_spec(b"").unwrap_err(),
2081            @"expected four digit year (or leading sign for six digit year), but found end of input",
2082        );
2083    }
2084
2085    #[test]
2086    fn err_date_year() {
2087        insta::assert_snapshot!(
2088            DateTimeParser::new().parse_date_spec(b"123").unwrap_err(),
2089            @"expected four digit year (or leading sign for six digit year), but found end of input",
2090        );
2091        insta::assert_snapshot!(
2092            DateTimeParser::new().parse_date_spec(b"123a").unwrap_err(),
2093            @"failed to parse four digit integer as year: invalid digit, expected 0-9 but got a",
2094        );
2095
2096        insta::assert_snapshot!(
2097            DateTimeParser::new().parse_date_spec(b"-9999").unwrap_err(),
2098            @"expected six digit year (because of a leading sign), but found end of input",
2099        );
2100        insta::assert_snapshot!(
2101            DateTimeParser::new().parse_date_spec(b"+9999").unwrap_err(),
2102            @"expected six digit year (because of a leading sign), but found end of input",
2103        );
2104        insta::assert_snapshot!(
2105            DateTimeParser::new().parse_date_spec(b"-99999").unwrap_err(),
2106            @"expected six digit year (because of a leading sign), but found end of input",
2107        );
2108        insta::assert_snapshot!(
2109            DateTimeParser::new().parse_date_spec(b"+99999").unwrap_err(),
2110            @"expected six digit year (because of a leading sign), but found end of input",
2111        );
2112        insta::assert_snapshot!(
2113            DateTimeParser::new().parse_date_spec(b"-99999a").unwrap_err(),
2114            @"failed to parse six digit integer as year: invalid digit, expected 0-9 but got a",
2115        );
2116        insta::assert_snapshot!(
2117            DateTimeParser::new().parse_date_spec(b"+999999").unwrap_err(),
2118            @"failed to parse six digit integer as year: parameter 'year' is not in the required range of -9999..=9999",
2119        );
2120        insta::assert_snapshot!(
2121            DateTimeParser::new().parse_date_spec(b"-010000").unwrap_err(),
2122            @"failed to parse six digit integer as year: parameter 'year' is not in the required range of -9999..=9999",
2123        );
2124    }
2125
2126    #[test]
2127    fn err_date_month() {
2128        insta::assert_snapshot!(
2129            DateTimeParser::new().parse_date_spec(b"2024-").unwrap_err(),
2130            @"expected two digit month, but found end of input",
2131        );
2132        insta::assert_snapshot!(
2133            DateTimeParser::new().parse_date_spec(b"2024").unwrap_err(),
2134            @"expected two digit month, but found end of input",
2135        );
2136        insta::assert_snapshot!(
2137            DateTimeParser::new().parse_date_spec(b"2024-13-01").unwrap_err(),
2138            @"failed to parse two digit integer as month: parameter 'month' is not in the required range of 1..=12",
2139        );
2140        insta::assert_snapshot!(
2141            DateTimeParser::new().parse_date_spec(b"20241301").unwrap_err(),
2142            @"failed to parse two digit integer as month: parameter 'month' is not in the required range of 1..=12",
2143        );
2144    }
2145
2146    #[test]
2147    fn err_date_day() {
2148        insta::assert_snapshot!(
2149            DateTimeParser::new().parse_date_spec(b"2024-12-").unwrap_err(),
2150            @"expected two digit day, but found end of input",
2151        );
2152        insta::assert_snapshot!(
2153            DateTimeParser::new().parse_date_spec(b"202412").unwrap_err(),
2154            @"expected two digit day, but found end of input",
2155        );
2156        insta::assert_snapshot!(
2157            DateTimeParser::new().parse_date_spec(b"2024-12-40").unwrap_err(),
2158            @"failed to parse two digit integer as day: parameter 'day' is not in the required range of 1..=31",
2159        );
2160        insta::assert_snapshot!(
2161            DateTimeParser::new().parse_date_spec(b"2024-11-31").unwrap_err(),
2162            @"parsed date is not valid: parameter 'day' for `2024-11` is invalid, must be in range `1..=30`",
2163        );
2164        insta::assert_snapshot!(
2165            DateTimeParser::new().parse_date_spec(b"2024-02-30").unwrap_err(),
2166            @"parsed date is not valid: parameter 'day' for `2024-02` is invalid, must be in range `1..=29`",
2167        );
2168        insta::assert_snapshot!(
2169            DateTimeParser::new().parse_date_spec(b"2023-02-29").unwrap_err(),
2170            @"parsed date is not valid: parameter 'day' for `2023-02` is invalid, must be in range `1..=28`",
2171        );
2172    }
2173
2174    #[test]
2175    fn err_date_separator() {
2176        insta::assert_snapshot!(
2177            DateTimeParser::new().parse_date_spec(b"2024-1231").unwrap_err(),
2178            @"failed to parse separator after month: expected `-` separator, but found `3`",
2179        );
2180        insta::assert_snapshot!(
2181            DateTimeParser::new().parse_date_spec(b"202412-31").unwrap_err(),
2182            @"failed to parse separator after month: expected no separator since none was found after the year, but found a `-` separator",
2183        );
2184    }
2185
2186    #[test]
2187    fn ok_time_basic() {
2188        let p = |input| DateTimeParser::new().parse_time_spec(input).unwrap();
2189
2190        insta::assert_debug_snapshot!(p(b"01:02:03"), @r#"
2191        Parsed {
2192            value: ParsedTime {
2193                time: 01:02:03,
2194                extended: true,
2195            },
2196            input: "",
2197        }
2198        "#);
2199        insta::assert_debug_snapshot!(p(b"010203"), @r#"
2200        Parsed {
2201            value: ParsedTime {
2202                time: 01:02:03,
2203                extended: false,
2204            },
2205            input: "",
2206        }
2207        "#);
2208    }
2209
2210    #[test]
2211    fn ok_time_fractional() {
2212        let p = |input| DateTimeParser::new().parse_time_spec(input).unwrap();
2213
2214        insta::assert_debug_snapshot!(p(b"01:02:03.123456789"), @r#"
2215        Parsed {
2216            value: ParsedTime {
2217                time: 01:02:03.123456789,
2218                extended: true,
2219            },
2220            input: "",
2221        }
2222        "#);
2223        insta::assert_debug_snapshot!(p(b"010203.123456789"), @r#"
2224        Parsed {
2225            value: ParsedTime {
2226                time: 01:02:03.123456789,
2227                extended: false,
2228            },
2229            input: "",
2230        }
2231        "#);
2232
2233        insta::assert_debug_snapshot!(p(b"01:02:03.9"), @r#"
2234        Parsed {
2235            value: ParsedTime {
2236                time: 01:02:03.9,
2237                extended: true,
2238            },
2239            input: "",
2240        }
2241        "#);
2242    }
2243
2244    #[test]
2245    fn ok_time_no_fractional() {
2246        let p = |input| DateTimeParser::new().parse_time_spec(input).unwrap();
2247
2248        insta::assert_debug_snapshot!(p(b"01:02.123456789"), @r#"
2249        Parsed {
2250            value: ParsedTime {
2251                time: 01:02:00,
2252                extended: true,
2253            },
2254            input: ".123456789",
2255        }
2256        "#);
2257    }
2258
2259    #[test]
2260    fn ok_time_leap() {
2261        let p = |input| DateTimeParser::new().parse_time_spec(input).unwrap();
2262
2263        insta::assert_debug_snapshot!(p(b"01:02:60"), @r#"
2264        Parsed {
2265            value: ParsedTime {
2266                time: 01:02:59,
2267                extended: true,
2268            },
2269            input: "",
2270        }
2271        "#);
2272    }
2273
2274    #[test]
2275    fn ok_time_mixed_format() {
2276        let p = |input| DateTimeParser::new().parse_time_spec(input).unwrap();
2277
2278        insta::assert_debug_snapshot!(p(b"01:0203"), @r#"
2279        Parsed {
2280            value: ParsedTime {
2281                time: 01:02:00,
2282                extended: true,
2283            },
2284            input: "03",
2285        }
2286        "#);
2287        insta::assert_debug_snapshot!(p(b"0102:03"), @r#"
2288        Parsed {
2289            value: ParsedTime {
2290                time: 01:02:00,
2291                extended: false,
2292            },
2293            input: ":03",
2294        }
2295        "#);
2296    }
2297
2298    #[test]
2299    fn err_time_empty() {
2300        insta::assert_snapshot!(
2301            DateTimeParser::new().parse_time_spec(b"").unwrap_err(),
2302            @"expected two digit hour, but found end of input",
2303        );
2304    }
2305
2306    #[test]
2307    fn err_time_hour() {
2308        insta::assert_snapshot!(
2309            DateTimeParser::new().parse_time_spec(b"a").unwrap_err(),
2310            @"expected two digit hour, but found end of input",
2311        );
2312        insta::assert_snapshot!(
2313            DateTimeParser::new().parse_time_spec(b"1a").unwrap_err(),
2314            @"failed to parse two digit integer as hour: invalid digit, expected 0-9 but got a",
2315        );
2316        insta::assert_snapshot!(
2317            DateTimeParser::new().parse_time_spec(b"24").unwrap_err(),
2318            @"failed to parse two digit integer as hour: parameter 'hour' is not in the required range of 0..=23",
2319        );
2320    }
2321
2322    #[test]
2323    fn err_time_minute() {
2324        insta::assert_snapshot!(
2325            DateTimeParser::new().parse_time_spec(b"01:").unwrap_err(),
2326            @"expected two digit minute, but found end of input",
2327        );
2328        insta::assert_snapshot!(
2329            DateTimeParser::new().parse_time_spec(b"01:a").unwrap_err(),
2330            @"expected two digit minute, but found end of input",
2331        );
2332        insta::assert_snapshot!(
2333            DateTimeParser::new().parse_time_spec(b"01:1a").unwrap_err(),
2334            @"failed to parse two digit integer as minute: invalid digit, expected 0-9 but got a",
2335        );
2336        insta::assert_snapshot!(
2337            DateTimeParser::new().parse_time_spec(b"01:60").unwrap_err(),
2338            @"failed to parse two digit integer as minute: parameter 'minute' is not in the required range of 0..=59",
2339        );
2340    }
2341
2342    #[test]
2343    fn err_time_second() {
2344        insta::assert_snapshot!(
2345            DateTimeParser::new().parse_time_spec(b"01:02:").unwrap_err(),
2346            @"expected two digit second, but found end of input",
2347        );
2348        insta::assert_snapshot!(
2349            DateTimeParser::new().parse_time_spec(b"01:02:a").unwrap_err(),
2350            @"expected two digit second, but found end of input",
2351        );
2352        insta::assert_snapshot!(
2353            DateTimeParser::new().parse_time_spec(b"01:02:1a").unwrap_err(),
2354            @"failed to parse two digit integer as second: invalid digit, expected 0-9 but got a",
2355        );
2356        insta::assert_snapshot!(
2357            DateTimeParser::new().parse_time_spec(b"01:02:61").unwrap_err(),
2358            @"failed to parse two digit integer as second: parameter 'second' is not in the required range of 0..=60",
2359        );
2360    }
2361
2362    #[test]
2363    fn err_time_fractional() {
2364        insta::assert_snapshot!(
2365            DateTimeParser::new().parse_time_spec(b"01:02:03.").unwrap_err(),
2366            @"failed to parse fractional seconds in time: found decimal after seconds component, but did not find any digits after decimal",
2367        );
2368        insta::assert_snapshot!(
2369            DateTimeParser::new().parse_time_spec(b"01:02:03.a").unwrap_err(),
2370            @"failed to parse fractional seconds in time: found decimal after seconds component, but did not find any digits after decimal",
2371        );
2372    }
2373
2374    #[test]
2375    fn ok_iso_week_date_parse_basic() {
2376        fn p(input: &str) -> Parsed<'_, ISOWeekDate> {
2377            DateTimeParser::new()
2378                .parse_iso_week_date(input.as_bytes())
2379                .unwrap()
2380        }
2381
2382        insta::assert_debug_snapshot!( p("2024-W01-5"), @r#"
2383        Parsed {
2384            value: 2024-W01-5,
2385            input: "",
2386        }
2387        "#);
2388        insta::assert_debug_snapshot!( p("2024-W52-7"), @r#"
2389        Parsed {
2390            value: 2024-W52-7,
2391            input: "",
2392        }
2393        "#);
2394        insta::assert_debug_snapshot!( p("2004-W53-6"), @r#"
2395        Parsed {
2396            value: 2004-W53-6,
2397            input: "",
2398        }
2399        "#);
2400        insta::assert_debug_snapshot!( p("2009-W01-1"), @r#"
2401        Parsed {
2402            value: 2009-W01-1,
2403            input: "",
2404        }
2405        "#);
2406
2407        insta::assert_debug_snapshot!( p("2024W015"), @r#"
2408        Parsed {
2409            value: 2024-W01-5,
2410            input: "",
2411        }
2412        "#);
2413        insta::assert_debug_snapshot!( p("2024W527"), @r#"
2414        Parsed {
2415            value: 2024-W52-7,
2416            input: "",
2417        }
2418        "#);
2419        insta::assert_debug_snapshot!( p("2004W536"), @r#"
2420        Parsed {
2421            value: 2004-W53-6,
2422            input: "",
2423        }
2424        "#);
2425        insta::assert_debug_snapshot!( p("2009W011"), @r#"
2426        Parsed {
2427            value: 2009-W01-1,
2428            input: "",
2429        }
2430        "#);
2431
2432        // Lowercase should be okay. This matches how
2433        // we support `T` or `t`.
2434        insta::assert_debug_snapshot!( p("2009w011"), @r#"
2435        Parsed {
2436            value: 2009-W01-1,
2437            input: "",
2438        }
2439        "#);
2440    }
2441
2442    #[test]
2443    fn err_iso_week_date_year() {
2444        let p = |input: &str| {
2445            DateTimeParser::new()
2446                .parse_iso_week_date(input.as_bytes())
2447                .unwrap_err()
2448        };
2449
2450        insta::assert_snapshot!(
2451            p("123"),
2452            @"expected four digit year (or leading sign for six digit year), but found end of input",
2453        );
2454        insta::assert_snapshot!(
2455            p("123a"),
2456            @"failed to parse four digit integer as year: invalid digit, expected 0-9 but got a",
2457        );
2458
2459        insta::assert_snapshot!(
2460            p("-9999"),
2461            @"expected six digit year (because of a leading sign), but found end of input",
2462        );
2463        insta::assert_snapshot!(
2464            p("+9999"),
2465            @"expected six digit year (because of a leading sign), but found end of input",
2466        );
2467        insta::assert_snapshot!(
2468            p("-99999"),
2469            @"expected six digit year (because of a leading sign), but found end of input",
2470        );
2471        insta::assert_snapshot!(
2472            p("+99999"),
2473            @"expected six digit year (because of a leading sign), but found end of input",
2474        );
2475        insta::assert_snapshot!(
2476            p("-99999a"),
2477            @"failed to parse six digit integer as year: invalid digit, expected 0-9 but got a",
2478        );
2479        insta::assert_snapshot!(
2480            p("+999999"),
2481            @"failed to parse six digit integer as year: parameter 'year' is not in the required range of -9999..=9999",
2482        );
2483        insta::assert_snapshot!(
2484            p("-010000"),
2485            @"failed to parse six digit integer as year: parameter 'year' is not in the required range of -9999..=9999",
2486        );
2487    }
2488
2489    #[test]
2490    fn err_iso_week_date_week_prefix() {
2491        let p = |input: &str| {
2492            DateTimeParser::new()
2493                .parse_iso_week_date(input.as_bytes())
2494                .unwrap_err()
2495        };
2496
2497        insta::assert_snapshot!(
2498            p("2024-"),
2499            @"failed to parse week number prefix in date: expected `W` or `w`, but found end of input",
2500        );
2501        insta::assert_snapshot!(
2502            p("2024"),
2503            @"failed to parse week number prefix in date: expected `W` or `w`, but found end of input",
2504        );
2505    }
2506
2507    #[test]
2508    fn err_iso_week_date_week_number() {
2509        let p = |input: &str| {
2510            DateTimeParser::new()
2511                .parse_iso_week_date(input.as_bytes())
2512                .unwrap_err()
2513        };
2514
2515        insta::assert_snapshot!(
2516            p("2024-W"),
2517            @"expected two digit week number, but found end of input",
2518        );
2519        insta::assert_snapshot!(
2520            p("2024-W1"),
2521            @"expected two digit week number, but found end of input",
2522        );
2523        insta::assert_snapshot!(
2524            p("2024-W53-1"),
2525            @"parsed week date is not valid: parameter 'iso-week' is not in the required range of 1..=53",
2526        );
2527        insta::assert_snapshot!(
2528            p("2030W531"),
2529            @"parsed week date is not valid: parameter 'iso-week' is not in the required range of 1..=53",
2530        );
2531    }
2532
2533    #[test]
2534    fn err_iso_week_date_parse_incomplete() {
2535        let p = |input: &str| {
2536            DateTimeParser::new()
2537                .parse_iso_week_date(input.as_bytes())
2538                .unwrap_err()
2539        };
2540
2541        insta::assert_snapshot!(
2542            p("2024-W53-1"),
2543            @"parsed week date is not valid: parameter 'iso-week' is not in the required range of 1..=53",
2544        );
2545        insta::assert_snapshot!(
2546            p("2025-W53-1"),
2547            @"parsed week date is not valid: parameter 'iso-week' is not in the required range of 1..=53",
2548        );
2549    }
2550
2551    #[test]
2552    fn err_iso_week_date_date_day() {
2553        let p = |input: &str| {
2554            DateTimeParser::new()
2555                .parse_iso_week_date(input.as_bytes())
2556                .unwrap_err()
2557        };
2558        insta::assert_snapshot!(
2559            p("2024-W12-"),
2560            @"expected one digit weekday, but found end of input",
2561        );
2562        insta::assert_snapshot!(
2563            p("2024W12"),
2564            @"expected one digit weekday, but found end of input",
2565        );
2566        insta::assert_snapshot!(
2567            p("2024-W11-8"),
2568            @"failed to parse one digit integer as weekday: parameter 'weekday (Monday 1-indexed)' is not in the required range of 1..=7",
2569        );
2570    }
2571
2572    #[test]
2573    fn err_iso_week_date_date_separator() {
2574        let p = |input: &str| {
2575            DateTimeParser::new()
2576                .parse_iso_week_date(input.as_bytes())
2577                .unwrap_err()
2578        };
2579        insta::assert_snapshot!(
2580            p("2024-W521"),
2581            @"failed to parse separator after week number: expected `-` separator, but found `1`",
2582        );
2583        insta::assert_snapshot!(
2584            p("2024W01-5"),
2585            @"failed to parse separator after week number: expected no separator since none was found after the year, but found a `-` separator",
2586        );
2587    }
2588}