chrono/format/
parse.rs

1// This is a part of Chrono.
2// Portions copyright (c) 2015, John Nagle.
3// See README.md and LICENSE.txt for details.
4
5//! Date and time parsing routines.
6
7use core::borrow::Borrow;
8use core::str;
9
10use super::scan;
11use super::{BAD_FORMAT, INVALID, OUT_OF_RANGE, TOO_LONG, TOO_SHORT};
12use super::{Fixed, InternalFixed, InternalInternal, Item, Numeric, Pad, Parsed};
13use super::{ParseError, ParseResult};
14use crate::{DateTime, FixedOffset, Weekday};
15
16fn set_weekday_with_num_days_from_sunday(p: &mut Parsed, v: i64) -> ParseResult<()> {
17    p.set_weekday(match v {
18        0 => Weekday::Sun,
19        1 => Weekday::Mon,
20        2 => Weekday::Tue,
21        3 => Weekday::Wed,
22        4 => Weekday::Thu,
23        5 => Weekday::Fri,
24        6 => Weekday::Sat,
25        _ => return Err(OUT_OF_RANGE),
26    })
27}
28
29fn set_weekday_with_number_from_monday(p: &mut Parsed, v: i64) -> ParseResult<()> {
30    p.set_weekday(match v {
31        1 => Weekday::Mon,
32        2 => Weekday::Tue,
33        3 => Weekday::Wed,
34        4 => Weekday::Thu,
35        5 => Weekday::Fri,
36        6 => Weekday::Sat,
37        7 => Weekday::Sun,
38        _ => return Err(OUT_OF_RANGE),
39    })
40}
41
42fn parse_rfc2822<'a>(parsed: &mut Parsed, mut s: &'a str) -> ParseResult<(&'a str, ())> {
43    macro_rules! try_consume {
44        ($e:expr) => {{
45            let (s_, v) = $e?;
46            s = s_;
47            v
48        }};
49    }
50
51    // an adapted RFC 2822 syntax from Section 3.3 and 4.3:
52    //
53    // c-char      = <any char except '(', ')' and '\\'>
54    // c-escape    = "\" <any char>
55    // comment     = "(" *(comment / c-char / c-escape) ")" *S
56    // date-time   = [ day-of-week "," ] date 1*S time *S *comment
57    // day-of-week = *S day-name *S
58    // day-name    = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun"
59    // date        = day month year
60    // day         = *S 1*2DIGIT *S
61    // month       = 1*S month-name 1*S
62    // month-name  = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
63    //               "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
64    // year        = *S 2*DIGIT *S
65    // time        = time-of-day 1*S zone
66    // time-of-day = hour ":" minute [ ":" second ]
67    // hour        = *S 2DIGIT *S
68    // minute      = *S 2DIGIT *S
69    // second      = *S 2DIGIT *S
70    // zone        = ( "+" / "-" ) 4DIGIT /
71    //               "UT" / "GMT" /                  ; same as +0000
72    //               "EST" / "CST" / "MST" / "PST" / ; same as -0500 to -0800
73    //               "EDT" / "CDT" / "MDT" / "PDT" / ; same as -0400 to -0700
74    //               1*(%d65-90 / %d97-122)          ; same as -0000
75    //
76    // some notes:
77    //
78    // - quoted characters can be in any mixture of lower and upper cases.
79    //
80    // - we do not recognize a folding white space (FWS) or comment (CFWS).
81    //   for our purposes, instead, we accept any sequence of Unicode
82    //   white space characters (denoted here to `S`). For comments, we accept
83    //   any text within parentheses while respecting escaped parentheses.
84    //   Any actual RFC 2822 parser is expected to parse FWS and/or CFWS themselves
85    //   and replace it with a single SP (`%x20`); this is legitimate.
86    //
87    // - two-digit year < 50 should be interpreted by adding 2000.
88    //   two-digit year >= 50 or three-digit year should be interpreted
89    //   by adding 1900. note that four-or-more-digit years less than 1000
90    //   are *never* affected by this rule.
91    //
92    // - mismatching day-of-week is always an error, which is consistent to
93    //   Chrono's own rules.
94    //
95    // - zones can range from `-9959` to `+9959`, but `FixedOffset` does not
96    //   support offsets larger than 24 hours. this is not *that* problematic
97    //   since we do not directly go to a `DateTime` so one can recover
98    //   the offset information from `Parsed` anyway.
99
100    s = s.trim_start();
101
102    if let Ok((s_, weekday)) = scan::short_weekday(s) {
103        if !s_.starts_with(',') {
104            return Err(INVALID);
105        }
106        s = &s_[1..];
107        parsed.set_weekday(weekday)?;
108    }
109
110    s = s.trim_start();
111    parsed.set_day(try_consume!(scan::number(s, 1, 2)))?;
112    s = scan::space(s)?; // mandatory
113    parsed.set_month(1 + i64::from(try_consume!(scan::short_month0(s))))?;
114    s = scan::space(s)?; // mandatory
115
116    // distinguish two- and three-digit years from four-digit years
117    let prevlen = s.len();
118    let mut year = try_consume!(scan::number(s, 2, usize::MAX));
119    let yearlen = prevlen - s.len();
120    match (yearlen, year) {
121        (2, 0..=49) => {
122            year += 2000;
123        } //   47 -> 2047,   05 -> 2005
124        (2, 50..=99) => {
125            year += 1900;
126        } //   79 -> 1979
127        (3, _) => {
128            year += 1900;
129        } //  112 -> 2012,  009 -> 1909
130        (_, _) => {} // 1987 -> 1987, 0654 -> 0654
131    }
132    parsed.set_year(year)?;
133
134    s = scan::space(s)?; // mandatory
135    parsed.set_hour(try_consume!(scan::number(s, 2, 2)))?;
136    s = scan::char(s.trim_start(), b':')?.trim_start(); // *S ":" *S
137    parsed.set_minute(try_consume!(scan::number(s, 2, 2)))?;
138    if let Ok(s_) = scan::char(s.trim_start(), b':') {
139        // [ ":" *S 2DIGIT ]
140        parsed.set_second(try_consume!(scan::number(s_, 2, 2)))?;
141    }
142
143    s = scan::space(s)?; // mandatory
144    parsed.set_offset(i64::from(try_consume!(scan::timezone_offset_2822(s))))?;
145
146    // optional comments
147    while let Ok((s_out, ())) = scan::comment_2822(s) {
148        s = s_out;
149    }
150
151    Ok((s, ()))
152}
153
154pub(crate) fn parse_rfc3339<'a>(parsed: &mut Parsed, mut s: &'a str) -> ParseResult<(&'a str, ())> {
155    macro_rules! try_consume {
156        ($e:expr) => {{
157            let (s_, v) = $e?;
158            s = s_;
159            v
160        }};
161    }
162
163    // an adapted RFC 3339 syntax from Section 5.6:
164    //
165    // date-fullyear  = 4DIGIT
166    // date-month     = 2DIGIT ; 01-12
167    // date-mday      = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on month/year
168    // time-hour      = 2DIGIT ; 00-23
169    // time-minute    = 2DIGIT ; 00-59
170    // time-second    = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second rules
171    // time-secfrac   = "." 1*DIGIT
172    // time-numoffset = ("+" / "-") time-hour ":" time-minute
173    // time-offset    = "Z" / time-numoffset
174    // partial-time   = time-hour ":" time-minute ":" time-second [time-secfrac]
175    // full-date      = date-fullyear "-" date-month "-" date-mday
176    // full-time      = partial-time time-offset
177    // date-time      = full-date "T" full-time
178    //
179    // some notes:
180    //
181    // - quoted characters can be in any mixture of lower and upper cases.
182    //
183    // - it may accept any number of fractional digits for seconds.
184    //   for Chrono, this means that we should skip digits past first 9 digits.
185    //
186    // - unlike RFC 2822, the valid offset ranges from -23:59 to +23:59.
187    //   note that this restriction is unique to RFC 3339 and not ISO 8601.
188    //   since this is not a typical Chrono behavior, we check it earlier.
189    //
190    // - For readability a full-date and a full-time may be separated by a space character.
191
192    parsed.set_year(try_consume!(scan::number(s, 4, 4)))?;
193    s = scan::char(s, b'-')?;
194    parsed.set_month(try_consume!(scan::number(s, 2, 2)))?;
195    s = scan::char(s, b'-')?;
196    parsed.set_day(try_consume!(scan::number(s, 2, 2)))?;
197
198    s = match s.as_bytes().first() {
199        Some(&b't' | &b'T' | &b' ') => &s[1..],
200        Some(_) => return Err(INVALID),
201        None => return Err(TOO_SHORT),
202    };
203
204    parsed.set_hour(try_consume!(scan::number(s, 2, 2)))?;
205    s = scan::char(s, b':')?;
206    parsed.set_minute(try_consume!(scan::number(s, 2, 2)))?;
207    s = scan::char(s, b':')?;
208    parsed.set_second(try_consume!(scan::number(s, 2, 2)))?;
209    if s.starts_with('.') {
210        let nanosecond = try_consume!(scan::nanosecond(&s[1..]));
211        parsed.set_nanosecond(nanosecond)?;
212    }
213
214    let offset = try_consume!(scan::timezone_offset(s, |s| scan::char(s, b':'), true, false, true));
215    // This range check is similar to the one in `FixedOffset::east_opt`, so it would be redundant.
216    // But it is possible to read the offset directly from `Parsed`. We want to only successfully
217    // populate `Parsed` if the input is fully valid RFC 3339.
218    // Max for the hours field is `23`, and for the minutes field `59`.
219    const MAX_RFC3339_OFFSET: i32 = (23 * 60 + 59) * 60;
220    if !(-MAX_RFC3339_OFFSET..=MAX_RFC3339_OFFSET).contains(&offset) {
221        return Err(OUT_OF_RANGE);
222    }
223    parsed.set_offset(i64::from(offset))?;
224
225    Ok((s, ()))
226}
227
228/// Tries to parse given string into `parsed` with given formatting items.
229/// Returns `Ok` when the entire string has been parsed (otherwise `parsed` should not be used).
230/// There should be no trailing string after parsing;
231/// use a stray [`Item::Space`](./enum.Item.html#variant.Space) to trim whitespaces.
232///
233/// This particular date and time parser is:
234///
235/// - Greedy. It will consume the longest possible prefix.
236///   For example, `April` is always consumed entirely when the long month name is requested;
237///   it equally accepts `Apr`, but prefers the longer prefix in this case.
238///
239/// - Padding-agnostic (for numeric items).
240///   The [`Pad`](./enum.Pad.html) field is completely ignored,
241///   so one can prepend any number of whitespace then any number of zeroes before numbers.
242///
243/// - (Still) obeying the intrinsic parsing width. This allows, for example, parsing `HHMMSS`.
244pub fn parse<'a, I, B>(parsed: &mut Parsed, s: &str, items: I) -> ParseResult<()>
245where
246    I: Iterator<Item = B>,
247    B: Borrow<Item<'a>>,
248{
249    match parse_internal(parsed, s, items) {
250        Ok("") => Ok(()),
251        Ok(_) => Err(TOO_LONG), // if there are trailing chars it is an error
252        Err(e) => Err(e),
253    }
254}
255
256/// Tries to parse given string into `parsed` with given formatting items.
257/// Returns `Ok` with a slice of the unparsed remainder.
258///
259/// This particular date and time parser is:
260///
261/// - Greedy. It will consume the longest possible prefix.
262///   For example, `April` is always consumed entirely when the long month name is requested;
263///   it equally accepts `Apr`, but prefers the longer prefix in this case.
264///
265/// - Padding-agnostic (for numeric items).
266///   The [`Pad`](./enum.Pad.html) field is completely ignored,
267///   so one can prepend any number of zeroes before numbers.
268///
269/// - (Still) obeying the intrinsic parsing width. This allows, for example, parsing `HHMMSS`.
270pub fn parse_and_remainder<'a, 'b, I, B>(
271    parsed: &mut Parsed,
272    s: &'b str,
273    items: I,
274) -> ParseResult<&'b str>
275where
276    I: Iterator<Item = B>,
277    B: Borrow<Item<'a>>,
278{
279    parse_internal(parsed, s, items)
280}
281
282fn parse_internal<'a, 'b, I, B>(
283    parsed: &mut Parsed,
284    mut s: &'b str,
285    items: I,
286) -> Result<&'b str, ParseError>
287where
288    I: Iterator<Item = B>,
289    B: Borrow<Item<'a>>,
290{
291    macro_rules! try_consume {
292        ($e:expr) => {{
293            match $e {
294                Ok((s_, v)) => {
295                    s = s_;
296                    v
297                }
298                Err(e) => return Err(e),
299            }
300        }};
301    }
302
303    for item in items {
304        match *item.borrow() {
305            Item::Literal(prefix) => {
306                if s.len() < prefix.len() {
307                    return Err(TOO_SHORT);
308                }
309                if !s.starts_with(prefix) {
310                    return Err(INVALID);
311                }
312                s = &s[prefix.len()..];
313            }
314
315            #[cfg(feature = "alloc")]
316            Item::OwnedLiteral(ref prefix) => {
317                if s.len() < prefix.len() {
318                    return Err(TOO_SHORT);
319                }
320                if !s.starts_with(&prefix[..]) {
321                    return Err(INVALID);
322                }
323                s = &s[prefix.len()..];
324            }
325
326            Item::Space(_) => {
327                s = s.trim_start();
328            }
329
330            #[cfg(feature = "alloc")]
331            Item::OwnedSpace(_) => {
332                s = s.trim_start();
333            }
334
335            Item::Numeric(ref spec, ref _pad) => {
336                use super::Numeric::*;
337                type Setter = fn(&mut Parsed, i64) -> ParseResult<()>;
338
339                let (width, signed, set): (usize, bool, Setter) = match *spec {
340                    Year => (4, true, Parsed::set_year),
341                    YearDiv100 => (2, false, Parsed::set_year_div_100),
342                    YearMod100 => (2, false, Parsed::set_year_mod_100),
343                    IsoYear => (4, true, Parsed::set_isoyear),
344                    IsoYearDiv100 => (2, false, Parsed::set_isoyear_div_100),
345                    IsoYearMod100 => (2, false, Parsed::set_isoyear_mod_100),
346                    Quarter => (1, false, Parsed::set_quarter),
347                    Month => (2, false, Parsed::set_month),
348                    Day => (2, false, Parsed::set_day),
349                    WeekFromSun => (2, false, Parsed::set_week_from_sun),
350                    WeekFromMon => (2, false, Parsed::set_week_from_mon),
351                    IsoWeek => (2, false, Parsed::set_isoweek),
352                    NumDaysFromSun => (1, false, set_weekday_with_num_days_from_sunday),
353                    WeekdayFromMon => (1, false, set_weekday_with_number_from_monday),
354                    Ordinal => (3, false, Parsed::set_ordinal),
355                    Hour => (2, false, Parsed::set_hour),
356                    Hour12 => (2, false, Parsed::set_hour12),
357                    Minute => (2, false, Parsed::set_minute),
358                    Second => (2, false, Parsed::set_second),
359                    Nanosecond => (9, false, Parsed::set_nanosecond),
360                    Timestamp => (usize::MAX, false, Parsed::set_timestamp),
361
362                    // for the future expansion
363                    Internal(ref int) => match int._dummy {},
364                };
365
366                s = s.trim_start();
367                let v = if signed {
368                    if s.starts_with('-') {
369                        let v = try_consume!(scan::number(&s[1..], 1, usize::MAX));
370                        0i64.checked_sub(v).ok_or(OUT_OF_RANGE)?
371                    } else if s.starts_with('+') {
372                        try_consume!(scan::number(&s[1..], 1, usize::MAX))
373                    } else {
374                        // if there is no explicit sign, we respect the original `width`
375                        try_consume!(scan::number(s, 1, width))
376                    }
377                } else {
378                    try_consume!(scan::number(s, 1, width))
379                };
380                set(parsed, v)?;
381            }
382
383            Item::Fixed(ref spec) => {
384                use super::Fixed::*;
385
386                match spec {
387                    &ShortMonthName => {
388                        let month0 = try_consume!(scan::short_month0(s));
389                        parsed.set_month(i64::from(month0) + 1)?;
390                    }
391
392                    &LongMonthName => {
393                        let month0 = try_consume!(scan::short_or_long_month0(s));
394                        parsed.set_month(i64::from(month0) + 1)?;
395                    }
396
397                    &ShortWeekdayName => {
398                        let weekday = try_consume!(scan::short_weekday(s));
399                        parsed.set_weekday(weekday)?;
400                    }
401
402                    &LongWeekdayName => {
403                        let weekday = try_consume!(scan::short_or_long_weekday(s));
404                        parsed.set_weekday(weekday)?;
405                    }
406
407                    &LowerAmPm | &UpperAmPm => {
408                        if s.len() < 2 {
409                            return Err(TOO_SHORT);
410                        }
411                        let ampm = match (s.as_bytes()[0] | 32, s.as_bytes()[1] | 32) {
412                            (b'a', b'm') => false,
413                            (b'p', b'm') => true,
414                            _ => return Err(INVALID),
415                        };
416                        parsed.set_ampm(ampm)?;
417                        s = &s[2..];
418                    }
419
420                    &Nanosecond | &Nanosecond3 | &Nanosecond6 | &Nanosecond9 => {
421                        if s.starts_with('.') {
422                            let nano = try_consume!(scan::nanosecond(&s[1..]));
423                            parsed.set_nanosecond(nano)?;
424                        }
425                    }
426
427                    &Internal(InternalFixed { val: InternalInternal::Nanosecond3NoDot }) => {
428                        if s.len() < 3 {
429                            return Err(TOO_SHORT);
430                        }
431                        let nano = try_consume!(scan::nanosecond_fixed(s, 3));
432                        parsed.set_nanosecond(nano)?;
433                    }
434
435                    &Internal(InternalFixed { val: InternalInternal::Nanosecond6NoDot }) => {
436                        if s.len() < 6 {
437                            return Err(TOO_SHORT);
438                        }
439                        let nano = try_consume!(scan::nanosecond_fixed(s, 6));
440                        parsed.set_nanosecond(nano)?;
441                    }
442
443                    &Internal(InternalFixed { val: InternalInternal::Nanosecond9NoDot }) => {
444                        if s.len() < 9 {
445                            return Err(TOO_SHORT);
446                        }
447                        let nano = try_consume!(scan::nanosecond_fixed(s, 9));
448                        parsed.set_nanosecond(nano)?;
449                    }
450
451                    &TimezoneName => {
452                        try_consume!(Ok((s.trim_start_matches(|c: char| !c.is_whitespace()), ())));
453                    }
454
455                    &TimezoneOffsetColon
456                    | &TimezoneOffsetDoubleColon
457                    | &TimezoneOffsetTripleColon
458                    | &TimezoneOffset => {
459                        let offset = try_consume!(scan::timezone_offset(
460                            s.trim_start(),
461                            scan::colon_or_space,
462                            false,
463                            false,
464                            true,
465                        ));
466                        parsed.set_offset(i64::from(offset))?;
467                    }
468
469                    &TimezoneOffsetColonZ | &TimezoneOffsetZ => {
470                        let offset = try_consume!(scan::timezone_offset(
471                            s.trim_start(),
472                            scan::colon_or_space,
473                            true,
474                            false,
475                            true,
476                        ));
477                        parsed.set_offset(i64::from(offset))?;
478                    }
479                    &Internal(InternalFixed {
480                        val: InternalInternal::TimezoneOffsetPermissive,
481                    }) => {
482                        let offset = try_consume!(scan::timezone_offset(
483                            s.trim_start(),
484                            scan::colon_or_space,
485                            true,
486                            true,
487                            true,
488                        ));
489                        parsed.set_offset(i64::from(offset))?;
490                    }
491
492                    &RFC2822 => try_consume!(parse_rfc2822(parsed, s)),
493                    &RFC3339 => {
494                        // Used for the `%+` specifier, which has the description:
495                        // "Same as `%Y-%m-%dT%H:%M:%S%.f%:z` (...)
496                        // This format also supports having a `Z` or `UTC` in place of `%:z`."
497                        // Use the relaxed parser to match this description.
498                        try_consume!(parse_rfc3339_relaxed(parsed, s))
499                    }
500                }
501            }
502
503            Item::Error => {
504                return Err(BAD_FORMAT);
505            }
506        }
507    }
508    Ok(s)
509}
510
511/// Accepts a relaxed form of RFC3339.
512/// A space or a 'T' are accepted as the separator between the date and time
513/// parts. Additional spaces are allowed between each component.
514///
515/// All of these examples are equivalent:
516/// ```
517/// # use chrono::{DateTime, offset::FixedOffset};
518/// "2012-12-12T12:12:12Z".parse::<DateTime<FixedOffset>>()?;
519/// "2012-12-12 12:12:12Z".parse::<DateTime<FixedOffset>>()?;
520/// "2012-  12-12T12:  12:12Z".parse::<DateTime<FixedOffset>>()?;
521/// # Ok::<(), chrono::ParseError>(())
522/// ```
523impl str::FromStr for DateTime<FixedOffset> {
524    type Err = ParseError;
525
526    fn from_str(s: &str) -> ParseResult<DateTime<FixedOffset>> {
527        let mut parsed = Parsed::new();
528        let (s, _) = parse_rfc3339_relaxed(&mut parsed, s)?;
529        if !s.trim_start().is_empty() {
530            return Err(TOO_LONG);
531        }
532        parsed.to_datetime()
533    }
534}
535
536/// Accepts a relaxed form of RFC3339.
537///
538/// Differences with RFC3339:
539/// - Values don't require padding to two digits.
540/// - Years outside the range 0...=9999 are accepted, but they must include a sign.
541/// - `UTC` is accepted as a valid timezone name/offset (for compatibility with the debug format of
542///   `DateTime<Utc>`.
543/// - There can be spaces between any of the components.
544/// - The colon in the offset may be missing.
545fn parse_rfc3339_relaxed<'a>(parsed: &mut Parsed, mut s: &'a str) -> ParseResult<(&'a str, ())> {
546    const DATE_ITEMS: &[Item<'static>] = &[
547        Item::Numeric(Numeric::Year, Pad::Zero),
548        Item::Space(""),
549        Item::Literal("-"),
550        Item::Numeric(Numeric::Month, Pad::Zero),
551        Item::Space(""),
552        Item::Literal("-"),
553        Item::Numeric(Numeric::Day, Pad::Zero),
554    ];
555    const TIME_ITEMS: &[Item<'static>] = &[
556        Item::Numeric(Numeric::Hour, Pad::Zero),
557        Item::Space(""),
558        Item::Literal(":"),
559        Item::Numeric(Numeric::Minute, Pad::Zero),
560        Item::Space(""),
561        Item::Literal(":"),
562        Item::Numeric(Numeric::Second, Pad::Zero),
563        Item::Fixed(Fixed::Nanosecond),
564        Item::Space(""),
565    ];
566
567    s = parse_internal(parsed, s, DATE_ITEMS.iter())?;
568
569    s = match s.as_bytes().first() {
570        Some(&b't' | &b'T' | &b' ') => &s[1..],
571        Some(_) => return Err(INVALID),
572        None => return Err(TOO_SHORT),
573    };
574
575    s = parse_internal(parsed, s, TIME_ITEMS.iter())?;
576    s = s.trim_start();
577    let (s, offset) = if s.len() >= 3 && "UTC".as_bytes().eq_ignore_ascii_case(&s.as_bytes()[..3]) {
578        (&s[3..], 0)
579    } else {
580        scan::timezone_offset(s, scan::colon_or_space, true, false, true)?
581    };
582    parsed.set_offset(i64::from(offset))?;
583    Ok((s, ()))
584}
585
586#[cfg(test)]
587mod tests {
588    use crate::format::*;
589    use crate::{DateTime, FixedOffset, NaiveDateTime, TimeZone, Timelike, Utc};
590
591    macro_rules! parsed {
592        ($($k:ident: $v:expr),*) => (#[allow(unused_mut)] {
593            let mut expected = Parsed::new();
594            $(expected.$k = Some($v);)*
595            Ok(expected)
596        });
597    }
598
599    #[test]
600    fn test_parse_whitespace_and_literal() {
601        use crate::format::Item::{Literal, Space};
602
603        // empty string
604        parses("", &[]);
605        check(" ", &[], Err(TOO_LONG));
606        check("a", &[], Err(TOO_LONG));
607        check("abc", &[], Err(TOO_LONG));
608        check("🤠", &[], Err(TOO_LONG));
609
610        // whitespaces
611        parses("", &[Space("")]);
612        parses(" ", &[Space(" ")]);
613        parses("  ", &[Space("  ")]);
614        parses("   ", &[Space("   ")]);
615        parses(" ", &[Space("")]);
616        parses("  ", &[Space(" ")]);
617        parses("   ", &[Space("  ")]);
618        parses("    ", &[Space("  ")]);
619        parses("", &[Space(" ")]);
620        parses(" ", &[Space("  ")]);
621        parses("  ", &[Space("   ")]);
622        parses("  ", &[Space("  "), Space("  ")]);
623        parses("   ", &[Space("  "), Space("  ")]);
624        parses("  ", &[Space(" "), Space(" ")]);
625        parses("   ", &[Space("  "), Space(" ")]);
626        parses("   ", &[Space(" "), Space("  ")]);
627        parses("   ", &[Space(" "), Space(" "), Space(" ")]);
628        parses("\t", &[Space("")]);
629        parses(" \n\r  \n", &[Space("")]);
630        parses("\t", &[Space("\t")]);
631        parses("\t", &[Space(" ")]);
632        parses(" ", &[Space("\t")]);
633        parses("\t\r", &[Space("\t\r")]);
634        parses("\t\r ", &[Space("\t\r ")]);
635        parses("\t \r", &[Space("\t \r")]);
636        parses(" \t\r", &[Space(" \t\r")]);
637        parses(" \n\r  \n", &[Space(" \n\r  \n")]);
638        parses(" \t\n", &[Space(" \t")]);
639        parses(" \n\t", &[Space(" \t\n")]);
640        parses("\u{2002}", &[Space("\u{2002}")]);
641        // most unicode whitespace characters
642        parses(
643            "\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{3000}",
644            &[Space(
645                "\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{3000}",
646            )],
647        );
648        // most unicode whitespace characters
649        parses(
650            "\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{3000}",
651            &[
652                Space("\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}"),
653                Space("\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{3000}"),
654            ],
655        );
656        check("a", &[Space("")], Err(TOO_LONG));
657        check("a", &[Space(" ")], Err(TOO_LONG));
658        // a Space containing a literal does not match a literal
659        check("a", &[Space("a")], Err(TOO_LONG));
660        check("abc", &[Space("")], Err(TOO_LONG));
661        check("abc", &[Space(" ")], Err(TOO_LONG));
662        check(" abc", &[Space("")], Err(TOO_LONG));
663        check(" abc", &[Space(" ")], Err(TOO_LONG));
664
665        // `\u{0363}` is combining diacritic mark "COMBINING LATIN SMALL LETTER A"
666
667        // literal
668        parses("", &[Literal("")]);
669        check("", &[Literal("a")], Err(TOO_SHORT));
670        check(" ", &[Literal("a")], Err(INVALID));
671        parses("a", &[Literal("a")]);
672        parses("+", &[Literal("+")]);
673        parses("-", &[Literal("-")]);
674        parses("−", &[Literal("−")]); // MINUS SIGN (U+2212)
675        parses(" ", &[Literal(" ")]); // a Literal may contain whitespace and match whitespace
676        check("aa", &[Literal("a")], Err(TOO_LONG));
677        check("🤠", &[Literal("a")], Err(INVALID));
678        check("A", &[Literal("a")], Err(INVALID));
679        check("a", &[Literal("z")], Err(INVALID));
680        check("a", &[Literal("🤠")], Err(TOO_SHORT));
681        check("a", &[Literal("\u{0363}a")], Err(TOO_SHORT));
682        check("\u{0363}a", &[Literal("a")], Err(INVALID));
683        parses("\u{0363}a", &[Literal("\u{0363}a")]);
684        check("a", &[Literal("ab")], Err(TOO_SHORT));
685        parses("xy", &[Literal("xy")]);
686        parses("xy", &[Literal("x"), Literal("y")]);
687        parses("1", &[Literal("1")]);
688        parses("1234", &[Literal("1234")]);
689        parses("+1234", &[Literal("+1234")]);
690        parses("-1234", &[Literal("-1234")]);
691        parses("−1234", &[Literal("−1234")]); // MINUS SIGN (U+2212)
692        parses("PST", &[Literal("PST")]);
693        parses("🤠", &[Literal("🤠")]);
694        parses("🤠a", &[Literal("🤠"), Literal("a")]);
695        parses("🤠a🤠", &[Literal("🤠"), Literal("a🤠")]);
696        parses("a🤠b", &[Literal("a"), Literal("🤠"), Literal("b")]);
697        // literals can be together
698        parses("xy", &[Literal("xy")]);
699        parses("xyz", &[Literal("xyz")]);
700        // or literals can be apart
701        parses("xy", &[Literal("x"), Literal("y")]);
702        parses("xyz", &[Literal("x"), Literal("yz")]);
703        parses("xyz", &[Literal("xy"), Literal("z")]);
704        parses("xyz", &[Literal("x"), Literal("y"), Literal("z")]);
705        //
706        check("x y", &[Literal("x"), Literal("y")], Err(INVALID));
707        parses("xy", &[Literal("x"), Space(""), Literal("y")]);
708        parses("x y", &[Literal("x"), Space(""), Literal("y")]);
709        parses("x y", &[Literal("x"), Space(" "), Literal("y")]);
710
711        // whitespaces + literals
712        parses("a\n", &[Literal("a"), Space("\n")]);
713        parses("\tab\n", &[Space("\t"), Literal("ab"), Space("\n")]);
714        parses(
715            "ab\tcd\ne",
716            &[Literal("ab"), Space("\t"), Literal("cd"), Space("\n"), Literal("e")],
717        );
718        parses(
719            "+1ab\tcd\r\n+,.",
720            &[Literal("+1ab"), Space("\t"), Literal("cd"), Space("\r\n"), Literal("+,.")],
721        );
722        // whitespace and literals can be intermixed
723        parses("a\tb", &[Literal("a\tb")]);
724        parses("a\tb", &[Literal("a"), Space("\t"), Literal("b")]);
725    }
726
727    #[test]
728    fn test_parse_numeric() {
729        use crate::format::Item::{Literal, Space};
730        use crate::format::Numeric::*;
731
732        // numeric
733        check("1987", &[num(Year)], parsed!(year: 1987));
734        check("1987 ", &[num(Year)], Err(TOO_LONG));
735        check("0x12", &[num(Year)], Err(TOO_LONG)); // `0` is parsed
736        check("x123", &[num(Year)], Err(INVALID));
737        check("o123", &[num(Year)], Err(INVALID));
738        check("2015", &[num(Year)], parsed!(year: 2015));
739        check("0000", &[num(Year)], parsed!(year: 0));
740        check("9999", &[num(Year)], parsed!(year: 9999));
741        check(" \t987", &[num(Year)], parsed!(year: 987));
742        check(" \t987", &[Space(" \t"), num(Year)], parsed!(year: 987));
743        check(" \t987🤠", &[Space(" \t"), num(Year), Literal("🤠")], parsed!(year: 987));
744        check("987🤠", &[num(Year), Literal("🤠")], parsed!(year: 987));
745        check("5", &[num(Year)], parsed!(year: 5));
746        check("5\0", &[num(Year)], Err(TOO_LONG));
747        check("\x005", &[num(Year)], Err(INVALID));
748        check("", &[num(Year)], Err(TOO_SHORT));
749        check("12345", &[num(Year), Literal("5")], parsed!(year: 1234));
750        check("12345", &[nums(Year), Literal("5")], parsed!(year: 1234));
751        check("12345", &[num0(Year), Literal("5")], parsed!(year: 1234));
752        check("12341234", &[num(Year), num(Year)], parsed!(year: 1234));
753        check("1234 1234", &[num(Year), num(Year)], parsed!(year: 1234));
754        check("1234 1234", &[num(Year), Space(" "), num(Year)], parsed!(year: 1234));
755        check("1234 1235", &[num(Year), num(Year)], Err(IMPOSSIBLE));
756        check("1234 1234", &[num(Year), Literal("x"), num(Year)], Err(INVALID));
757        check("1234x1234", &[num(Year), Literal("x"), num(Year)], parsed!(year: 1234));
758        check("1234 x 1234", &[num(Year), Literal("x"), num(Year)], Err(INVALID));
759        check("1234xx1234", &[num(Year), Literal("x"), num(Year)], Err(INVALID));
760        check("1234xx1234", &[num(Year), Literal("xx"), num(Year)], parsed!(year: 1234));
761        check(
762            "1234 x 1234",
763            &[num(Year), Space(" "), Literal("x"), Space(" "), num(Year)],
764            parsed!(year: 1234),
765        );
766        check(
767            "1234 x 1235",
768            &[num(Year), Space(" "), Literal("x"), Space(" "), Literal("1235")],
769            parsed!(year: 1234),
770        );
771
772        // signed numeric
773        check("-42", &[num(Year)], parsed!(year: -42));
774        check("+42", &[num(Year)], parsed!(year: 42));
775        check("-0042", &[num(Year)], parsed!(year: -42));
776        check("+0042", &[num(Year)], parsed!(year: 42));
777        check("-42195", &[num(Year)], parsed!(year: -42195));
778        check("−42195", &[num(Year)], Err(INVALID)); // MINUS SIGN (U+2212)
779        check("+42195", &[num(Year)], parsed!(year: 42195));
780        check("  -42195", &[num(Year)], parsed!(year: -42195));
781        check(" +42195", &[num(Year)], parsed!(year: 42195));
782        check("  -42195", &[num(Year)], parsed!(year: -42195));
783        check("  +42195", &[num(Year)], parsed!(year: 42195));
784        check("-42195 ", &[num(Year)], Err(TOO_LONG));
785        check("+42195 ", &[num(Year)], Err(TOO_LONG));
786        check("  -   42", &[num(Year)], Err(INVALID));
787        check("  +   42", &[num(Year)], Err(INVALID));
788        check("  -42195", &[Space("  "), num(Year)], parsed!(year: -42195));
789        check("  −42195", &[Space("  "), num(Year)], Err(INVALID)); // MINUS SIGN (U+2212)
790        check("  +42195", &[Space("  "), num(Year)], parsed!(year: 42195));
791        check("  -   42", &[Space("  "), num(Year)], Err(INVALID));
792        check("  +   42", &[Space("  "), num(Year)], Err(INVALID));
793        check("-", &[num(Year)], Err(TOO_SHORT));
794        check("+", &[num(Year)], Err(TOO_SHORT));
795
796        // unsigned numeric
797        check("345", &[num(Ordinal)], parsed!(ordinal: 345));
798        check("+345", &[num(Ordinal)], Err(INVALID));
799        check("-345", &[num(Ordinal)], Err(INVALID));
800        check(" 345", &[num(Ordinal)], parsed!(ordinal: 345));
801        check("−345", &[num(Ordinal)], Err(INVALID)); // MINUS SIGN (U+2212)
802        check("345 ", &[num(Ordinal)], Err(TOO_LONG));
803        check(" 345", &[Space(" "), num(Ordinal)], parsed!(ordinal: 345));
804        check("345 ", &[num(Ordinal), Space(" ")], parsed!(ordinal: 345));
805        check("345🤠 ", &[num(Ordinal), Literal("🤠"), Space(" ")], parsed!(ordinal: 345));
806        check("345🤠", &[num(Ordinal)], Err(TOO_LONG));
807        check("\u{0363}345", &[num(Ordinal)], Err(INVALID));
808        check(" +345", &[num(Ordinal)], Err(INVALID));
809        check(" -345", &[num(Ordinal)], Err(INVALID));
810        check("\t345", &[Space("\t"), num(Ordinal)], parsed!(ordinal: 345));
811        check(" +345", &[Space(" "), num(Ordinal)], Err(INVALID));
812        check(" -345", &[Space(" "), num(Ordinal)], Err(INVALID));
813
814        // various numeric fields
815        check("1234 5678", &[num(Year), num(IsoYear)], parsed!(year: 1234, isoyear: 5678));
816        check("1234 5678", &[num(Year), num(IsoYear)], parsed!(year: 1234, isoyear: 5678));
817        check(
818            "12 34 56 78",
819            &[num(YearDiv100), num(YearMod100), num(IsoYearDiv100), num(IsoYearMod100)],
820            parsed!(year_div_100: 12, year_mod_100: 34, isoyear_div_100: 56, isoyear_mod_100: 78),
821        );
822        check(
823            "1 1 2 3 4 5",
824            &[
825                num(Quarter),
826                num(Month),
827                num(Day),
828                num(WeekFromSun),
829                num(NumDaysFromSun),
830                num(IsoWeek),
831            ],
832            parsed!(quarter: 1, month: 1, day: 2, week_from_sun: 3, weekday: Weekday::Thu, isoweek: 5),
833        );
834        check(
835            "6 7 89 01",
836            &[num(WeekFromMon), num(WeekdayFromMon), num(Ordinal), num(Hour12)],
837            parsed!(week_from_mon: 6, weekday: Weekday::Sun, ordinal: 89, hour_mod_12: 1),
838        );
839        check(
840            "23 45 6 78901234 567890123",
841            &[num(Hour), num(Minute), num(Second), num(Nanosecond), num(Timestamp)],
842            parsed!(hour_div_12: 1, hour_mod_12: 11, minute: 45, second: 6, nanosecond: 78_901_234, timestamp: 567_890_123),
843        );
844    }
845
846    #[test]
847    fn test_parse_fixed() {
848        use crate::format::Fixed::*;
849        use crate::format::Item::{Literal, Space};
850
851        // fixed: month and weekday names
852        check("apr", &[fixed(ShortMonthName)], parsed!(month: 4));
853        check("Apr", &[fixed(ShortMonthName)], parsed!(month: 4));
854        check("APR", &[fixed(ShortMonthName)], parsed!(month: 4));
855        check("ApR", &[fixed(ShortMonthName)], parsed!(month: 4));
856        check("\u{0363}APR", &[fixed(ShortMonthName)], Err(INVALID));
857        check("April", &[fixed(ShortMonthName)], Err(TOO_LONG)); // `Apr` is parsed
858        check("A", &[fixed(ShortMonthName)], Err(TOO_SHORT));
859        check("Sol", &[fixed(ShortMonthName)], Err(INVALID));
860        check("Apr", &[fixed(LongMonthName)], parsed!(month: 4));
861        check("Apri", &[fixed(LongMonthName)], Err(TOO_LONG)); // `Apr` is parsed
862        check("April", &[fixed(LongMonthName)], parsed!(month: 4));
863        check("Aprill", &[fixed(LongMonthName)], Err(TOO_LONG));
864        check("Aprill", &[fixed(LongMonthName), Literal("l")], parsed!(month: 4));
865        check("Aprl", &[fixed(LongMonthName), Literal("l")], parsed!(month: 4));
866        check("April", &[fixed(LongMonthName), Literal("il")], Err(TOO_SHORT)); // do not backtrack
867        check("thu", &[fixed(ShortWeekdayName)], parsed!(weekday: Weekday::Thu));
868        check("Thu", &[fixed(ShortWeekdayName)], parsed!(weekday: Weekday::Thu));
869        check("THU", &[fixed(ShortWeekdayName)], parsed!(weekday: Weekday::Thu));
870        check("tHu", &[fixed(ShortWeekdayName)], parsed!(weekday: Weekday::Thu));
871        check("Thursday", &[fixed(ShortWeekdayName)], Err(TOO_LONG)); // `Thu` is parsed
872        check("T", &[fixed(ShortWeekdayName)], Err(TOO_SHORT));
873        check("The", &[fixed(ShortWeekdayName)], Err(INVALID));
874        check("Nop", &[fixed(ShortWeekdayName)], Err(INVALID));
875        check("Thu", &[fixed(LongWeekdayName)], parsed!(weekday: Weekday::Thu));
876        check("Thur", &[fixed(LongWeekdayName)], Err(TOO_LONG)); // `Thu` is parsed
877        check("Thurs", &[fixed(LongWeekdayName)], Err(TOO_LONG)); // `Thu` is parsed
878        check("Thursday", &[fixed(LongWeekdayName)], parsed!(weekday: Weekday::Thu));
879        check("Thursdays", &[fixed(LongWeekdayName)], Err(TOO_LONG));
880        check("Thursdays", &[fixed(LongWeekdayName), Literal("s")], parsed!(weekday: Weekday::Thu));
881        check("Thus", &[fixed(LongWeekdayName), Literal("s")], parsed!(weekday: Weekday::Thu));
882        check("Thursday", &[fixed(LongWeekdayName), Literal("rsday")], Err(TOO_SHORT)); // do not backtrack
883
884        // fixed: am/pm
885        check("am", &[fixed(LowerAmPm)], parsed!(hour_div_12: 0));
886        check("pm", &[fixed(LowerAmPm)], parsed!(hour_div_12: 1));
887        check("AM", &[fixed(LowerAmPm)], parsed!(hour_div_12: 0));
888        check("PM", &[fixed(LowerAmPm)], parsed!(hour_div_12: 1));
889        check("am", &[fixed(UpperAmPm)], parsed!(hour_div_12: 0));
890        check("pm", &[fixed(UpperAmPm)], parsed!(hour_div_12: 1));
891        check("AM", &[fixed(UpperAmPm)], parsed!(hour_div_12: 0));
892        check("PM", &[fixed(UpperAmPm)], parsed!(hour_div_12: 1));
893        check("Am", &[fixed(LowerAmPm)], parsed!(hour_div_12: 0));
894        check(" Am", &[Space(" "), fixed(LowerAmPm)], parsed!(hour_div_12: 0));
895        check("Am🤠", &[fixed(LowerAmPm), Literal("🤠")], parsed!(hour_div_12: 0));
896        check("🤠Am", &[Literal("🤠"), fixed(LowerAmPm)], parsed!(hour_div_12: 0));
897        check("\u{0363}am", &[fixed(LowerAmPm)], Err(INVALID));
898        check("\u{0360}am", &[fixed(LowerAmPm)], Err(INVALID));
899        check(" Am", &[fixed(LowerAmPm)], Err(INVALID));
900        check("Am ", &[fixed(LowerAmPm)], Err(TOO_LONG));
901        check("a.m.", &[fixed(LowerAmPm)], Err(INVALID));
902        check("A.M.", &[fixed(LowerAmPm)], Err(INVALID));
903        check("ame", &[fixed(LowerAmPm)], Err(TOO_LONG)); // `am` is parsed
904        check("a", &[fixed(LowerAmPm)], Err(TOO_SHORT));
905        check("p", &[fixed(LowerAmPm)], Err(TOO_SHORT));
906        check("x", &[fixed(LowerAmPm)], Err(TOO_SHORT));
907        check("xx", &[fixed(LowerAmPm)], Err(INVALID));
908        check("", &[fixed(LowerAmPm)], Err(TOO_SHORT));
909    }
910
911    #[test]
912    fn test_parse_fixed_nanosecond() {
913        use crate::format::Fixed::Nanosecond;
914        use crate::format::InternalInternal::*;
915        use crate::format::Item::Literal;
916        use crate::format::Numeric::Second;
917
918        // fixed: dot plus nanoseconds
919        check("", &[fixed(Nanosecond)], parsed!()); // no field set, but not an error
920        check(".", &[fixed(Nanosecond)], Err(TOO_SHORT));
921        check("4", &[fixed(Nanosecond)], Err(TOO_LONG)); // never consumes `4`
922        check("4", &[fixed(Nanosecond), num(Second)], parsed!(second: 4));
923        check(".0", &[fixed(Nanosecond)], parsed!(nanosecond: 0));
924        check(".4", &[fixed(Nanosecond)], parsed!(nanosecond: 400_000_000));
925        check(".42", &[fixed(Nanosecond)], parsed!(nanosecond: 420_000_000));
926        check(".421", &[fixed(Nanosecond)], parsed!(nanosecond: 421_000_000));
927        check(".42195", &[fixed(Nanosecond)], parsed!(nanosecond: 421_950_000));
928        check(".421951", &[fixed(Nanosecond)], parsed!(nanosecond: 421_951_000));
929        check(".4219512", &[fixed(Nanosecond)], parsed!(nanosecond: 421_951_200));
930        check(".42195123", &[fixed(Nanosecond)], parsed!(nanosecond: 421_951_230));
931        check(".421950803", &[fixed(Nanosecond)], parsed!(nanosecond: 421_950_803));
932        check(".4219508035", &[fixed(Nanosecond)], parsed!(nanosecond: 421_950_803));
933        check(".42195080354", &[fixed(Nanosecond)], parsed!(nanosecond: 421_950_803));
934        check(".421950803547", &[fixed(Nanosecond)], parsed!(nanosecond: 421_950_803));
935        check(".000000003", &[fixed(Nanosecond)], parsed!(nanosecond: 3));
936        check(".0000000031", &[fixed(Nanosecond)], parsed!(nanosecond: 3));
937        check(".0000000035", &[fixed(Nanosecond)], parsed!(nanosecond: 3));
938        check(".000000003547", &[fixed(Nanosecond)], parsed!(nanosecond: 3));
939        check(".0000000009", &[fixed(Nanosecond)], parsed!(nanosecond: 0));
940        check(".000000000547", &[fixed(Nanosecond)], parsed!(nanosecond: 0));
941        check(".0000000009999999999999999999999999", &[fixed(Nanosecond)], parsed!(nanosecond: 0));
942        check(".4🤠", &[fixed(Nanosecond), Literal("🤠")], parsed!(nanosecond: 400_000_000));
943        check(".4x", &[fixed(Nanosecond)], Err(TOO_LONG));
944        check(".  4", &[fixed(Nanosecond)], Err(INVALID));
945        check("  .4", &[fixed(Nanosecond)], Err(TOO_LONG)); // no automatic trimming
946
947        // fixed: nanoseconds without the dot
948        check("", &[internal_fixed(Nanosecond3NoDot)], Err(TOO_SHORT));
949        check(".", &[internal_fixed(Nanosecond3NoDot)], Err(TOO_SHORT));
950        check("0", &[internal_fixed(Nanosecond3NoDot)], Err(TOO_SHORT));
951        check("4", &[internal_fixed(Nanosecond3NoDot)], Err(TOO_SHORT));
952        check("42", &[internal_fixed(Nanosecond3NoDot)], Err(TOO_SHORT));
953        check("421", &[internal_fixed(Nanosecond3NoDot)], parsed!(nanosecond: 421_000_000));
954        check("4210", &[internal_fixed(Nanosecond3NoDot)], Err(TOO_LONG));
955        check(
956            "42143",
957            &[internal_fixed(Nanosecond3NoDot), num(Second)],
958            parsed!(nanosecond: 421_000_000, second: 43),
959        );
960        check(
961            "421🤠",
962            &[internal_fixed(Nanosecond3NoDot), Literal("🤠")],
963            parsed!(nanosecond: 421_000_000),
964        );
965        check(
966            "🤠421",
967            &[Literal("🤠"), internal_fixed(Nanosecond3NoDot)],
968            parsed!(nanosecond: 421_000_000),
969        );
970        check("42195", &[internal_fixed(Nanosecond3NoDot)], Err(TOO_LONG));
971        check("123456789", &[internal_fixed(Nanosecond3NoDot)], Err(TOO_LONG));
972        check("4x", &[internal_fixed(Nanosecond3NoDot)], Err(TOO_SHORT));
973        check("  4", &[internal_fixed(Nanosecond3NoDot)], Err(INVALID));
974        check(".421", &[internal_fixed(Nanosecond3NoDot)], Err(INVALID));
975
976        check("", &[internal_fixed(Nanosecond6NoDot)], Err(TOO_SHORT));
977        check(".", &[internal_fixed(Nanosecond6NoDot)], Err(TOO_SHORT));
978        check("0", &[internal_fixed(Nanosecond6NoDot)], Err(TOO_SHORT));
979        check("1234", &[internal_fixed(Nanosecond6NoDot)], Err(TOO_SHORT));
980        check("12345", &[internal_fixed(Nanosecond6NoDot)], Err(TOO_SHORT));
981        check("421950", &[internal_fixed(Nanosecond6NoDot)], parsed!(nanosecond: 421_950_000));
982        check("000003", &[internal_fixed(Nanosecond6NoDot)], parsed!(nanosecond: 3000));
983        check("000000", &[internal_fixed(Nanosecond6NoDot)], parsed!(nanosecond: 0));
984        check("1234567", &[internal_fixed(Nanosecond6NoDot)], Err(TOO_LONG));
985        check("123456789", &[internal_fixed(Nanosecond6NoDot)], Err(TOO_LONG));
986        check("4x", &[internal_fixed(Nanosecond6NoDot)], Err(TOO_SHORT));
987        check("     4", &[internal_fixed(Nanosecond6NoDot)], Err(INVALID));
988        check(".42100", &[internal_fixed(Nanosecond6NoDot)], Err(INVALID));
989
990        check("", &[internal_fixed(Nanosecond9NoDot)], Err(TOO_SHORT));
991        check(".", &[internal_fixed(Nanosecond9NoDot)], Err(TOO_SHORT));
992        check("42195", &[internal_fixed(Nanosecond9NoDot)], Err(TOO_SHORT));
993        check("12345678", &[internal_fixed(Nanosecond9NoDot)], Err(TOO_SHORT));
994        check("421950803", &[internal_fixed(Nanosecond9NoDot)], parsed!(nanosecond: 421_950_803));
995        check("000000003", &[internal_fixed(Nanosecond9NoDot)], parsed!(nanosecond: 3));
996        check(
997            "42195080354",
998            &[internal_fixed(Nanosecond9NoDot), num(Second)],
999            parsed!(nanosecond: 421_950_803, second: 54),
1000        ); // don't skip digits that come after the 9
1001        check("1234567890", &[internal_fixed(Nanosecond9NoDot)], Err(TOO_LONG));
1002        check("000000000", &[internal_fixed(Nanosecond9NoDot)], parsed!(nanosecond: 0));
1003        check("00000000x", &[internal_fixed(Nanosecond9NoDot)], Err(INVALID));
1004        check("        4", &[internal_fixed(Nanosecond9NoDot)], Err(INVALID));
1005        check(".42100000", &[internal_fixed(Nanosecond9NoDot)], Err(INVALID));
1006    }
1007
1008    #[test]
1009    fn test_parse_fixed_timezone_offset() {
1010        use crate::format::Fixed::*;
1011        use crate::format::InternalInternal::*;
1012        use crate::format::Item::Literal;
1013
1014        // TimezoneOffset
1015        check("1", &[fixed(TimezoneOffset)], Err(INVALID));
1016        check("12", &[fixed(TimezoneOffset)], Err(INVALID));
1017        check("123", &[fixed(TimezoneOffset)], Err(INVALID));
1018        check("1234", &[fixed(TimezoneOffset)], Err(INVALID));
1019        check("12345", &[fixed(TimezoneOffset)], Err(INVALID));
1020        check("123456", &[fixed(TimezoneOffset)], Err(INVALID));
1021        check("1234567", &[fixed(TimezoneOffset)], Err(INVALID));
1022        check("+1", &[fixed(TimezoneOffset)], Err(TOO_SHORT));
1023        check("+12", &[fixed(TimezoneOffset)], Err(TOO_SHORT));
1024        check("+123", &[fixed(TimezoneOffset)], Err(TOO_SHORT));
1025        check("+1234", &[fixed(TimezoneOffset)], parsed!(offset: 45_240));
1026        check("+12345", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1027        check("+123456", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1028        check("+1234567", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1029        check("+12345678", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1030        check("+12:", &[fixed(TimezoneOffset)], Err(TOO_SHORT));
1031        check("+12:3", &[fixed(TimezoneOffset)], Err(TOO_SHORT));
1032        check("+12:34", &[fixed(TimezoneOffset)], parsed!(offset: 45_240));
1033        check("-12:34", &[fixed(TimezoneOffset)], parsed!(offset: -45_240));
1034        check("−12:34", &[fixed(TimezoneOffset)], parsed!(offset: -45_240)); // MINUS SIGN (U+2212)
1035        check("+12:34:", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1036        check("+12:34:5", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1037        check("+12:34:56", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1038        check("+12:34:56:", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1039        check("+12 34", &[fixed(TimezoneOffset)], parsed!(offset: 45_240));
1040        check("+12  34", &[fixed(TimezoneOffset)], parsed!(offset: 45_240));
1041        check("12:34", &[fixed(TimezoneOffset)], Err(INVALID));
1042        check("12:34:56", &[fixed(TimezoneOffset)], Err(INVALID));
1043        check("+12::34", &[fixed(TimezoneOffset)], parsed!(offset: 45_240));
1044        check("+12: :34", &[fixed(TimezoneOffset)], parsed!(offset: 45_240));
1045        check("+12:::34", &[fixed(TimezoneOffset)], parsed!(offset: 45_240));
1046        check("+12::::34", &[fixed(TimezoneOffset)], parsed!(offset: 45_240));
1047        check("+12::34", &[fixed(TimezoneOffset)], parsed!(offset: 45_240));
1048        check("+12:34:56", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1049        check("+12:3456", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1050        check("+1234:56", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1051        check("+1234:567", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1052        check("+00:00", &[fixed(TimezoneOffset)], parsed!(offset: 0));
1053        check("-00:00", &[fixed(TimezoneOffset)], parsed!(offset: 0));
1054        check("−00:00", &[fixed(TimezoneOffset)], parsed!(offset: 0)); // MINUS SIGN (U+2212)
1055        check("+00:01", &[fixed(TimezoneOffset)], parsed!(offset: 60));
1056        check("-00:01", &[fixed(TimezoneOffset)], parsed!(offset: -60));
1057        check("+00:30", &[fixed(TimezoneOffset)], parsed!(offset: 1_800));
1058        check("-00:30", &[fixed(TimezoneOffset)], parsed!(offset: -1_800));
1059        check("+24:00", &[fixed(TimezoneOffset)], parsed!(offset: 86_400));
1060        check("-24:00", &[fixed(TimezoneOffset)], parsed!(offset: -86_400));
1061        check("−24:00", &[fixed(TimezoneOffset)], parsed!(offset: -86_400)); // MINUS SIGN (U+2212)
1062        check("+99:59", &[fixed(TimezoneOffset)], parsed!(offset: 359_940));
1063        check("-99:59", &[fixed(TimezoneOffset)], parsed!(offset: -359_940));
1064        check("+00:60", &[fixed(TimezoneOffset)], Err(OUT_OF_RANGE));
1065        check("+00:99", &[fixed(TimezoneOffset)], Err(OUT_OF_RANGE));
1066        check("#12:34", &[fixed(TimezoneOffset)], Err(INVALID));
1067        check("+12:34 ", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1068        check("+12 34 ", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1069        check(" +12:34", &[fixed(TimezoneOffset)], parsed!(offset: 45_240));
1070        check(" -12:34", &[fixed(TimezoneOffset)], parsed!(offset: -45_240));
1071        check(" −12:34", &[fixed(TimezoneOffset)], parsed!(offset: -45_240)); // MINUS SIGN (U+2212)
1072        check("  +12:34", &[fixed(TimezoneOffset)], parsed!(offset: 45_240));
1073        check("  -12:34", &[fixed(TimezoneOffset)], parsed!(offset: -45_240));
1074        check("\t -12:34", &[fixed(TimezoneOffset)], parsed!(offset: -45_240));
1075        check("-12: 34", &[fixed(TimezoneOffset)], parsed!(offset: -45_240));
1076        check("-12 :34", &[fixed(TimezoneOffset)], parsed!(offset: -45_240));
1077        check("-12 : 34", &[fixed(TimezoneOffset)], parsed!(offset: -45_240));
1078        check("-12 :  34", &[fixed(TimezoneOffset)], parsed!(offset: -45_240));
1079        check("-12  : 34", &[fixed(TimezoneOffset)], parsed!(offset: -45_240));
1080        check("-12:  34", &[fixed(TimezoneOffset)], parsed!(offset: -45_240));
1081        check("-12  :34", &[fixed(TimezoneOffset)], parsed!(offset: -45_240));
1082        check("-12  :  34", &[fixed(TimezoneOffset)], parsed!(offset: -45_240));
1083        check("12:34 ", &[fixed(TimezoneOffset)], Err(INVALID));
1084        check(" 12:34", &[fixed(TimezoneOffset)], Err(INVALID));
1085        check("", &[fixed(TimezoneOffset)], Err(TOO_SHORT));
1086        check("+", &[fixed(TimezoneOffset)], Err(TOO_SHORT));
1087        check(
1088            "+12345",
1089            &[fixed(TimezoneOffset), num(Numeric::Day)],
1090            parsed!(offset: 45_240, day: 5),
1091        );
1092        check(
1093            "+12:345",
1094            &[fixed(TimezoneOffset), num(Numeric::Day)],
1095            parsed!(offset: 45_240, day: 5),
1096        );
1097        check("+12:34:", &[fixed(TimezoneOffset), Literal(":")], parsed!(offset: 45_240));
1098        check("Z12:34", &[fixed(TimezoneOffset)], Err(INVALID));
1099        check("X12:34", &[fixed(TimezoneOffset)], Err(INVALID));
1100        check("Z+12:34", &[fixed(TimezoneOffset)], Err(INVALID));
1101        check("X+12:34", &[fixed(TimezoneOffset)], Err(INVALID));
1102        check("X−12:34", &[fixed(TimezoneOffset)], Err(INVALID)); // MINUS SIGN (U+2212)
1103        check("🤠+12:34", &[fixed(TimezoneOffset)], Err(INVALID));
1104        check("+12:34🤠", &[fixed(TimezoneOffset)], Err(TOO_LONG));
1105        check("+12:🤠34", &[fixed(TimezoneOffset)], Err(INVALID));
1106        check("+1234🤠", &[fixed(TimezoneOffset), Literal("🤠")], parsed!(offset: 45_240));
1107        check("-1234🤠", &[fixed(TimezoneOffset), Literal("🤠")], parsed!(offset: -45_240));
1108        check("−1234🤠", &[fixed(TimezoneOffset), Literal("🤠")], parsed!(offset: -45_240)); // MINUS SIGN (U+2212)
1109        check("+12:34🤠", &[fixed(TimezoneOffset), Literal("🤠")], parsed!(offset: 45_240));
1110        check("-12:34🤠", &[fixed(TimezoneOffset), Literal("🤠")], parsed!(offset: -45_240));
1111        check("−12:34🤠", &[fixed(TimezoneOffset), Literal("🤠")], parsed!(offset: -45_240)); // MINUS SIGN (U+2212)
1112        check("🤠+12:34", &[Literal("🤠"), fixed(TimezoneOffset)], parsed!(offset: 45_240));
1113        check("Z", &[fixed(TimezoneOffset)], Err(INVALID));
1114        check("A", &[fixed(TimezoneOffset)], Err(INVALID));
1115        check("PST", &[fixed(TimezoneOffset)], Err(INVALID));
1116        check("#Z", &[fixed(TimezoneOffset)], Err(INVALID));
1117        check(":Z", &[fixed(TimezoneOffset)], Err(INVALID));
1118        check("+Z", &[fixed(TimezoneOffset)], Err(TOO_SHORT));
1119        check("+:Z", &[fixed(TimezoneOffset)], Err(INVALID));
1120        check("+Z:", &[fixed(TimezoneOffset)], Err(INVALID));
1121        check("z", &[fixed(TimezoneOffset)], Err(INVALID));
1122        check(" :Z", &[fixed(TimezoneOffset)], Err(INVALID));
1123        check(" Z", &[fixed(TimezoneOffset)], Err(INVALID));
1124        check(" z", &[fixed(TimezoneOffset)], Err(INVALID));
1125
1126        // TimezoneOffsetColon
1127        check("1", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1128        check("12", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1129        check("123", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1130        check("1234", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1131        check("12345", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1132        check("123456", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1133        check("1234567", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1134        check("12345678", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1135        check("+1", &[fixed(TimezoneOffsetColon)], Err(TOO_SHORT));
1136        check("+12", &[fixed(TimezoneOffsetColon)], Err(TOO_SHORT));
1137        check("+123", &[fixed(TimezoneOffsetColon)], Err(TOO_SHORT));
1138        check("+1234", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1139        check("-1234", &[fixed(TimezoneOffsetColon)], parsed!(offset: -45_240));
1140        check("−1234", &[fixed(TimezoneOffsetColon)], parsed!(offset: -45_240)); // MINUS SIGN (U+2212)
1141        check("+12345", &[fixed(TimezoneOffsetColon)], Err(TOO_LONG));
1142        check("+123456", &[fixed(TimezoneOffsetColon)], Err(TOO_LONG));
1143        check("+1234567", &[fixed(TimezoneOffsetColon)], Err(TOO_LONG));
1144        check("+12345678", &[fixed(TimezoneOffsetColon)], Err(TOO_LONG));
1145        check("1:", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1146        check("12:", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1147        check("12:3", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1148        check("12:34", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1149        check("12:34:", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1150        check("12:34:5", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1151        check("12:34:56", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1152        check("+1:", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1153        check("+12:", &[fixed(TimezoneOffsetColon)], Err(TOO_SHORT));
1154        check("+12:3", &[fixed(TimezoneOffsetColon)], Err(TOO_SHORT));
1155        check("+12:34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1156        check("-12:34", &[fixed(TimezoneOffsetColon)], parsed!(offset: -45_240));
1157        check("−12:34", &[fixed(TimezoneOffsetColon)], parsed!(offset: -45_240)); // MINUS SIGN (U+2212)
1158        check("+12:34:", &[fixed(TimezoneOffsetColon)], Err(TOO_LONG));
1159        check("+12:34:5", &[fixed(TimezoneOffsetColon)], Err(TOO_LONG));
1160        check("+12:34:56", &[fixed(TimezoneOffsetColon)], Err(TOO_LONG));
1161        check("+12:34:56:", &[fixed(TimezoneOffsetColon)], Err(TOO_LONG));
1162        check("+12:34:56:7", &[fixed(TimezoneOffsetColon)], Err(TOO_LONG));
1163        check("+12:34:56:78", &[fixed(TimezoneOffsetColon)], Err(TOO_LONG));
1164        check("+12:3456", &[fixed(TimezoneOffsetColon)], Err(TOO_LONG));
1165        check("+1234:56", &[fixed(TimezoneOffsetColon)], Err(TOO_LONG));
1166        check("−12:34", &[fixed(TimezoneOffsetColon)], parsed!(offset: -45_240)); // MINUS SIGN (U+2212)
1167        check("−12 : 34", &[fixed(TimezoneOffsetColon)], parsed!(offset: -45_240)); // MINUS SIGN (U+2212)
1168        check("+12 :34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1169        check("+12: 34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1170        check("+12 34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1171        check("+12: 34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1172        check("+12 :34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1173        check("+12 : 34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1174        check("-12 : 34", &[fixed(TimezoneOffsetColon)], parsed!(offset: -45_240));
1175        check("+12  : 34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1176        check("+12 :  34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1177        check("+12  :  34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1178        check("+12::34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1179        check("+12: :34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1180        check("+12:::34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1181        check("+12::::34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1182        check("+12::34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1183        check("#1234", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1184        check("#12:34", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1185        check("+12:34 ", &[fixed(TimezoneOffsetColon)], Err(TOO_LONG));
1186        check(" +12:34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1187        check("\t+12:34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1188        check("\t\t+12:34", &[fixed(TimezoneOffsetColon)], parsed!(offset: 45_240));
1189        check("12:34 ", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1190        check(" 12:34", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1191        check("", &[fixed(TimezoneOffsetColon)], Err(TOO_SHORT));
1192        check("+", &[fixed(TimezoneOffsetColon)], Err(TOO_SHORT));
1193        check(":", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1194        check(
1195            "+12345",
1196            &[fixed(TimezoneOffsetColon), num(Numeric::Day)],
1197            parsed!(offset: 45_240, day: 5),
1198        );
1199        check(
1200            "+12:345",
1201            &[fixed(TimezoneOffsetColon), num(Numeric::Day)],
1202            parsed!(offset: 45_240, day: 5),
1203        );
1204        check("+12:34:", &[fixed(TimezoneOffsetColon), Literal(":")], parsed!(offset: 45_240));
1205        check("Z", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1206        check("A", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1207        check("PST", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1208        check("#Z", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1209        check(":Z", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1210        check("+Z", &[fixed(TimezoneOffsetColon)], Err(TOO_SHORT));
1211        check("+:Z", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1212        check("+Z:", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1213        check("z", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1214        check(" :Z", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1215        check(" Z", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1216        check(" z", &[fixed(TimezoneOffsetColon)], Err(INVALID));
1217        // testing `TimezoneOffsetColon` also tests same path as `TimezoneOffsetDoubleColon`
1218        // and `TimezoneOffsetTripleColon` for function `parse_internal`.
1219        // No need for separate tests for `TimezoneOffsetDoubleColon` and
1220        // `TimezoneOffsetTripleColon`.
1221
1222        // TimezoneOffsetZ
1223        check("1", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1224        check("12", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1225        check("123", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1226        check("1234", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1227        check("12345", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1228        check("123456", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1229        check("1234567", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1230        check("12345678", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1231        check("+1", &[fixed(TimezoneOffsetZ)], Err(TOO_SHORT));
1232        check("+12", &[fixed(TimezoneOffsetZ)], Err(TOO_SHORT));
1233        check("+123", &[fixed(TimezoneOffsetZ)], Err(TOO_SHORT));
1234        check("+1234", &[fixed(TimezoneOffsetZ)], parsed!(offset: 45_240));
1235        check("-1234", &[fixed(TimezoneOffsetZ)], parsed!(offset: -45_240));
1236        check("−1234", &[fixed(TimezoneOffsetZ)], parsed!(offset: -45_240)); // MINUS SIGN (U+2212)
1237        check("+12345", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1238        check("+123456", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1239        check("+1234567", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1240        check("+12345678", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1241        check("1:", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1242        check("12:", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1243        check("12:3", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1244        check("12:34", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1245        check("12:34:", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1246        check("12:34:5", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1247        check("12:34:56", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1248        check("+1:", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1249        check("+12:", &[fixed(TimezoneOffsetZ)], Err(TOO_SHORT));
1250        check("+12:3", &[fixed(TimezoneOffsetZ)], Err(TOO_SHORT));
1251        check("+12:34", &[fixed(TimezoneOffsetZ)], parsed!(offset: 45_240));
1252        check("-12:34", &[fixed(TimezoneOffsetZ)], parsed!(offset: -45_240));
1253        check("−12:34", &[fixed(TimezoneOffsetZ)], parsed!(offset: -45_240)); // MINUS SIGN (U+2212)
1254        check("+12:34:", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1255        check("+12:34:5", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1256        check("+12:34:56", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1257        check("+12:34:56:", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1258        check("+12:34:56:7", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1259        check("+12:34:56:78", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1260        check("+12::34", &[fixed(TimezoneOffsetZ)], parsed!(offset: 45_240));
1261        check("+12:3456", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1262        check("+1234:56", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1263        check("+12 34", &[fixed(TimezoneOffsetZ)], parsed!(offset: 45_240));
1264        check("+12  34", &[fixed(TimezoneOffsetZ)], parsed!(offset: 45_240));
1265        check("+12: 34", &[fixed(TimezoneOffsetZ)], parsed!(offset: 45_240));
1266        check("+12 :34", &[fixed(TimezoneOffsetZ)], parsed!(offset: 45_240));
1267        check("+12 : 34", &[fixed(TimezoneOffsetZ)], parsed!(offset: 45_240));
1268        check("+12  : 34", &[fixed(TimezoneOffsetZ)], parsed!(offset: 45_240));
1269        check("+12 :  34", &[fixed(TimezoneOffsetZ)], parsed!(offset: 45_240));
1270        check("+12  :  34", &[fixed(TimezoneOffsetZ)], parsed!(offset: 45_240));
1271        check("12:34 ", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1272        check(" 12:34", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1273        check("+12:34 ", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1274        check("+12 34 ", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1275        check(" +12:34", &[fixed(TimezoneOffsetZ)], parsed!(offset: 45_240));
1276        check(
1277            "+12345",
1278            &[fixed(TimezoneOffsetZ), num(Numeric::Day)],
1279            parsed!(offset: 45_240, day: 5),
1280        );
1281        check(
1282            "+12:345",
1283            &[fixed(TimezoneOffsetZ), num(Numeric::Day)],
1284            parsed!(offset: 45_240, day: 5),
1285        );
1286        check("+12:34:", &[fixed(TimezoneOffsetZ), Literal(":")], parsed!(offset: 45_240));
1287        check("Z12:34", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1288        check("X12:34", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1289        check("Z", &[fixed(TimezoneOffsetZ)], parsed!(offset: 0));
1290        check("z", &[fixed(TimezoneOffsetZ)], parsed!(offset: 0));
1291        check(" Z", &[fixed(TimezoneOffsetZ)], parsed!(offset: 0));
1292        check(" z", &[fixed(TimezoneOffsetZ)], parsed!(offset: 0));
1293        check("\u{0363}Z", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1294        check("Z ", &[fixed(TimezoneOffsetZ)], Err(TOO_LONG));
1295        check("A", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1296        check("PST", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1297        check("#Z", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1298        check(":Z", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1299        check(":z", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1300        check("+Z", &[fixed(TimezoneOffsetZ)], Err(TOO_SHORT));
1301        check("-Z", &[fixed(TimezoneOffsetZ)], Err(TOO_SHORT));
1302        check("+A", &[fixed(TimezoneOffsetZ)], Err(TOO_SHORT));
1303        check("+🙃", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1304        check("+Z:", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1305        check(" :Z", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1306        check(" +Z", &[fixed(TimezoneOffsetZ)], Err(TOO_SHORT));
1307        check(" -Z", &[fixed(TimezoneOffsetZ)], Err(TOO_SHORT));
1308        check("+:Z", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1309        check("Y", &[fixed(TimezoneOffsetZ)], Err(INVALID));
1310        check("Zulu", &[fixed(TimezoneOffsetZ), Literal("ulu")], parsed!(offset: 0));
1311        check("zulu", &[fixed(TimezoneOffsetZ), Literal("ulu")], parsed!(offset: 0));
1312        check("+1234ulu", &[fixed(TimezoneOffsetZ), Literal("ulu")], parsed!(offset: 45_240));
1313        check("+12:34ulu", &[fixed(TimezoneOffsetZ), Literal("ulu")], parsed!(offset: 45_240));
1314        // Testing `TimezoneOffsetZ` also tests same path as `TimezoneOffsetColonZ`
1315        // in function `parse_internal`.
1316        // No need for separate tests for `TimezoneOffsetColonZ`.
1317
1318        // TimezoneOffsetPermissive
1319        check("1", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1320        check("12", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1321        check("123", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1322        check("1234", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1323        check("12345", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1324        check("123456", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1325        check("1234567", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1326        check("12345678", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1327        check("+1", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_SHORT));
1328        check("+12", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 43_200));
1329        check("+123", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_SHORT));
1330        check("+1234", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1331        check("-1234", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: -45_240));
1332        check("−1234", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: -45_240)); // MINUS SIGN (U+2212)
1333        check("+12345", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_LONG));
1334        check("+123456", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_LONG));
1335        check("+1234567", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_LONG));
1336        check("+12345678", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_LONG));
1337        check("1:", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1338        check("12:", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1339        check("12:3", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1340        check("12:34", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1341        check("12:34:", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1342        check("12:34:5", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1343        check("12:34:56", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1344        check("+1:", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1345        check("+12:", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 43_200));
1346        check("+12:3", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_SHORT));
1347        check("+12:34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1348        check("-12:34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: -45_240));
1349        check("−12:34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: -45_240)); // MINUS SIGN (U+2212)
1350        check("+12:34:", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_LONG));
1351        check("+12:34:5", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_LONG));
1352        check("+12:34:56", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_LONG));
1353        check("+12:34:56:", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_LONG));
1354        check("+12:34:56:7", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_LONG));
1355        check("+12:34:56:78", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_LONG));
1356        check("+12 34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1357        check("+12  34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1358        check("+12 :34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1359        check("+12: 34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1360        check("+12 : 34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1361        check("+12  :34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1362        check("+12:  34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1363        check("+12  :  34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1364        check("+12::34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1365        check("+12 ::34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1366        check("+12: :34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1367        check("+12:: 34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1368        check("+12  ::34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1369        check("+12:  :34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1370        check("+12::  34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1371        check("+12:::34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1372        check("+12::::34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1373        check("12:34 ", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1374        check(" 12:34", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1375        check("+12:34 ", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_LONG));
1376        check(" +12:34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 45_240));
1377        check(" -12:34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: -45_240));
1378        check(" −12:34", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: -45_240)); // MINUS SIGN (U+2212)
1379        check(
1380            "+12345",
1381            &[internal_fixed(TimezoneOffsetPermissive), num(Numeric::Day)],
1382            parsed!(offset: 45_240, day: 5),
1383        );
1384        check(
1385            "+12:345",
1386            &[internal_fixed(TimezoneOffsetPermissive), num(Numeric::Day)],
1387            parsed!(offset: 45_240, day: 5),
1388        );
1389        check(
1390            "+12:34:",
1391            &[internal_fixed(TimezoneOffsetPermissive), Literal(":")],
1392            parsed!(offset: 45_240),
1393        );
1394        check("🤠+12:34", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1395        check("+12:34🤠", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_LONG));
1396        check("+12:🤠34", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1397        check(
1398            "+12:34🤠",
1399            &[internal_fixed(TimezoneOffsetPermissive), Literal("🤠")],
1400            parsed!(offset: 45_240),
1401        );
1402        check(
1403            "🤠+12:34",
1404            &[Literal("🤠"), internal_fixed(TimezoneOffsetPermissive)],
1405            parsed!(offset: 45_240),
1406        );
1407        check("Z", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 0));
1408        check("A", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1409        check("PST", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1410        check("z", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 0));
1411        check(" Z", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 0));
1412        check(" z", &[internal_fixed(TimezoneOffsetPermissive)], parsed!(offset: 0));
1413        check("Z ", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_LONG));
1414        check("#Z", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1415        check(":Z", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1416        check(":z", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1417        check("+Z", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_SHORT));
1418        check("-Z", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_SHORT));
1419        check("+A", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_SHORT));
1420        check("+PST", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1421        check("+🙃", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1422        check("+Z:", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1423        check(" :Z", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1424        check(" +Z", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_SHORT));
1425        check(" -Z", &[internal_fixed(TimezoneOffsetPermissive)], Err(TOO_SHORT));
1426        check("+:Z", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1427        check("Y", &[internal_fixed(TimezoneOffsetPermissive)], Err(INVALID));
1428
1429        // TimezoneName
1430        check("CEST", &[fixed(TimezoneName)], parsed!());
1431        check("cest", &[fixed(TimezoneName)], parsed!()); // lowercase
1432        check("XXXXXXXX", &[fixed(TimezoneName)], parsed!()); // not a real timezone name
1433        check("!!!!", &[fixed(TimezoneName)], parsed!()); // not a real timezone name!
1434        check("CEST 5", &[fixed(TimezoneName), Literal(" "), num(Numeric::Day)], parsed!(day: 5));
1435        check("CEST ", &[fixed(TimezoneName)], Err(TOO_LONG));
1436        check(" CEST", &[fixed(TimezoneName)], Err(TOO_LONG));
1437        check("CE ST", &[fixed(TimezoneName)], Err(TOO_LONG));
1438    }
1439
1440    #[test]
1441    #[rustfmt::skip]
1442    fn test_parse_practical_examples() {
1443        use crate::format::InternalInternal::*;
1444        use crate::format::Item::{Literal, Space};
1445        use crate::format::Numeric::*;
1446
1447        // some practical examples
1448        check(
1449            "2015-02-04T14:37:05+09:00",
1450            &[
1451                num(Year), Literal("-"), num(Month), Literal("-"), num(Day), Literal("T"),
1452                num(Hour), Literal(":"), num(Minute), Literal(":"), num(Second),
1453                fixed(Fixed::TimezoneOffset),
1454            ],
1455            parsed!(
1456                year: 2015, month: 2, day: 4, hour_div_12: 1, hour_mod_12: 2, minute: 37,
1457                second: 5, offset: 32400
1458            ),
1459        );
1460        check(
1461            "2015-02-04T14:37:05-09:00",
1462            &[
1463                num(Year), Literal("-"), num(Month), Literal("-"), num(Day), Literal("T"),
1464                num(Hour), Literal(":"), num(Minute), Literal(":"), num(Second),
1465                fixed(Fixed::TimezoneOffset),
1466            ],
1467            parsed!(
1468                year: 2015, month: 2, day: 4, hour_div_12: 1, hour_mod_12: 2, minute: 37,
1469                second: 5, offset: -32400
1470            ),
1471        );
1472        check(
1473            "2015-02-04T14:37:05−09:00", // timezone offset using MINUS SIGN (U+2212)
1474            &[
1475                num(Year), Literal("-"), num(Month), Literal("-"), num(Day), Literal("T"),
1476                num(Hour), Literal(":"), num(Minute), Literal(":"), num(Second),
1477                fixed(Fixed::TimezoneOffset)
1478            ],
1479            parsed!(
1480                year: 2015, month: 2, day: 4, hour_div_12: 1, hour_mod_12: 2, minute: 37,
1481                second: 5, offset: -32400
1482            ),
1483        );
1484        check(
1485            "20150204143705567",
1486            &[
1487                num(Year), num(Month), num(Day), num(Hour), num(Minute), num(Second),
1488                internal_fixed(Nanosecond3NoDot)
1489            ],
1490            parsed!(
1491                year: 2015, month: 2, day: 4, hour_div_12: 1, hour_mod_12: 2, minute: 37,
1492                second: 5, nanosecond: 567000000
1493            ),
1494        );
1495        check(
1496            "Mon, 10 Jun 2013 09:32:37 GMT",
1497            &[
1498                fixed(Fixed::ShortWeekdayName), Literal(","), Space(" "), num(Day), Space(" "),
1499                fixed(Fixed::ShortMonthName), Space(" "), num(Year), Space(" "), num(Hour),
1500                Literal(":"), num(Minute), Literal(":"), num(Second), Space(" "), Literal("GMT")
1501            ],
1502            parsed!(
1503                year: 2013, month: 6, day: 10, weekday: Weekday::Mon,
1504                hour_div_12: 0, hour_mod_12: 9, minute: 32, second: 37
1505            ),
1506        );
1507        check(
1508            "🤠Mon, 10 Jun🤠2013 09:32:37  GMT🤠",
1509            &[
1510                Literal("🤠"), fixed(Fixed::ShortWeekdayName), Literal(","), Space(" "), num(Day),
1511                Space(" "), fixed(Fixed::ShortMonthName), Literal("🤠"), num(Year), Space(" "),
1512                num(Hour), Literal(":"), num(Minute), Literal(":"), num(Second), Space("  "),
1513                Literal("GMT"), Literal("🤠")
1514            ],
1515            parsed!(
1516                year: 2013, month: 6, day: 10, weekday: Weekday::Mon,
1517                hour_div_12: 0, hour_mod_12: 9, minute: 32, second: 37
1518            ),
1519        );
1520        check(
1521            "Sun Aug 02 13:39:15 CEST 2020",
1522            &[
1523                fixed(Fixed::ShortWeekdayName), Space(" "), fixed(Fixed::ShortMonthName),
1524                Space(" "), num(Day), Space(" "), num(Hour), Literal(":"), num(Minute),
1525                Literal(":"), num(Second), Space(" "), fixed(Fixed::TimezoneName), Space(" "),
1526                num(Year)
1527            ],
1528            parsed!(
1529                year: 2020, month: 8, day: 2, weekday: Weekday::Sun,
1530                hour_div_12: 1, hour_mod_12: 1, minute: 39, second: 15
1531            ),
1532        );
1533        check(
1534            "20060102150405",
1535            &[num(Year), num(Month), num(Day), num(Hour), num(Minute), num(Second)],
1536            parsed!(
1537                year: 2006, month: 1, day: 2, hour_div_12: 1, hour_mod_12: 3, minute: 4, second: 5
1538            ),
1539        );
1540        check(
1541            "3:14PM",
1542            &[num(Hour12), Literal(":"), num(Minute), fixed(Fixed::LowerAmPm)],
1543            parsed!(hour_div_12: 1, hour_mod_12: 3, minute: 14),
1544        );
1545        check(
1546            "12345678901234.56789",
1547            &[num(Timestamp), Literal("."), num(Nanosecond)],
1548            parsed!(nanosecond: 56_789, timestamp: 12_345_678_901_234),
1549        );
1550        check(
1551            "12345678901234.56789",
1552            &[num(Timestamp), fixed(Fixed::Nanosecond)],
1553            parsed!(nanosecond: 567_890_000, timestamp: 12_345_678_901_234),
1554        );
1555
1556        // docstring examples from `impl str::FromStr`
1557        check(
1558            "2000-01-02T03:04:05Z",
1559            &[
1560                num(Year), Literal("-"), num(Month), Literal("-"), num(Day), Literal("T"),
1561                num(Hour), Literal(":"), num(Minute), Literal(":"), num(Second),
1562                internal_fixed(TimezoneOffsetPermissive)
1563            ],
1564            parsed!(
1565                year: 2000, month: 1, day: 2, hour_div_12: 0, hour_mod_12: 3, minute: 4, second: 5,
1566                offset: 0
1567            ),
1568        );
1569        check(
1570            "2000-01-02 03:04:05Z",
1571            &[
1572                num(Year), Literal("-"), num(Month), Literal("-"), num(Day), Space(" "),
1573                num(Hour), Literal(":"), num(Minute), Literal(":"), num(Second),
1574                internal_fixed(TimezoneOffsetPermissive)
1575            ],
1576            parsed!(
1577                year: 2000, month: 1, day: 2, hour_div_12: 0, hour_mod_12: 3, minute: 4, second: 5,
1578                offset: 0
1579            ),
1580        );
1581    }
1582
1583    #[track_caller]
1584    fn parses(s: &str, items: &[Item]) {
1585        let mut parsed = Parsed::new();
1586        assert!(parse(&mut parsed, s, items.iter()).is_ok());
1587    }
1588
1589    #[track_caller]
1590    fn check(s: &str, items: &[Item], expected: ParseResult<Parsed>) {
1591        let mut parsed = Parsed::new();
1592        let result = parse(&mut parsed, s, items.iter());
1593        let parsed = result.map(|_| parsed);
1594        assert_eq!(parsed, expected);
1595    }
1596
1597    #[test]
1598    fn test_rfc2822() {
1599        let ymd_hmsn = |y, m, d, h, n, s, nano, off| {
1600            FixedOffset::east_opt(off * 60 * 60)
1601                .unwrap()
1602                .with_ymd_and_hms(y, m, d, h, n, s)
1603                .unwrap()
1604                .with_nanosecond(nano)
1605                .unwrap()
1606        };
1607
1608        // Test data - (input, Ok(expected result) or Err(error code))
1609        let testdates = [
1610            ("Tue, 20 Jan 2015 17:35:20 -0800", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -8))), // normal case
1611            ("Fri,  2 Jan 2015 17:35:20 -0800", Ok(ymd_hmsn(2015, 1, 2, 17, 35, 20, 0, -8))), // folding whitespace
1612            ("Fri, 02 Jan 2015 17:35:20 -0800", Ok(ymd_hmsn(2015, 1, 2, 17, 35, 20, 0, -8))), // leading zero
1613            ("Tue, 20 Jan 2015 17:35:20 -0800 (UTC)", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -8))), // trailing comment
1614            (
1615                r"Tue, 20 Jan 2015 17:35:20 -0800 ( (UTC ) (\( (a)\(( \t ) ) \\( \) ))",
1616                Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -8)),
1617            ), // complex trailing comment
1618            (r"Tue, 20 Jan 2015 17:35:20 -0800 (UTC\)", Err(TOO_LONG)), // incorrect comment, not enough closing parentheses
1619            (
1620                "Tue, 20 Jan 2015 17:35:20 -0800 (UTC)\t \r\n(Anothercomment)",
1621                Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -8)),
1622            ), // multiple comments
1623            ("Tue, 20 Jan 2015 17:35:20 -0800 (UTC) ", Err(TOO_LONG)), // trailing whitespace after comment
1624            ("20 Jan 2015 17:35:20 -0800", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -8))), // no day of week
1625            ("20 JAN 2015 17:35:20 -0800", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -8))), // upper case month
1626            ("Tue, 20 Jan 2015 17:35 -0800", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 0, 0, -8))), // no second
1627            ("11 Sep 2001 09:45:00 +0000", Ok(ymd_hmsn(2001, 9, 11, 9, 45, 0, 0, 0))),
1628            ("11 Sep 2001 09:45:00 EST", Ok(ymd_hmsn(2001, 9, 11, 9, 45, 0, 0, -5))),
1629            ("11 Sep 2001 09:45:00 GMT", Ok(ymd_hmsn(2001, 9, 11, 9, 45, 0, 0, 0))),
1630            ("30 Feb 2015 17:35:20 -0800", Err(OUT_OF_RANGE)), // bad day of month
1631            ("Tue, 20 Jan 2015", Err(TOO_SHORT)),              // omitted fields
1632            ("Tue, 20 Avr 2015 17:35:20 -0800", Err(INVALID)), // bad month name
1633            ("Tue, 20 Jan 2015 25:35:20 -0800", Err(OUT_OF_RANGE)), // bad hour
1634            ("Tue, 20 Jan 2015 7:35:20 -0800", Err(INVALID)),  // bad # of digits in hour
1635            ("Tue, 20 Jan 2015 17:65:20 -0800", Err(OUT_OF_RANGE)), // bad minute
1636            ("Tue, 20 Jan 2015 17:35:90 -0800", Err(OUT_OF_RANGE)), // bad second
1637            ("Tue, 20 Jan 2015 17:35:20 -0890", Err(OUT_OF_RANGE)), // bad offset
1638            ("6 Jun 1944 04:00:00Z", Err(INVALID)),            // bad offset (zulu not allowed)
1639            // named timezones that have specific timezone offsets
1640            // see https://www.rfc-editor.org/rfc/rfc2822#section-4.3
1641            ("Tue, 20 Jan 2015 17:35:20 GMT", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, 0))),
1642            ("Tue, 20 Jan 2015 17:35:20 UT", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, 0))),
1643            ("Tue, 20 Jan 2015 17:35:20 ut", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, 0))),
1644            ("Tue, 20 Jan 2015 17:35:20 EDT", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -4))),
1645            ("Tue, 20 Jan 2015 17:35:20 EST", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -5))),
1646            ("Tue, 20 Jan 2015 17:35:20 CDT", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -5))),
1647            ("Tue, 20 Jan 2015 17:35:20 CST", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -6))),
1648            ("Tue, 20 Jan 2015 17:35:20 MDT", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -6))),
1649            ("Tue, 20 Jan 2015 17:35:20 MST", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -7))),
1650            ("Tue, 20 Jan 2015 17:35:20 PDT", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -7))),
1651            ("Tue, 20 Jan 2015 17:35:20 PST", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -8))),
1652            ("Tue, 20 Jan 2015 17:35:20 pst", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -8))),
1653            // named single-letter military timezones must fallback to +0000
1654            ("Tue, 20 Jan 2015 17:35:20 Z", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, 0))),
1655            ("Tue, 20 Jan 2015 17:35:20 A", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, 0))),
1656            ("Tue, 20 Jan 2015 17:35:20 a", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, 0))),
1657            ("Tue, 20 Jan 2015 17:35:20 K", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, 0))),
1658            ("Tue, 20 Jan 2015 17:35:20 k", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, 0))),
1659            // named single-letter timezone "J" is specifically not valid
1660            ("Tue, 20 Jan 2015 17:35:20 J", Err(INVALID)),
1661            ("Tue, 20 Jan 2015 17:35:20 -0890", Err(OUT_OF_RANGE)), // bad offset minutes
1662            ("Tue, 20 Jan 2015 17:35:20Z", Err(INVALID)),           // bad offset: zulu not allowed
1663            ("Tue, 20 Jan 2015 17:35:20 Zulu", Err(INVALID)),       // bad offset: zulu not allowed
1664            ("Tue, 20 Jan 2015 17:35:20 ZULU", Err(INVALID)),       // bad offset: zulu not allowed
1665            ("Tue, 20 Jan 2015 17:35:20 −0800", Err(INVALID)), // bad offset: timezone offset using MINUS SIGN (U+2212), not specified for RFC 2822
1666            ("Tue, 20 Jan 2015 17:35:20 0800", Err(INVALID)),  // missing offset sign
1667            ("Tue, 20 Jan 2015 17:35:20 HAS", Err(INVALID)),   // bad named timezone
1668            ("Tue, 20 Jan 2015😈17:35:20 -0800", Err(INVALID)), // bad character!
1669        ];
1670
1671        fn rfc2822_to_datetime(date: &str) -> ParseResult<DateTime<FixedOffset>> {
1672            let mut parsed = Parsed::new();
1673            parse(&mut parsed, date, [Item::Fixed(Fixed::RFC2822)].iter())?;
1674            parsed.to_datetime()
1675        }
1676
1677        // Test against test data above
1678        for &(date, checkdate) in testdates.iter() {
1679            #[cfg(feature = "std")]
1680            eprintln!("Test input: {:?}\n    Expect: {:?}", date, checkdate);
1681            let dt = rfc2822_to_datetime(date); // parse a date
1682            if dt != checkdate {
1683                // check for expected result
1684                panic!(
1685                    "Date conversion failed for {}\nReceived: {:?}\nExpected: {:?}",
1686                    date, dt, checkdate
1687                );
1688            }
1689        }
1690    }
1691
1692    #[test]
1693    fn parse_rfc850() {
1694        static RFC850_FMT: &str = "%A, %d-%b-%y %T GMT";
1695
1696        let dt = Utc.with_ymd_and_hms(1994, 11, 6, 8, 49, 37).unwrap();
1697
1698        // Check that the format is what we expect
1699        #[cfg(feature = "alloc")]
1700        assert_eq!(dt.format(RFC850_FMT).to_string(), "Sunday, 06-Nov-94 08:49:37 GMT");
1701
1702        // Check that it parses correctly
1703        assert_eq!(
1704            NaiveDateTime::parse_from_str("Sunday, 06-Nov-94 08:49:37 GMT", RFC850_FMT),
1705            Ok(dt.naive_utc())
1706        );
1707
1708        // Check that the rest of the weekdays parse correctly (this test originally failed because
1709        // Sunday parsed incorrectly).
1710        let testdates = [
1711            (
1712                Utc.with_ymd_and_hms(1994, 11, 7, 8, 49, 37).unwrap(),
1713                "Monday, 07-Nov-94 08:49:37 GMT",
1714            ),
1715            (
1716                Utc.with_ymd_and_hms(1994, 11, 8, 8, 49, 37).unwrap(),
1717                "Tuesday, 08-Nov-94 08:49:37 GMT",
1718            ),
1719            (
1720                Utc.with_ymd_and_hms(1994, 11, 9, 8, 49, 37).unwrap(),
1721                "Wednesday, 09-Nov-94 08:49:37 GMT",
1722            ),
1723            (
1724                Utc.with_ymd_and_hms(1994, 11, 10, 8, 49, 37).unwrap(),
1725                "Thursday, 10-Nov-94 08:49:37 GMT",
1726            ),
1727            (
1728                Utc.with_ymd_and_hms(1994, 11, 11, 8, 49, 37).unwrap(),
1729                "Friday, 11-Nov-94 08:49:37 GMT",
1730            ),
1731            (
1732                Utc.with_ymd_and_hms(1994, 11, 12, 8, 49, 37).unwrap(),
1733                "Saturday, 12-Nov-94 08:49:37 GMT",
1734            ),
1735        ];
1736
1737        for val in &testdates {
1738            assert_eq!(NaiveDateTime::parse_from_str(val.1, RFC850_FMT), Ok(val.0.naive_utc()));
1739        }
1740
1741        let test_dates_fail = [
1742            "Saturday, 12-Nov-94 08:49:37",
1743            "Saturday, 12-Nov-94 08:49:37 Z",
1744            "Saturday, 12-Nov-94 08:49:37 GMTTTT",
1745            "Saturday, 12-Nov-94 08:49:37 gmt",
1746            "Saturday, 12-Nov-94 08:49:37 +08:00",
1747            "Caturday, 12-Nov-94 08:49:37 GMT",
1748            "Saturday, 99-Nov-94 08:49:37 GMT",
1749            "Saturday, 12-Nov-2000 08:49:37 GMT",
1750            "Saturday, 12-Mop-94 08:49:37 GMT",
1751            "Saturday, 12-Nov-94 28:49:37 GMT",
1752            "Saturday, 12-Nov-94 08:99:37 GMT",
1753            "Saturday, 12-Nov-94 08:49:99 GMT",
1754        ];
1755
1756        for val in &test_dates_fail {
1757            assert!(NaiveDateTime::parse_from_str(val, RFC850_FMT).is_err());
1758        }
1759    }
1760
1761    #[test]
1762    fn test_rfc3339() {
1763        let ymd_hmsn = |y, m, d, h, n, s, nano, off| {
1764            FixedOffset::east_opt(off * 60 * 60)
1765                .unwrap()
1766                .with_ymd_and_hms(y, m, d, h, n, s)
1767                .unwrap()
1768                .with_nanosecond(nano)
1769                .unwrap()
1770        };
1771
1772        // Test data - (input, Ok(expected result) or Err(error code))
1773        let testdates = [
1774            ("2015-01-20T17:35:20-08:00", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -8))), // normal case
1775            ("2015-01-20T17:35:20−08:00", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -8))), // normal case with MINUS SIGN (U+2212)
1776            ("1944-06-06T04:04:00Z", Ok(ymd_hmsn(1944, 6, 6, 4, 4, 0, 0, 0))),           // D-day
1777            ("2001-09-11T09:45:00-08:00", Ok(ymd_hmsn(2001, 9, 11, 9, 45, 0, 0, -8))),
1778            ("2015-01-20T17:35:20.001-08:00", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 1_000_000, -8))),
1779            ("2015-01-20T17:35:20.001−08:00", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 1_000_000, -8))), // with MINUS SIGN (U+2212)
1780            ("2015-01-20T17:35:20.000031-08:00", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 31_000, -8))),
1781            ("2015-01-20T17:35:20.000000004-08:00", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 4, -8))),
1782            ("2015-01-20T17:35:20.000000004−08:00", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 4, -8))), // with MINUS SIGN (U+2212)
1783            (
1784                "2015-01-20T17:35:20.000000000452-08:00",
1785                Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -8)),
1786            ), // too small
1787            (
1788                "2015-01-20T17:35:20.000000000452−08:00",
1789                Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -8)),
1790            ), // too small with MINUS SIGN (U+2212)
1791            ("2015-01-20 17:35:20-08:00", Ok(ymd_hmsn(2015, 1, 20, 17, 35, 20, 0, -8))), // without 'T'
1792            ("2015/01/20T17:35:20.001-08:00", Err(INVALID)), // wrong separator char YMD
1793            ("2015-01-20T17-35-20.001-08:00", Err(INVALID)), // wrong separator char HMS
1794            ("-01-20T17:35:20-08:00", Err(INVALID)),         // missing year
1795            ("99-01-20T17:35:20-08:00", Err(INVALID)),       // bad year format
1796            ("99999-01-20T17:35:20-08:00", Err(INVALID)),    // bad year value
1797            ("-2000-01-20T17:35:20-08:00", Err(INVALID)),    // bad year value
1798            ("2015-02-30T17:35:20-08:00", Err(OUT_OF_RANGE)), // bad day of month value
1799            ("2015-01-20T25:35:20-08:00", Err(OUT_OF_RANGE)), // bad hour value
1800            ("2015-01-20T17:65:20-08:00", Err(OUT_OF_RANGE)), // bad minute value
1801            ("2015-01-20T17:35:90-08:00", Err(OUT_OF_RANGE)), // bad second value
1802            ("2015-01-20T17:35:20-24:00", Err(OUT_OF_RANGE)), // bad offset value
1803            ("15-01-20T17:35:20-08:00", Err(INVALID)),       // bad year format
1804            ("15-01-20T17:35:20-08:00:00", Err(INVALID)),    // bad year format, bad offset format
1805            ("2015-01-20T17:35:2008:00", Err(INVALID)),      // missing offset sign
1806            ("2015-01-20T17:35:20 08:00", Err(INVALID)),     // missing offset sign
1807            ("2015-01-20T17:35:20Zulu", Err(TOO_LONG)),      // bad offset format
1808            ("2015-01-20T17:35:20 Zulu", Err(INVALID)),      // bad offset format
1809            ("2015-01-20T17:35:20GMT", Err(INVALID)),        // bad offset format
1810            ("2015-01-20T17:35:20 GMT", Err(INVALID)),       // bad offset format
1811            ("2015-01-20T17:35:20+GMT", Err(INVALID)),       // bad offset format
1812            ("2015-01-20T17:35:20++08:00", Err(INVALID)),    // bad offset format
1813            ("2015-01-20T17:35:20--08:00", Err(INVALID)),    // bad offset format
1814            ("2015-01-20T17:35:20−−08:00", Err(INVALID)), // bad offset format with MINUS SIGN (U+2212)
1815            ("2015-01-20T17:35:20±08:00", Err(INVALID)),  // bad offset sign
1816            ("2015-01-20T17:35:20-08-00", Err(INVALID)),  // bad offset separator
1817            ("2015-01-20T17:35:20-08;00", Err(INVALID)),  // bad offset separator
1818            ("2015-01-20T17:35:20-0800", Err(INVALID)),   // bad offset separator
1819            ("2015-01-20T17:35:20-08:0", Err(TOO_SHORT)), // bad offset minutes
1820            ("2015-01-20T17:35:20-08:AA", Err(INVALID)),  // bad offset minutes
1821            ("2015-01-20T17:35:20-08:ZZ", Err(INVALID)),  // bad offset minutes
1822            ("2015-01-20T17:35:20.001-08 : 00", Err(INVALID)), // bad offset separator
1823            ("2015-01-20T17:35:20-08:00:00", Err(TOO_LONG)), // bad offset format
1824            ("2015-01-20T17:35:20+08:", Err(TOO_SHORT)),  // bad offset format
1825            ("2015-01-20T17:35:20-08:", Err(TOO_SHORT)),  // bad offset format
1826            ("2015-01-20T17:35:20−08:", Err(TOO_SHORT)), // bad offset format with MINUS SIGN (U+2212)
1827            ("2015-01-20T17:35:20-08", Err(TOO_SHORT)),  // bad offset format
1828            ("2015-01-20T", Err(TOO_SHORT)),             // missing HMS
1829            ("2015-01-20T00:00:1", Err(TOO_SHORT)),      // missing complete S
1830            ("2015-01-20T00:00:1-08:00", Err(INVALID)),  // missing complete S
1831        ];
1832
1833        // Test against test data above
1834        for &(date, checkdate) in testdates.iter() {
1835            let dt = DateTime::<FixedOffset>::parse_from_rfc3339(date);
1836            if dt != checkdate {
1837                // check for expected result
1838                panic!(
1839                    "Date conversion failed for {}\nReceived: {:?}\nExpected: {:?}",
1840                    date, dt, checkdate
1841                );
1842            }
1843        }
1844    }
1845
1846    #[test]
1847    fn test_issue_1010() {
1848        let dt = crate::NaiveDateTime::parse_from_str(
1849            "\u{c}SUN\u{e}\u{3000}\0m@J\u{3000}\0\u{3000}\0m\u{c}!\u{c}\u{b}\u{c}\u{c}\u{c}\u{c}%A\u{c}\u{b}\0SU\u{c}\u{c}",
1850            "\u{c}\u{c}%A\u{c}\u{b}\0SUN\u{c}\u{c}\u{c}SUNN\u{c}\u{c}\u{c}SUN\u{c}\u{c}!\u{c}\u{b}\u{c}\u{c}\u{c}\u{c}%A\u{c}\u{b}%a",
1851        );
1852        assert_eq!(dt, Err(ParseError(ParseErrorKind::Invalid)));
1853    }
1854}