1use crate::{
2 Error, Timestamp,
3 civil::Weekday,
4 error::{
5 ErrorContext,
6 fmt::strtime::{Error as E, ParseError as PE},
7 util::ParseIntError,
8 },
9 fmt::{
10 Parsed, offset,
11 strtime::{BrokenDownTime, Extension, Flag, Meridiem},
12 },
13 util::{b, parse},
14};
15
16pub(super) struct Parser<'f, 'i, 't> {
17 pub(super) fmt: &'f [u8],
18 pub(super) inp: &'i [u8],
19 pub(super) tm: &'t mut BrokenDownTime,
20}
21
22impl<'f, 'i, 't> Parser<'f, 'i, 't> {
23 pub(super) fn parse(&mut self) -> Result<(), Error> {
24 let failc =
25 |directive, colons| E::DirectiveFailure { directive, colons };
26 let fail = |directive| failc(directive, 0);
27
28 while !self.fmt.is_empty() {
29 if self.f() != b'%' {
30 self.parse_literal()?;
31 continue;
32 }
33 if !self.bump_fmt() {
34 return Err(Error::from(E::UnexpectedEndAfterPercent));
35 }
36 if self.inp.is_empty() && self.f() != b'.' {
39 return Err(Error::from(PE::ExpectedNonEmpty {
40 directive: self.f(),
41 }));
42 }
43 let ext = self.parse_extension()?;
45 match self.f() {
46 b'%' => self.parse_percent().context(fail(b'%'))?,
47 b'A' => self.parse_weekday_full().context(fail(b'A'))?,
48 b'a' => self.parse_weekday_abbrev().context(fail(b'a'))?,
49 b'B' => self.parse_month_name_full().context(fail(b'B'))?,
50 b'b' => self.parse_month_name_abbrev().context(fail(b'b'))?,
51 b'C' => self.parse_century(ext).context(fail(b'C'))?,
52 b'D' => self.parse_american_date().context(fail(b'D'))?,
53 b'd' => self.parse_day(ext).context(fail(b'd'))?,
54 b'e' => self.parse_day(ext).context(fail(b'e'))?,
55 b'F' => self.parse_iso_date().context(fail(b'F'))?,
56 b'f' => self.parse_fractional(ext).context(fail(b'f'))?,
57 b'G' => self.parse_iso_week_year(ext).context(fail(b'G'))?,
58 b'g' => self.parse_iso_week_year2(ext).context(fail(b'g'))?,
59 b'H' => self.parse_hour24(ext).context(fail(b'H'))?,
60 b'h' => self.parse_month_name_abbrev().context(fail(b'h'))?,
61 b'I' => self.parse_hour12(ext).context(fail(b'I'))?,
62 b'j' => self.parse_day_of_year(ext).context(fail(b'j'))?,
63 b'k' => self.parse_hour24(ext).context(fail(b'k'))?,
64 b'l' => self.parse_hour12(ext).context(fail(b'l'))?,
65 b'M' => self.parse_minute(ext).context(fail(b'M'))?,
66 b'm' => self.parse_month(ext).context(fail(b'm'))?,
67 b'N' => self.parse_fractional(ext).context(fail(b'N'))?,
68 b'n' => self.parse_whitespace().context(fail(b'n'))?,
69 b'P' => self.parse_ampm().context(fail(b'P'))?,
70 b'p' => self.parse_ampm().context(fail(b'p'))?,
71 b'Q' => match ext.colons {
72 0 => self.parse_iana_nocolon().context(fail(b'Q'))?,
73 1 => self.parse_iana_colon().context(failc(b'Q', 1))?,
74 _ => return Err(E::ColonCount { directive: b'Q' }.into()),
75 },
76 b'R' => self.parse_clock_nosecs().context(fail(b'R'))?,
77 b'S' => self.parse_second(ext).context(fail(b'S'))?,
78 b's' => self.parse_timestamp(ext).context(fail(b's'))?,
79 b'T' => self.parse_clock_secs().context(fail(b'T'))?,
80 b't' => self.parse_whitespace().context(fail(b't'))?,
81 b'U' => self.parse_week_sun(ext).context(fail(b'U'))?,
82 b'u' => self.parse_weekday_mon(ext).context(fail(b'u'))?,
83 b'V' => self.parse_week_iso(ext).context(fail(b'V'))?,
84 b'W' => self.parse_week_mon(ext).context(fail(b'W'))?,
85 b'w' => self.parse_weekday_sun(ext).context(fail(b'w'))?,
86 b'Y' => self.parse_year(ext).context(fail(b'Y'))?,
87 b'y' => self.parse_year2(ext).context(fail(b'y'))?,
88 b'z' => match ext.colons {
89 0 => self.parse_offset_nocolon().context(fail(b'z'))?,
90 1 => self.parse_offset_colon().context(failc(b'z', 1))?,
91 2 => self.parse_offset_colon2().context(failc(b'z', 2))?,
92 3 => self.parse_offset_colon3().context(failc(b'z', 3))?,
93 _ => return Err(E::ColonCount { directive: b'z' }.into()),
94 },
95 b'c' => {
96 return Err(Error::from(PE::NotAllowedLocaleDateAndTime));
97 }
98 b'r' => {
99 return Err(Error::from(
100 PE::NotAllowedLocaleTwelveHourClockTime,
101 ));
102 }
103 b'X' => {
104 return Err(Error::from(PE::NotAllowedLocaleClockTime));
105 }
106 b'x' => return Err(Error::from(PE::NotAllowedLocaleDate)),
107 b'Z' => {
108 return Err(Error::from(
109 PE::NotAllowedTimeZoneAbbreviation,
110 ));
111 }
112 b'.' => {
113 if !self.bump_fmt() {
114 return Err(E::UnexpectedEndAfterDot.into());
115 }
116 let (width, fmt) = Extension::parse_width(self.fmt)?;
119 let ext = Extension { width, ..ext };
120 self.fmt = fmt;
121 match self.f() {
122 b'f' => self.parse_dot_fractional(ext).context(
123 E::DirectiveFailureDot { directive: b'f' },
124 )?,
125 unk => {
126 return Err(Error::from(
127 E::UnknownDirectiveAfterDot { directive: unk },
128 ));
129 }
130 }
131 }
132 unk => {
133 return Err(Error::from(E::UnknownDirective {
134 directive: unk,
135 }));
136 }
137 }
138 }
139 Ok(())
140 }
141
142 fn f(&self) -> u8 {
148 self.fmt[0]
149 }
150
151 fn i(&self) -> u8 {
157 self.inp[0]
158 }
159
160 fn bump_fmt(&mut self) -> bool {
165 self.fmt = &self.fmt[1..];
166 !self.fmt.is_empty()
167 }
168
169 fn bump_input(&mut self) -> bool {
174 self.inp = &self.inp[1..];
175 !self.inp.is_empty()
176 }
177
178 fn parse_extension(&mut self) -> Result<Extension, Error> {
182 if self.f().is_ascii_alphabetic() {
183 return Ok(Extension { flag: None, width: None, colons: 0 });
184 }
185 let (flag, fmt) = Extension::parse_flag(self.fmt)?;
186 let (width, fmt) = Extension::parse_width(fmt)?;
187 let (colons, fmt) = Extension::parse_colons(fmt)?;
188 self.fmt = fmt;
189 Ok(Extension { flag, width, colons })
190 }
191
192 fn parse_literal(&mut self) -> Result<(), Error> {
204 if self.f().is_ascii_whitespace() {
205 if !self.inp.is_empty() {
206 while self.i().is_ascii_whitespace() && self.bump_input() {}
207 }
208 } else if self.inp.is_empty() {
209 return Err(Error::from(PE::ExpectedMatchLiteralEndOfInput {
210 expected: self.f(),
211 }));
212 } else if self.f() != self.i() {
213 return Err(Error::from(PE::ExpectedMatchLiteralByte {
214 expected: self.fmt[0],
215 got: self.i(),
216 }));
217 } else {
218 self.bump_input();
219 }
220 self.bump_fmt();
221 Ok(())
222 }
223
224 fn parse_whitespace(&mut self) -> Result<(), Error> {
228 if !self.inp.is_empty() {
229 while self.i().is_ascii_whitespace() && self.bump_input() {}
230 }
231 self.bump_fmt();
232 Ok(())
233 }
234
235 fn parse_percent(&mut self) -> Result<(), Error> {
237 if self.i() != b'%' {
238 return Err(Error::from(PE::ExpectedMatchLiteralByte {
239 expected: b'%',
240 got: self.i(),
241 }));
242 }
243 self.bump_fmt();
244 self.bump_input();
245 Ok(())
246 }
247
248 fn parse_american_date(&mut self) -> Result<(), Error> {
250 let mut p = Parser { fmt: b"%m/%d/%y", inp: self.inp, tm: self.tm };
251 p.parse()?;
252 self.inp = p.inp;
253 self.bump_fmt();
254 Ok(())
255 }
256
257 fn parse_ampm(&mut self) -> Result<(), Error> {
263 let (index, inp) = parse_ampm(self.inp)?;
264 self.inp = inp;
265
266 self.tm.set_meridiem(Some(match index {
267 0 => Meridiem::AM,
268 1 => Meridiem::PM,
269 _ => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("unknown AM/PM index")));
}unreachable!("unknown AM/PM index"),
271 }));
272 self.bump_fmt();
273 Ok(())
274 }
275
276 fn parse_clock_secs(&mut self) -> Result<(), Error> {
278 let mut p = Parser { fmt: b"%H:%M:%S", inp: self.inp, tm: self.tm };
279 p.parse()?;
280 self.inp = p.inp;
281 self.bump_fmt();
282 Ok(())
283 }
284
285 fn parse_clock_nosecs(&mut self) -> Result<(), Error> {
287 let mut p = Parser { fmt: b"%H:%M", inp: self.inp, tm: self.tm };
288 p.parse()?;
289 self.inp = p.inp;
290 self.bump_fmt();
291 Ok(())
292 }
293
294 fn parse_day(&mut self, ext: Extension) -> Result<(), Error> {
298 let (day, inp) = ext
299 .parse_number(2, Flag::PadZero, self.inp)
300 .context(PE::ParseDay)?;
301 self.inp = inp;
302
303 self.tm.day = Some(b::Day::check(day).context(PE::ParseDay)?);
304 self.bump_fmt();
305 Ok(())
306 }
307
308 fn parse_day_of_year(&mut self, ext: Extension) -> Result<(), Error> {
312 let (day, inp) = ext
313 .parse_number(3, Flag::PadZero, self.inp)
314 .context(PE::ParseDayOfYear)?;
315 self.inp = inp;
316
317 self.tm.day_of_year =
318 Some(b::DayOfYear::check(day).context(PE::ParseDayOfYear)?);
319 self.bump_fmt();
320 Ok(())
321 }
322
323 fn parse_hour24(&mut self, ext: Extension) -> Result<(), Error> {
325 let (hour, inp) = ext
326 .parse_number(2, Flag::PadZero, self.inp)
327 .context(PE::ParseHour)?;
328 self.inp = inp;
329
330 let hour = b::Hour::check(hour).context(PE::ParseHour)?;
331 self.tm.set_hour(Some(hour)).unwrap();
333 self.bump_fmt();
334 Ok(())
335 }
336
337 fn parse_hour12(&mut self, ext: Extension) -> Result<(), Error> {
339 let (hour, inp) = ext
340 .parse_number(2, Flag::PadZero, self.inp)
341 .context(PE::ParseHour)?;
342 self.inp = inp;
343
344 let hour = b::Hour12::check(hour).context(PE::ParseHour)?;
345 self.tm.set_hour(Some(hour)).unwrap();
347 self.bump_fmt();
348 Ok(())
349 }
350
351 fn parse_iso_date(&mut self) -> Result<(), Error> {
353 let mut p = Parser { fmt: b"%Y-%m-%d", inp: self.inp, tm: self.tm };
354 p.parse()?;
355 self.inp = p.inp;
356 self.bump_fmt();
357 Ok(())
358 }
359
360 fn parse_minute(&mut self, ext: Extension) -> Result<(), Error> {
362 let (minute, inp) = ext
363 .parse_number(2, Flag::PadZero, self.inp)
364 .context(PE::ParseMinute)?;
365 self.inp = inp;
366
367 self.tm.minute =
368 Some(b::Minute::check(minute).context(PE::ParseMinute)?);
369 self.bump_fmt();
370 Ok(())
371 }
372
373 fn parse_iana_nocolon(&mut self) -> Result<(), Error> {
376 #[cfg(not(feature = "alloc"))]
377 {
378 Err(Error::from(PE::NotAllowedAlloc {
379 directive: b'Q',
380 colons: 0,
381 }))
382 }
383 #[cfg(feature = "alloc")]
384 {
385 use alloc::string::ToString;
386
387 if !self.inp.is_empty() && #[allow(non_exhaustive_omitted_patterns)] match self.inp[0] {
b'+' | b'-' => true,
_ => false,
}matches!(self.inp[0], b'+' | b'-') {
388 return self.parse_offset_nocolon();
389 }
390 let (iana, inp) = parse_iana(self.inp)?;
391 self.inp = inp;
392 self.tm.iana = Some(iana.to_string());
393 self.bump_fmt();
394 Ok(())
395 }
396 }
397
398 fn parse_iana_colon(&mut self) -> Result<(), Error> {
401 #[cfg(not(feature = "alloc"))]
402 {
403 Err(Error::from(PE::NotAllowedAlloc {
404 directive: b'Q',
405 colons: 1,
406 }))
407 }
408 #[cfg(feature = "alloc")]
409 {
410 use alloc::string::ToString;
411
412 if !self.inp.is_empty() && #[allow(non_exhaustive_omitted_patterns)] match self.inp[0] {
b'+' | b'-' => true,
_ => false,
}matches!(self.inp[0], b'+' | b'-') {
413 return self.parse_offset_colon();
414 }
415 let (iana, inp) = parse_iana(self.inp)?;
416 self.inp = inp;
417 self.tm.iana = Some(iana.to_string());
418 self.bump_fmt();
419 Ok(())
420 }
421 }
422
423 fn parse_offset_nocolon(&mut self) -> Result<(), Error> {
426 static PARSER: offset::Parser = offset::Parser::new()
427 .zulu(false)
428 .require_minute(true)
429 .subminute(true)
430 .subsecond(false)
431 .colon(offset::Colon::Absent);
432
433 let Parsed { value, input } = PARSER.parse(self.inp)?;
434 self.tm.offset = Some(value.to_offset()?);
435 self.inp = input;
436 self.bump_fmt();
437
438 Ok(())
439 }
440
441 fn parse_offset_colon(&mut self) -> Result<(), Error> {
444 static PARSER: offset::Parser = offset::Parser::new()
445 .zulu(false)
446 .require_minute(true)
447 .subminute(true)
448 .subsecond(false)
449 .colon(offset::Colon::Required);
450
451 let Parsed { value, input } = PARSER.parse(self.inp)?;
452 self.tm.offset = Some(value.to_offset()?);
453 self.inp = input;
454 self.bump_fmt();
455
456 Ok(())
457 }
458
459 fn parse_offset_colon2(&mut self) -> Result<(), Error> {
462 static PARSER: offset::Parser = offset::Parser::new()
463 .zulu(false)
464 .require_minute(true)
465 .require_second(true)
466 .subminute(true)
467 .subsecond(false)
468 .colon(offset::Colon::Required);
469
470 let Parsed { value, input } = PARSER.parse(self.inp)?;
471 self.tm.offset = Some(value.to_offset()?);
472 self.inp = input;
473 self.bump_fmt();
474
475 Ok(())
476 }
477
478 fn parse_offset_colon3(&mut self) -> Result<(), Error> {
482 static PARSER: offset::Parser = offset::Parser::new()
483 .zulu(false)
484 .require_minute(false)
485 .require_second(false)
486 .subminute(true)
487 .subsecond(false)
488 .colon(offset::Colon::Required);
489
490 let Parsed { value, input } = PARSER.parse(self.inp)?;
491 self.tm.offset = Some(value.to_offset()?);
492 self.inp = input;
493 self.bump_fmt();
494
495 Ok(())
496 }
497
498 fn parse_second(&mut self, ext: Extension) -> Result<(), Error> {
500 let (mut second, inp) = ext
501 .parse_number(2, Flag::PadZero, self.inp)
502 .context(PE::ParseSecond)?;
503 self.inp = inp;
504
505 if second == 60 {
509 second = 59;
510 }
511 self.tm.second =
512 Some(b::Second::check(second).context(PE::ParseSecond)?);
513 self.bump_fmt();
514 Ok(())
515 }
516
517 fn parse_timestamp(&mut self, ext: Extension) -> Result<(), Error> {
519 let (sign, inp) = parse_optional_sign(self.inp);
520 let (timestamp, inp) = ext
521 .parse_number(19, Flag::PadSpace, inp)
523 .context(PE::ParseTimestamp)?;
524 let timestamp =
528 timestamp.checked_mul(sign).ok_or(PE::ParseTimestamp)?;
529 let timestamp =
530 Timestamp::from_second(timestamp).context(PE::ParseTimestamp)?;
531 self.inp = inp;
532 self.tm.timestamp = Some(timestamp);
533
534 self.bump_fmt();
535 Ok(())
536 }
537
538 fn parse_fractional(&mut self, _ext: Extension) -> Result<(), Error> {
546 let mkdigits = parse::slicer(self.inp);
547 while mkdigits(self.inp).len() < 9
548 && self.inp.first().map_or(false, u8::is_ascii_digit)
549 {
550 self.inp = &self.inp[1..];
551 }
552 let digits = mkdigits(self.inp);
553 if digits.is_empty() {
554 return Err(Error::from(PE::ExpectedFractionalDigit));
555 }
556 let nanoseconds =
560 parse::fraction(digits).context(PE::ParseFractionalSeconds)?;
561 self.tm.subsec = Some(
566 b::SubsecNanosecond::check(nanoseconds)
567 .context(PE::ParseFractionalSeconds)?,
568 );
569 self.bump_fmt();
570 Ok(())
571 }
572
573 fn parse_dot_fractional(&mut self, ext: Extension) -> Result<(), Error> {
577 if !self.inp.starts_with(b".") {
578 self.bump_fmt();
579 return Ok(());
580 }
581 self.inp = &self.inp[1..];
582 self.parse_fractional(ext)
583 }
584
585 fn parse_month(&mut self, ext: Extension) -> Result<(), Error> {
587 let (month, inp) = ext
588 .parse_number(2, Flag::PadZero, self.inp)
589 .context(PE::ParseMonth)?;
590 self.inp = inp;
591
592 self.tm.month = Some(b::Month::check(month).context(PE::ParseMonth)?);
593 self.bump_fmt();
594 Ok(())
595 }
596
597 fn parse_month_name_abbrev(&mut self) -> Result<(), Error> {
599 let (index, inp) = parse_month_name_abbrev(self.inp)?;
600 self.inp = inp;
601
602 self.tm.month = Some(index + 1);
604 self.bump_fmt();
605 Ok(())
606 }
607
608 fn parse_month_name_full(&mut self) -> Result<(), Error> {
610 static CHOICES: &'static [&'static [u8]] = &[
611 b"January",
612 b"February",
613 b"March",
614 b"April",
615 b"May",
616 b"June",
617 b"July",
618 b"August",
619 b"September",
620 b"October",
621 b"November",
622 b"December",
623 ];
624
625 let (index, inp) =
626 parse_choice(self.inp, CHOICES).context(PE::UnknownMonthName)?;
627 self.inp = inp;
628
629 self.tm.month = Some(index + 1);
631 self.bump_fmt();
632 Ok(())
633 }
634
635 fn parse_weekday_abbrev(&mut self) -> Result<(), Error> {
637 let (index, inp) = parse_weekday_abbrev(self.inp)?;
638 self.inp = inp;
639
640 let index = i8::try_from(index).unwrap();
642 self.tm.weekday =
643 Some(Weekday::from_sunday_zero_offset(index).unwrap());
644 self.bump_fmt();
645 Ok(())
646 }
647
648 fn parse_weekday_full(&mut self) -> Result<(), Error> {
650 static CHOICES: &'static [&'static [u8]] = &[
651 b"Sunday",
652 b"Monday",
653 b"Tuesday",
654 b"Wednesday",
655 b"Thursday",
656 b"Friday",
657 b"Saturday",
658 ];
659
660 let (index, inp) = parse_choice(self.inp, CHOICES)
661 .context(PE::UnknownWeekdayAbbreviation)?;
662 self.inp = inp;
663
664 let index = i8::try_from(index).unwrap();
666 self.tm.weekday =
667 Some(Weekday::from_sunday_zero_offset(index).unwrap());
668 self.bump_fmt();
669 Ok(())
670 }
671
672 fn parse_weekday_mon(&mut self, ext: Extension) -> Result<(), Error> {
675 let (weekday, inp) = ext
676 .parse_number(1, Flag::NoPad, self.inp)
677 .context(PE::ParseWeekdayNumber)?;
678 self.inp = inp;
679
680 let weekday =
681 i8::try_from(weekday).map_err(|_| PE::ParseWeekdayNumber)?;
682 let weekday = Weekday::from_monday_one_offset(weekday)
683 .context(PE::ParseWeekdayNumber)?;
684 self.tm.weekday = Some(weekday);
685 self.bump_fmt();
686 Ok(())
687 }
688
689 fn parse_weekday_sun(&mut self, ext: Extension) -> Result<(), Error> {
691 let (weekday, inp) = ext
692 .parse_number(1, Flag::NoPad, self.inp)
693 .context(PE::ParseWeekdayNumber)?;
694 self.inp = inp;
695
696 let weekday =
697 i8::try_from(weekday).map_err(|_| PE::ParseWeekdayNumber)?;
698 let weekday = Weekday::from_sunday_zero_offset(weekday)
699 .context(PE::ParseWeekdayNumber)?;
700 self.tm.weekday = Some(weekday);
701 self.bump_fmt();
702 Ok(())
703 }
704
705 fn parse_week_sun(&mut self, ext: Extension) -> Result<(), Error> {
708 let (week, inp) = ext
709 .parse_number(2, Flag::PadZero, self.inp)
710 .context(PE::ParseSundayWeekNumber)?;
711 self.inp = inp;
712
713 self.tm.week_sun =
714 Some(b::WeekNum::check(week).context(PE::ParseSundayWeekNumber)?);
715 self.bump_fmt();
716 Ok(())
717 }
718
719 fn parse_week_iso(&mut self, ext: Extension) -> Result<(), Error> {
721 let (week, inp) = ext
722 .parse_number(2, Flag::PadZero, self.inp)
723 .context(PE::ParseIsoWeekNumber)?;
724 self.inp = inp;
725
726 self.tm.iso_week =
727 Some(b::ISOWeek::check(week).context(PE::ParseIsoWeekNumber)?);
728 self.bump_fmt();
729 Ok(())
730 }
731
732 fn parse_week_mon(&mut self, ext: Extension) -> Result<(), Error> {
735 let (week, inp) = ext
736 .parse_number(2, Flag::PadZero, self.inp)
737 .context(PE::ParseMondayWeekNumber)?;
738 self.inp = inp;
739
740 self.tm.week_mon =
741 Some(b::WeekNum::check(week).context(PE::ParseMondayWeekNumber)?);
742 self.bump_fmt();
743 Ok(())
744 }
745
746 fn parse_year(&mut self, ext: Extension) -> Result<(), Error> {
748 let (sign, inp) = parse_optional_sign(self.inp);
749 let (year, inp) =
750 ext.parse_number(4, Flag::PadZero, inp).context(PE::ParseYear)?;
751 self.inp = inp;
752
753 let year = sign.checked_mul(year).unwrap();
756 self.tm.year = Some(b::Year::check(year).context(PE::ParseYear)?);
757 self.bump_fmt();
758 Ok(())
759 }
760
761 fn parse_year2(&mut self, ext: Extension) -> Result<(), Error> {
765 let (year, inp) = ext
766 .parse_number(2, Flag::PadZero, self.inp)
767 .context(PE::ParseYearTwoDigit)?;
768 self.inp = inp;
769
770 let mut year =
771 b::YearTwoDigit::check(year).context(PE::ParseYearTwoDigit)?;
772 if year <= 68 {
773 year += 2000;
774 } else {
775 year += 1900;
776 }
777 self.tm.year = Some(year);
778 self.bump_fmt();
779 Ok(())
780 }
781
782 fn parse_century(&mut self, ext: Extension) -> Result<(), Error> {
785 let (sign, inp) = parse_optional_sign(self.inp);
786 let (century, inp) =
787 ext.parse_number(2, Flag::NoPad, inp).context(PE::ParseCentury)?;
788 self.inp = inp;
789
790 let century =
791 i64::from(b::Century::check(century).context(PE::ParseCentury)?);
792 let century = sign.checked_mul(century).unwrap();
795 let year = century.checked_mul(100).unwrap();
798 self.tm.year = Some(b::Year::check(year).context(PE::ParseCentury)?);
800 self.bump_fmt();
801 Ok(())
802 }
803
804 fn parse_iso_week_year(&mut self, ext: Extension) -> Result<(), Error> {
806 let (sign, inp) = parse_optional_sign(self.inp);
807 let (year, inp) = ext
808 .parse_number(4, Flag::PadZero, inp)
809 .context(PE::ParseIsoWeekYear)?;
810 self.inp = inp;
811
812 let year = sign.checked_mul(year).unwrap();
815 self.tm.iso_week_year =
816 Some(b::ISOYear::check(year).context(PE::ParseIsoWeekYear)?);
817 self.bump_fmt();
818 Ok(())
819 }
820
821 fn parse_iso_week_year2(&mut self, ext: Extension) -> Result<(), Error> {
825 let (year, inp) = ext
826 .parse_number(2, Flag::PadZero, self.inp)
827 .context(PE::ParseIsoWeekYearTwoDigit)?;
828 self.inp = inp;
829
830 let mut year = b::YearTwoDigit::check(year)
831 .context(PE::ParseIsoWeekYearTwoDigit)?;
832 if year <= 68 {
833 year += 2000;
834 } else {
835 year += 1900;
836 }
837 self.tm.iso_week_year = Some(year);
838 self.bump_fmt();
839 Ok(())
840 }
841}
842
843impl Extension {
844 #[cfg_attr(feature = "perf-inline", inline(always))]
860 fn parse_number<'i>(
861 &self,
862 default_pad_width: usize,
863 default_flag: Flag,
864 mut inp: &'i [u8],
865 ) -> Result<(i64, &'i [u8]), Error> {
866 let flag = self.flag.unwrap_or(default_flag);
867 let zero_pad_width = match flag {
868 Flag::PadSpace | Flag::NoPad => 0,
869 _ => self.width.map(usize::from).unwrap_or(default_pad_width),
870 };
871 let max_digits = default_pad_width.max(zero_pad_width);
872
873 while inp.get(0).map_or(false, |b| b.is_ascii_whitespace()) {
875 inp = &inp[1..];
876 }
877 let mut digits = 0;
878 while digits < inp.len()
879 && digits < zero_pad_width
880 && inp[digits] == b'0'
881 {
882 digits += 1;
883 }
884 let mut n: i64 = 0;
885 while digits < inp.len()
886 && digits < max_digits
887 && inp[digits].is_ascii_digit()
888 {
889 let byte = inp[digits];
890 digits += 1;
891 let digit = i64::from(byte - b'0');
895 n = n
896 .checked_mul(10)
897 .and_then(|n| n.checked_add(digit))
898 .ok_or(ParseIntError::TooBig)?;
899 }
900 if digits == 0 {
901 return Err(Error::from(ParseIntError::NoDigitsFound));
902 }
903 Ok((n, &inp[digits..]))
904 }
905}
906
907#[cfg_attr(feature = "perf-inline", inline(always))]
912fn parse_optional_sign<'i>(input: &'i [u8]) -> (i64, &'i [u8]) {
913 if input.is_empty() {
914 (1, input)
915 } else if input[0] == b'-' {
916 (-1, &input[1..])
917 } else if input[0] == b'+' {
918 (1, &input[1..])
919 } else {
920 (1, input)
921 }
922}
923
924fn parse_choice<'i>(
935 input: &'i [u8],
936 choices: &'static [&'static [u8]],
937) -> Result<(i8, &'i [u8]), Error> {
938 if true {
if !(choices.len() < usize::from(i8::MAX.unsigned_abs())) {
::core::panicking::panic("assertion failed: choices.len() < usize::from(i8::MAX.unsigned_abs())")
};
};debug_assert!(choices.len() < usize::from(i8::MAX.unsigned_abs()));
939 for (i, choice) in choices.into_iter().enumerate() {
940 if input.len() < choice.len() {
941 continue;
942 }
943 let (candidate, input) = input.split_at(choice.len());
944 if candidate.eq_ignore_ascii_case(choice) {
945 return Ok((i8::try_from(i).unwrap(), input));
946 }
947 }
948 Err(Error::from(PE::ExpectedChoice { available: choices }))
949}
950
951#[cfg_attr(feature = "perf-inline", inline(always))]
956fn parse_ampm<'i>(input: &'i [u8]) -> Result<(usize, &'i [u8]), Error> {
957 if input.len() < 2 {
958 return Err(Error::from(PE::ExpectedAmPmTooShort));
959 }
960 let (x, input) = input.split_at(2);
961 let candidate = &[x[0].to_ascii_lowercase(), x[1].to_ascii_lowercase()];
962 let index = match candidate {
963 b"am" => 0,
964 b"pm" => 1,
965 _ => return Err(Error::from(PE::ExpectedAmPm)),
966 };
967 Ok((index, input))
968}
969
970#[cfg_attr(feature = "perf-inline", inline(always))]
975fn parse_weekday_abbrev<'i>(
976 input: &'i [u8],
977) -> Result<(usize, &'i [u8]), Error> {
978 if input.len() < 3 {
979 return Err(Error::from(PE::ExpectedWeekdayAbbreviationTooShort));
980 }
981 let (x, input) = input.split_at(3);
982 let candidate = &[
983 x[0].to_ascii_lowercase(),
984 x[1].to_ascii_lowercase(),
985 x[2].to_ascii_lowercase(),
986 ];
987 let index = match candidate {
988 b"sun" => 0,
989 b"mon" => 1,
990 b"tue" => 2,
991 b"wed" => 3,
992 b"thu" => 4,
993 b"fri" => 5,
994 b"sat" => 6,
995 _ => return Err(Error::from(PE::ExpectedWeekdayAbbreviation)),
996 };
997 Ok((index, input))
998}
999
1000#[cfg_attr(feature = "perf-inline", inline(always))]
1005fn parse_month_name_abbrev<'i>(
1006 input: &'i [u8],
1007) -> Result<(i8, &'i [u8]), Error> {
1008 if input.len() < 3 {
1009 return Err(Error::from(PE::ExpectedMonthAbbreviationTooShort));
1010 }
1011 let (x, input) = input.split_at(3);
1012 let candidate = &[
1013 x[0].to_ascii_lowercase(),
1014 x[1].to_ascii_lowercase(),
1015 x[2].to_ascii_lowercase(),
1016 ];
1017 let index = match candidate {
1018 b"jan" => 0,
1019 b"feb" => 1,
1020 b"mar" => 2,
1021 b"apr" => 3,
1022 b"may" => 4,
1023 b"jun" => 5,
1024 b"jul" => 6,
1025 b"aug" => 7,
1026 b"sep" => 8,
1027 b"oct" => 9,
1028 b"nov" => 10,
1029 b"dec" => 11,
1030 _ => return Err(Error::from(PE::ExpectedMonthAbbreviation)),
1031 };
1032 Ok((index, input))
1033}
1034
1035#[cfg_attr(feature = "perf-inline", inline(always))]
1036fn parse_iana<'i>(input: &'i [u8]) -> Result<(&'i str, &'i [u8]), Error> {
1037 let mkiana = parse::slicer(input);
1038 let (_, mut input) = parse_iana_component(input)?;
1039 while let Some(tail) = input.strip_prefix(b"/") {
1040 input = tail;
1041 let (_, unconsumed) = parse_iana_component(input)?;
1042 input = unconsumed;
1043 }
1044 let iana = core::str::from_utf8(mkiana(input)).expect("ASCII");
1049 Ok((iana, input))
1050}
1051
1052#[cfg_attr(feature = "perf-inline", inline(always))]
1056fn parse_iana_component<'i>(
1057 mut input: &'i [u8],
1058) -> Result<(&'i [u8], &'i [u8]), Error> {
1059 let mkname = parse::slicer(input);
1060 if input.is_empty() {
1061 return Err(Error::from(PE::ExpectedIanaTzEndOfInput));
1062 }
1063 if !#[allow(non_exhaustive_omitted_patterns)] match input[0] {
b'_' | b'.' | b'A'..=b'Z' | b'a'..=b'z' => true,
_ => false,
}matches!(input[0], b'_' | b'.' | b'A'..=b'Z' | b'a'..=b'z') {
1064 return Err(Error::from(PE::ExpectedIanaTz));
1065 }
1066 input = &input[1..];
1067
1068 let is_iana_char = |byte| {
1069 #[allow(non_exhaustive_omitted_patterns)] match byte {
b'_' | b'.' | b'+' | b'-' | b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' =>
true,
_ => false,
}matches!(
1070 byte,
1071 b'_' | b'.' | b'+' | b'-' | b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z',
1072 )
1073 };
1074 loop {
1075 let Some((&first, tail)) = input.split_first() else { break };
1076 if !is_iana_char(first) {
1077 break;
1078 }
1079 input = tail;
1080 }
1081 Ok((mkname(input), input))
1082}
1083
1084#[cfg(feature = "alloc")]
1085#[cfg(test)]
1086mod tests {
1087 use alloc::string::ToString;
1088
1089 use super::*;
1090
1091 #[test]
1092 fn ok_parse_zoned_datetime() {
1093 if crate::tz::db().is_definitively_empty() {
1094 return;
1095 }
1096
1097 let p = |fmt: &str, input: &str| {
1098 BrokenDownTime::parse_mono(fmt.as_bytes(), input.as_bytes())
1099 .unwrap()
1100 .to_zoned_datetime()
1101 .unwrap()
1102 };
1103
1104 insta::assert_debug_snapshot!(
1105 p("%h %d, %Y %H:%M:%S %z", "Apr 1, 2022 20:46:15 -0400"),
1106 @"2022-04-01T20:46:15-04:00[-04:00]",
1107 );
1108 insta::assert_debug_snapshot!(
1109 p("%h %d, %Y %H:%M:%S %Q", "Apr 1, 2022 20:46:15 -0400"),
1110 @"2022-04-01T20:46:15-04:00[-04:00]",
1111 );
1112 insta::assert_debug_snapshot!(
1113 p("%h %d, %Y %H:%M:%S [%Q]", "Apr 1, 2022 20:46:15 [America/New_York]"),
1114 @"2022-04-01T20:46:15-04:00[America/New_York]",
1115 );
1116 insta::assert_debug_snapshot!(
1117 p("%h %d, %Y %H:%M:%S %Q", "Apr 1, 2022 20:46:15 America/New_York"),
1118 @"2022-04-01T20:46:15-04:00[America/New_York]",
1119 );
1120 insta::assert_debug_snapshot!(
1121 p("%h %d, %Y %H:%M:%S %:z %:Q", "Apr 1, 2022 20:46:15 -08:00 -04:00"),
1122 @"2022-04-01T20:46:15-04:00[-04:00]",
1123 );
1124 }
1125
1126 #[test]
1127 fn ok_parse_timestamp() {
1128 let p = |fmt: &str, input: &str| {
1129 BrokenDownTime::parse_mono(fmt.as_bytes(), input.as_bytes())
1130 .unwrap()
1131 .to_timestamp()
1132 .unwrap()
1133 };
1134
1135 insta::assert_debug_snapshot!(
1136 p("%h %d, %Y %H:%M:%S %z", "Apr 1, 2022 20:46:15 -0400"),
1137 @"2022-04-02T00:46:15Z",
1138 );
1139 insta::assert_debug_snapshot!(
1140 p("%h %d, %Y %H:%M:%S %z", "Apr 1, 2022 20:46:15 +0400"),
1141 @"2022-04-01T16:46:15Z",
1142 );
1143 insta::assert_debug_snapshot!(
1144 p("%h %d, %Y %H:%M:%S %z", "Apr 1, 2022 20:46:15 -040059"),
1145 @"2022-04-02T00:47:14Z",
1146 );
1147
1148 insta::assert_debug_snapshot!(
1149 p("%h %d, %Y %H:%M:%S %:z", "Apr 1, 2022 20:46:15 -04:00"),
1150 @"2022-04-02T00:46:15Z",
1151 );
1152 insta::assert_debug_snapshot!(
1153 p("%h %d, %Y %H:%M:%S %:z", "Apr 1, 2022 20:46:15 +04:00"),
1154 @"2022-04-01T16:46:15Z",
1155 );
1156 insta::assert_debug_snapshot!(
1157 p("%h %d, %Y %H:%M:%S %:z", "Apr 1, 2022 20:46:15 -04:00:59"),
1158 @"2022-04-02T00:47:14Z",
1159 );
1160
1161 insta::assert_debug_snapshot!(
1162 p("%s", "0"),
1163 @"1970-01-01T00:00:00Z",
1164 );
1165 insta::assert_debug_snapshot!(
1166 p("%s", "-0"),
1167 @"1970-01-01T00:00:00Z",
1168 );
1169 insta::assert_debug_snapshot!(
1170 p("%s", "-1"),
1171 @"1969-12-31T23:59:59Z",
1172 );
1173 insta::assert_debug_snapshot!(
1174 p("%s", "1"),
1175 @"1970-01-01T00:00:01Z",
1176 );
1177 insta::assert_debug_snapshot!(
1178 p("%s", "+1"),
1179 @"1970-01-01T00:00:01Z",
1180 );
1181 insta::assert_debug_snapshot!(
1182 p("%s", "1737396540"),
1183 @"2025-01-20T18:09:00Z",
1184 );
1185 insta::assert_debug_snapshot!(
1186 p("%s", "-377705023201"),
1187 @"-009999-01-02T01:59:59Z",
1188 );
1189 insta::assert_debug_snapshot!(
1190 p("%s", "253402207200"),
1191 @"9999-12-30T22:00:00Z",
1192 );
1193 }
1194
1195 #[test]
1196 fn ok_parse_datetime() {
1197 let p = |fmt: &str, input: &str| {
1198 BrokenDownTime::parse_mono(fmt.as_bytes(), input.as_bytes())
1199 .unwrap()
1200 .to_datetime()
1201 .unwrap()
1202 };
1203
1204 insta::assert_debug_snapshot!(
1205 p("%h %d, %Y %H:%M:%S", "Apr 1, 2022 20:46:15"),
1206 @"2022-04-01T20:46:15",
1207 );
1208 insta::assert_debug_snapshot!(
1209 p("%h %05d, %Y %H:%M:%S", "Apr 1, 2022 20:46:15"),
1210 @"2022-04-01T20:46:15",
1211 );
1212 }
1213
1214 #[test]
1215 fn ok_parse_date() {
1216 let p = |fmt: &str, input: &str| {
1217 BrokenDownTime::parse_mono(fmt.as_bytes(), input.as_bytes())
1218 .unwrap()
1219 .to_date()
1220 .unwrap()
1221 };
1222
1223 insta::assert_debug_snapshot!(
1224 p("%m/%d/%y", "1/1/99"),
1225 @"1999-01-01",
1226 );
1227 insta::assert_debug_snapshot!(
1228 p("%m/%d/%04y", "1/1/0099"),
1229 @"1999-01-01",
1230 );
1231 insta::assert_debug_snapshot!(
1232 p("%D", "1/1/99"),
1233 @"1999-01-01",
1234 );
1235 insta::assert_debug_snapshot!(
1236 p("%m/%d/%Y", "1/1/0099"),
1237 @"0099-01-01",
1238 );
1239 insta::assert_debug_snapshot!(
1240 p("%m/%d/%Y", "1/1/1999"),
1241 @"1999-01-01",
1242 );
1243 insta::assert_debug_snapshot!(
1244 p("%m/%d/%Y", "12/31/9999"),
1245 @"9999-12-31",
1246 );
1247 insta::assert_debug_snapshot!(
1248 p("%m/%d/%Y", "01/01/-9999"),
1249 @"-009999-01-01",
1250 );
1251 insta::assert_snapshot!(
1252 p("%a %m/%d/%Y", "sun 7/14/2024"),
1253 @"2024-07-14",
1254 );
1255 insta::assert_snapshot!(
1256 p("%A %m/%d/%Y", "sUnDaY 7/14/2024"),
1257 @"2024-07-14",
1258 );
1259 insta::assert_snapshot!(
1260 p("%b %d %Y", "Jul 14 2024"),
1261 @"2024-07-14",
1262 );
1263 insta::assert_snapshot!(
1264 p("%B %d, %Y", "July 14, 2024"),
1265 @"2024-07-14",
1266 );
1267 insta::assert_snapshot!(
1268 p("%A, %B %d, %Y", "Wednesday, dEcEmBeR 25, 2024"),
1269 @"2024-12-25",
1270 );
1271
1272 insta::assert_debug_snapshot!(
1273 p("%Y%m%d", "20240730"),
1274 @"2024-07-30",
1275 );
1276 insta::assert_debug_snapshot!(
1277 p("%Y%m%d", "09990730"),
1278 @"0999-07-30",
1279 );
1280 insta::assert_debug_snapshot!(
1281 p("%Y%m%d", "9990111"),
1282 @"9990-11-01",
1283 );
1284 insta::assert_debug_snapshot!(
1285 p("%3Y%m%d", "09990111"),
1286 @"0999-01-11",
1287 );
1288 insta::assert_debug_snapshot!(
1289 p("%5Y%m%d", "09990111"),
1290 @"9990-11-01",
1291 );
1292 insta::assert_debug_snapshot!(
1293 p("%5Y%m%d", "009990111"),
1294 @"0999-01-11",
1295 );
1296
1297 insta::assert_debug_snapshot!(
1298 p("%C-%m-%d", "20-07-01"),
1299 @"2000-07-01",
1300 );
1301 insta::assert_debug_snapshot!(
1302 p("%C-%m-%d", "-20-07-01"),
1303 @"-002000-07-01",
1304 );
1305 insta::assert_debug_snapshot!(
1306 p("%C-%m-%d", "9-07-01"),
1307 @"0900-07-01",
1308 );
1309 insta::assert_debug_snapshot!(
1310 p("%C-%m-%d", "-9-07-01"),
1311 @"-000900-07-01",
1312 );
1313 insta::assert_debug_snapshot!(
1314 p("%C-%m-%d", "09-07-01"),
1315 @"0900-07-01",
1316 );
1317 insta::assert_debug_snapshot!(
1318 p("%C-%m-%d", "-09-07-01"),
1319 @"-000900-07-01",
1320 );
1321 insta::assert_debug_snapshot!(
1322 p("%C-%m-%d", "0-07-01"),
1323 @"0000-07-01",
1324 );
1325 insta::assert_debug_snapshot!(
1326 p("%C-%m-%d", "-0-07-01"),
1327 @"0000-07-01",
1328 );
1329
1330 insta::assert_snapshot!(
1331 p("%u %m/%d/%Y", "7 7/14/2024"),
1332 @"2024-07-14",
1333 );
1334 insta::assert_snapshot!(
1335 p("%w %m/%d/%Y", "0 7/14/2024"),
1336 @"2024-07-14",
1337 );
1338
1339 insta::assert_snapshot!(
1340 p("%Y-%U-%u", "2025-00-6"),
1341 @"2025-01-04",
1342 );
1343 insta::assert_snapshot!(
1344 p("%Y-%U-%u", "2025-01-7"),
1345 @"2025-01-05",
1346 );
1347 insta::assert_snapshot!(
1348 p("%Y-%U-%u", "2025-01-1"),
1349 @"2025-01-06",
1350 );
1351
1352 insta::assert_snapshot!(
1353 p("%Y-%W-%u", "2025-00-6"),
1354 @"2025-01-04",
1355 );
1356 insta::assert_snapshot!(
1357 p("%Y-%W-%u", "2025-00-7"),
1358 @"2025-01-05",
1359 );
1360 insta::assert_snapshot!(
1361 p("%Y-%W-%u", "2025-01-1"),
1362 @"2025-01-06",
1363 );
1364 insta::assert_snapshot!(
1365 p("%Y-%W-%u", "2025-01-2"),
1366 @"2025-01-07",
1367 );
1368 }
1369
1370 #[test]
1371 fn ok_parse_time() {
1372 let p = |fmt: &str, input: &str| {
1373 BrokenDownTime::parse_mono(fmt.as_bytes(), input.as_bytes())
1374 .unwrap()
1375 .to_time()
1376 .unwrap()
1377 };
1378
1379 insta::assert_debug_snapshot!(
1380 p("%H:%M", "15:48"),
1381 @"15:48:00",
1382 );
1383 insta::assert_debug_snapshot!(
1384 p("%H:%M:%S", "15:48:59"),
1385 @"15:48:59",
1386 );
1387 insta::assert_debug_snapshot!(
1388 p("%H:%M:%S", "15:48:60"),
1389 @"15:48:59",
1390 );
1391 insta::assert_debug_snapshot!(
1392 p("%T", "15:48:59"),
1393 @"15:48:59",
1394 );
1395 insta::assert_debug_snapshot!(
1396 p("%R", "15:48"),
1397 @"15:48:00",
1398 );
1399
1400 insta::assert_debug_snapshot!(
1401 p("%H %p", "5 am"),
1402 @"05:00:00",
1403 );
1404 insta::assert_debug_snapshot!(
1405 p("%H%p", "5am"),
1406 @"05:00:00",
1407 );
1408 insta::assert_debug_snapshot!(
1409 p("%H%p", "11pm"),
1410 @"23:00:00",
1411 );
1412 insta::assert_debug_snapshot!(
1413 p("%I%p", "11pm"),
1414 @"23:00:00",
1415 );
1416 insta::assert_debug_snapshot!(
1417 p("%I%p", "12am"),
1418 @"00:00:00",
1419 );
1420 insta::assert_debug_snapshot!(
1421 p("%H%p", "23pm"),
1422 @"23:00:00",
1423 );
1424 insta::assert_debug_snapshot!(
1425 p("%H%p", "23am"),
1426 @"11:00:00",
1427 );
1428
1429 insta::assert_debug_snapshot!(
1430 p("%H:%M:%S%.f", "15:48:01.1"),
1431 @"15:48:01.1",
1432 );
1433 insta::assert_debug_snapshot!(
1434 p("%H:%M:%S%.255f", "15:48:01.1"),
1435 @"15:48:01.1",
1436 );
1437 insta::assert_debug_snapshot!(
1438 p("%H:%M:%S%255.255f", "15:48:01.1"),
1439 @"15:48:01.1",
1440 );
1441 insta::assert_debug_snapshot!(
1442 p("%H:%M:%S%.f", "15:48:01"),
1443 @"15:48:01",
1444 );
1445 insta::assert_debug_snapshot!(
1446 p("%H:%M:%S%.fa", "15:48:01a"),
1447 @"15:48:01",
1448 );
1449 insta::assert_debug_snapshot!(
1450 p("%H:%M:%S%.f", "15:48:01.123456789"),
1451 @"15:48:01.123456789",
1452 );
1453 insta::assert_debug_snapshot!(
1454 p("%H:%M:%S%.f", "15:48:01.000000001"),
1455 @"15:48:01.000000001",
1456 );
1457
1458 insta::assert_debug_snapshot!(
1459 p("%H:%M:%S.%f", "15:48:01.1"),
1460 @"15:48:01.1",
1461 );
1462 insta::assert_debug_snapshot!(
1463 p("%H:%M:%S.%3f", "15:48:01.123"),
1464 @"15:48:01.123",
1465 );
1466 insta::assert_debug_snapshot!(
1467 p("%H:%M:%S.%3f", "15:48:01.123456"),
1468 @"15:48:01.123456",
1469 );
1470
1471 insta::assert_debug_snapshot!(
1472 p("%H:%M:%S.%N", "15:48:01.1"),
1473 @"15:48:01.1",
1474 );
1475 insta::assert_debug_snapshot!(
1476 p("%H:%M:%S.%3N", "15:48:01.123"),
1477 @"15:48:01.123",
1478 );
1479 insta::assert_debug_snapshot!(
1480 p("%H:%M:%S.%3N", "15:48:01.123456"),
1481 @"15:48:01.123456",
1482 );
1483
1484 insta::assert_debug_snapshot!(
1485 p("%H", "09"),
1486 @"09:00:00",
1487 );
1488 insta::assert_debug_snapshot!(
1489 p("%H", " 9"),
1490 @"09:00:00",
1491 );
1492 insta::assert_debug_snapshot!(
1493 p("%H", "15"),
1494 @"15:00:00",
1495 );
1496 insta::assert_debug_snapshot!(
1497 p("%k", "09"),
1498 @"09:00:00",
1499 );
1500 insta::assert_debug_snapshot!(
1501 p("%k", " 9"),
1502 @"09:00:00",
1503 );
1504 insta::assert_debug_snapshot!(
1505 p("%k", "15"),
1506 @"15:00:00",
1507 );
1508
1509 insta::assert_debug_snapshot!(
1510 p("%I", "09"),
1511 @"09:00:00",
1512 );
1513 insta::assert_debug_snapshot!(
1514 p("%I", " 9"),
1515 @"09:00:00",
1516 );
1517 insta::assert_debug_snapshot!(
1518 p("%l", "09"),
1519 @"09:00:00",
1520 );
1521 insta::assert_debug_snapshot!(
1522 p("%l", " 9"),
1523 @"09:00:00",
1524 );
1525 }
1526
1527 #[test]
1528 fn ok_parse_whitespace() {
1529 let p = |fmt: &str, input: &str| {
1530 BrokenDownTime::parse_mono(fmt.as_bytes(), input.as_bytes())
1531 .unwrap()
1532 .to_time()
1533 .unwrap()
1534 };
1535
1536 insta::assert_debug_snapshot!(
1537 p("%H%M", "1548"),
1538 @"15:48:00",
1539 );
1540 insta::assert_debug_snapshot!(
1541 p("%H%M", "15\n48"),
1542 @"15:48:00",
1543 );
1544 insta::assert_debug_snapshot!(
1545 p("%H%M", "15\t48"),
1546 @"15:48:00",
1547 );
1548 insta::assert_debug_snapshot!(
1549 p("%H%n%M", "1548"),
1550 @"15:48:00",
1551 );
1552 insta::assert_debug_snapshot!(
1553 p("%H%n%M", "15\n48"),
1554 @"15:48:00",
1555 );
1556 insta::assert_debug_snapshot!(
1557 p("%H%n%M", "15\t48"),
1558 @"15:48:00",
1559 );
1560 insta::assert_debug_snapshot!(
1561 p("%H%t%M", "1548"),
1562 @"15:48:00",
1563 );
1564 insta::assert_debug_snapshot!(
1565 p("%H%t%M", "15\n48"),
1566 @"15:48:00",
1567 );
1568 insta::assert_debug_snapshot!(
1569 p("%H%t%M", "15\t48"),
1570 @"15:48:00",
1571 );
1572 }
1573
1574 #[test]
1575 fn ok_parse_offset() {
1576 let p = |fmt: &str, input: &str| {
1577 BrokenDownTime::parse_mono(fmt.as_bytes(), input.as_bytes())
1578 .unwrap()
1579 .offset
1580 .unwrap()
1581 };
1582
1583 insta::assert_debug_snapshot!(
1584 p("%z", "+0530"),
1585 @"05:30:00",
1586 );
1587 insta::assert_debug_snapshot!(
1588 p("%z", "-0530"),
1589 @"-05:30:00",
1590 );
1591 insta::assert_debug_snapshot!(
1592 p("%z", "-0500"),
1593 @"-05:00:00",
1594 );
1595 insta::assert_debug_snapshot!(
1596 p("%z", "+053015"),
1597 @"05:30:15",
1598 );
1599 insta::assert_debug_snapshot!(
1600 p("%z", "+050015"),
1601 @"05:00:15",
1602 );
1603
1604 insta::assert_debug_snapshot!(
1605 p("%:z", "+05:30"),
1606 @"05:30:00",
1607 );
1608 insta::assert_debug_snapshot!(
1609 p("%:z", "-05:30"),
1610 @"-05:30:00",
1611 );
1612 insta::assert_debug_snapshot!(
1613 p("%:z", "-05:00"),
1614 @"-05:00:00",
1615 );
1616 insta::assert_debug_snapshot!(
1617 p("%:z", "+05:30:15"),
1618 @"05:30:15",
1619 );
1620 insta::assert_debug_snapshot!(
1621 p("%:z", "-05:00:15"),
1622 @"-05:00:15",
1623 );
1624
1625 insta::assert_debug_snapshot!(
1626 p("%::z", "+05:30:15"),
1627 @"05:30:15",
1628 );
1629 insta::assert_debug_snapshot!(
1630 p("%::z", "-05:30:15"),
1631 @"-05:30:15",
1632 );
1633 insta::assert_debug_snapshot!(
1634 p("%::z", "-05:00:00"),
1635 @"-05:00:00",
1636 );
1637 insta::assert_debug_snapshot!(
1638 p("%::z", "-05:00:15"),
1639 @"-05:00:15",
1640 );
1641
1642 insta::assert_debug_snapshot!(
1643 p("%:::z", "+05"),
1644 @"05:00:00",
1645 );
1646 insta::assert_debug_snapshot!(
1647 p("%:::z", "-05"),
1648 @"-05:00:00",
1649 );
1650 insta::assert_debug_snapshot!(
1651 p("%:::z", "+00"),
1652 @"00:00:00",
1653 );
1654 insta::assert_debug_snapshot!(
1655 p("%:::z", "-00"),
1656 @"00:00:00",
1657 );
1658 insta::assert_debug_snapshot!(
1659 p("%:::z", "+05:30"),
1660 @"05:30:00",
1661 );
1662 insta::assert_debug_snapshot!(
1663 p("%:::z", "-05:30"),
1664 @"-05:30:00",
1665 );
1666 insta::assert_debug_snapshot!(
1667 p("%:::z", "+05:30:15"),
1668 @"05:30:15",
1669 );
1670 insta::assert_debug_snapshot!(
1671 p("%:::z", "-05:30:15"),
1672 @"-05:30:15",
1673 );
1674 insta::assert_debug_snapshot!(
1675 p("%:::z", "-05:00:00"),
1676 @"-05:00:00",
1677 );
1678 insta::assert_debug_snapshot!(
1679 p("%:::z", "-05:00:15"),
1680 @"-05:00:15",
1681 );
1682 }
1683
1684 #[test]
1685 fn err_parse() {
1686 let p = |fmt: &str, input: &str| {
1687 BrokenDownTime::parse_mono(fmt.as_bytes(), input.as_bytes())
1688 .unwrap_err()
1689 .to_string()
1690 };
1691
1692 insta::assert_snapshot!(
1693 p("%M", ""),
1694 @"strptime parsing failed: expected non-empty input for directive `%M`, but found end of input",
1695 );
1696 insta::assert_snapshot!(
1697 p("%M", "a"),
1698 @"strptime parsing failed: %M failed: failed to parse minute number: invalid number, no digits found",
1699 );
1700 insta::assert_snapshot!(
1701 p("%M%S", "15"),
1702 @"strptime parsing failed: expected non-empty input for directive `%S`, but found end of input",
1703 );
1704 insta::assert_snapshot!(
1705 p("%M%a", "Sun"),
1706 @"strptime parsing failed: %M failed: failed to parse minute number: invalid number, no digits found",
1707 );
1708
1709 insta::assert_snapshot!(
1710 p("%y", "999"),
1711 @"strptime expects to consume the entire input, but `9` remains unparsed",
1712 );
1713 insta::assert_snapshot!(
1714 p("%Y", "-10000"),
1715 @"strptime expects to consume the entire input, but `0` remains unparsed",
1716 );
1717 insta::assert_snapshot!(
1718 p("%Y", "10000"),
1719 @"strptime expects to consume the entire input, but `0` remains unparsed",
1720 );
1721 insta::assert_snapshot!(
1722 p("%A %m/%d/%y", "Mon 7/14/24"),
1723 @"strptime parsing failed: %A failed: unrecognized weekday abbreviation: failed to find expected value, available choices are: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday",
1724 );
1725 insta::assert_snapshot!(
1726 p("%b", "Bad"),
1727 @"strptime parsing failed: %b failed: expected to find month name abbreviation",
1728 );
1729 insta::assert_snapshot!(
1730 p("%h", "July"),
1731 @"strptime expects to consume the entire input, but `y` remains unparsed",
1732 );
1733 insta::assert_snapshot!(
1734 p("%B", "Jul"),
1735 @"strptime parsing failed: %B failed: unrecognized month name: failed to find expected value, available choices are: January, February, March, April, May, June, July, August, September, October, November, December",
1736 );
1737 insta::assert_snapshot!(
1738 p("%H", "24"),
1739 @"strptime parsing failed: %H failed: failed to parse hour number: parameter 'hour' is not in the required range of 0..=23",
1740 );
1741 insta::assert_snapshot!(
1742 p("%M", "60"),
1743 @"strptime parsing failed: %M failed: failed to parse minute number: parameter 'minute' is not in the required range of 0..=59",
1744 );
1745 insta::assert_snapshot!(
1746 p("%S", "61"),
1747 @"strptime parsing failed: %S failed: failed to parse second number: parameter 'second' is not in the required range of 0..=59",
1748 );
1749 insta::assert_snapshot!(
1750 p("%I", "0"),
1751 @"strptime parsing failed: %I failed: failed to parse hour number: parameter 'hour (12 hour clock)' is not in the required range of 1..=12",
1752 );
1753 insta::assert_snapshot!(
1754 p("%I", "13"),
1755 @"strptime parsing failed: %I failed: failed to parse hour number: parameter 'hour (12 hour clock)' is not in the required range of 1..=12",
1756 );
1757 insta::assert_snapshot!(
1758 p("%p", "aa"),
1759 @"strptime parsing failed: %p failed: expected to find `AM` or `PM`",
1760 );
1761
1762 insta::assert_snapshot!(
1763 p("%_", " "),
1764 @"strptime parsing failed: expected to find specifier directive after flag `_`, but found end of format string",
1765 );
1766 insta::assert_snapshot!(
1767 p("%-", " "),
1768 @"strptime parsing failed: expected to find specifier directive after flag `-`, but found end of format string",
1769 );
1770 insta::assert_snapshot!(
1771 p("%0", " "),
1772 @"strptime parsing failed: expected to find specifier directive after flag `0`, but found end of format string",
1773 );
1774 insta::assert_snapshot!(
1775 p("%^", " "),
1776 @"strptime parsing failed: expected to find specifier directive after flag `^`, but found end of format string",
1777 );
1778 insta::assert_snapshot!(
1779 p("%#", " "),
1780 @"strptime parsing failed: expected to find specifier directive after flag `#`, but found end of format string",
1781 );
1782 insta::assert_snapshot!(
1783 p("%_1", " "),
1784 @"strptime parsing failed: expected to find specifier directive after parsed width, but found end of format string",
1785 );
1786 insta::assert_snapshot!(
1787 p("%_23", " "),
1788 @"strptime parsing failed: expected to find specifier directive after parsed width, but found end of format string",
1789 );
1790
1791 insta::assert_snapshot!(
1792 p("%:", " "),
1793 @"strptime parsing failed: expected to find specifier directive after colons, but found end of format string",
1794 );
1795
1796 insta::assert_snapshot!(
1797 p("%::", " "),
1798 @"strptime parsing failed: expected to find specifier directive after colons, but found end of format string",
1799 );
1800
1801 insta::assert_snapshot!(
1802 p("%:::", " "),
1803 @"strptime parsing failed: expected to find specifier directive after colons, but found end of format string",
1804 );
1805
1806 insta::assert_snapshot!(
1807 p("%H:%M:%S%.f", "15:59:01."),
1808 @"strptime parsing failed: %.f failed: expected at least one fractional decimal digit, but did not find any",
1809 );
1810 insta::assert_snapshot!(
1811 p("%H:%M:%S%.f", "15:59:01.a"),
1812 @"strptime parsing failed: %.f failed: expected at least one fractional decimal digit, but did not find any",
1813 );
1814 insta::assert_snapshot!(
1815 p("%H:%M:%S%.f", "15:59:01.1234567891"),
1816 @"strptime expects to consume the entire input, but `1` remains unparsed",
1817 );
1818 insta::assert_snapshot!(
1819 p("%H:%M:%S.%f", "15:59:01."),
1820 @"strptime parsing failed: expected non-empty input for directive `%f`, but found end of input",
1821 );
1822 insta::assert_snapshot!(
1823 p("%H:%M:%S.%f", "15:59:01"),
1824 @"strptime parsing failed: expected to match literal byte `.` from format string, but found end of input",
1825 );
1826 insta::assert_snapshot!(
1827 p("%H:%M:%S.%f", "15:59:01.a"),
1828 @"strptime parsing failed: %f failed: expected at least one fractional decimal digit, but did not find any",
1829 );
1830 insta::assert_snapshot!(
1831 p("%H:%M:%S.%N", "15:59:01."),
1832 @"strptime parsing failed: expected non-empty input for directive `%N`, but found end of input",
1833 );
1834 insta::assert_snapshot!(
1835 p("%H:%M:%S.%N", "15:59:01"),
1836 @"strptime parsing failed: expected to match literal byte `.` from format string, but found end of input",
1837 );
1838 insta::assert_snapshot!(
1839 p("%H:%M:%S.%N", "15:59:01.a"),
1840 @"strptime parsing failed: %N failed: expected at least one fractional decimal digit, but did not find any",
1841 );
1842
1843 insta::assert_snapshot!(
1844 p("%Q", "+America/New_York"),
1845 @"strptime parsing failed: %Q failed: failed to parse hours in UTC numeric offset: failed to parse hours (requires a two digit integer): invalid digit, expected 0-9 but got A",
1846 );
1847 insta::assert_snapshot!(
1848 p("%Q", "-America/New_York"),
1849 @"strptime parsing failed: %Q failed: failed to parse hours in UTC numeric offset: failed to parse hours (requires a two digit integer): invalid digit, expected 0-9 but got A",
1850 );
1851 insta::assert_snapshot!(
1852 p("%:Q", "+0400"),
1853 @"strptime parsing failed: %:Q failed: parsed hour component of time zone offset, but could not find required colon separator",
1854 );
1855 insta::assert_snapshot!(
1856 p("%Q", "+04:00"),
1857 @"strptime parsing failed: %Q failed: parsed hour component of time zone offset, but found colon after hours which is not allowed",
1858 );
1859 insta::assert_snapshot!(
1860 p("%Q", "America/"),
1861 @"strptime parsing failed: %Q failed: expected to find the start of an IANA time zone identifier name or component, but found end of input instead",
1862 );
1863 insta::assert_snapshot!(
1864 p("%Q", "America/+"),
1865 @"strptime parsing failed: %Q failed: expected to find the start of an IANA time zone identifier name or component",
1866 );
1867
1868 insta::assert_snapshot!(
1869 p("%s", "-377705023202"),
1870 @"strptime parsing failed: %s failed: failed to parse Unix timestamp (in seconds): parameter 'Unix timestamp seconds' is not in the required range of -377705023201..=253402207200",
1871 );
1872 insta::assert_snapshot!(
1873 p("%s", "253402207201"),
1874 @"strptime parsing failed: %s failed: failed to parse Unix timestamp (in seconds): parameter 'Unix timestamp seconds' is not in the required range of -377705023201..=253402207200",
1875 );
1876 insta::assert_snapshot!(
1877 p("%s", "-9999999999999999999"),
1878 @"strptime parsing failed: %s failed: failed to parse Unix timestamp (in seconds): number too big to parse into 64-bit integer",
1879 );
1880 insta::assert_snapshot!(
1881 p("%s", "9999999999999999999"),
1882 @"strptime parsing failed: %s failed: failed to parse Unix timestamp (in seconds): number too big to parse into 64-bit integer",
1883 );
1884
1885 insta::assert_snapshot!(
1886 p("%u", "0"),
1887 @"strptime parsing failed: %u failed: failed to parse weekday number: parameter 'weekday (Monday 1-indexed)' is not in the required range of 1..=7",
1888 );
1889 insta::assert_snapshot!(
1890 p("%w", "7"),
1891 @"strptime parsing failed: %w failed: failed to parse weekday number: parameter 'weekday (Sunday 0-indexed)' is not in the required range of 0..=6",
1892 );
1893 insta::assert_snapshot!(
1894 p("%u", "128"),
1895 @"strptime expects to consume the entire input, but `28` remains unparsed",
1896 );
1897 insta::assert_snapshot!(
1898 p("%w", "128"),
1899 @"strptime expects to consume the entire input, but `28` remains unparsed",
1900 );
1901 }
1902
1903 #[test]
1904 fn err_parse_date() {
1905 let p = |fmt: &str, input: &str| {
1906 BrokenDownTime::parse_mono(fmt.as_bytes(), input.as_bytes())
1907 .unwrap()
1908 .to_date()
1909 .unwrap_err()
1910 .to_string()
1911 };
1912
1913 insta::assert_snapshot!(
1914 p("%Y", "2024"),
1915 @"a month/day, day-of-year or week date must be present to create a date, but none were found",
1916 );
1917 insta::assert_snapshot!(
1918 p("%m", "7"),
1919 @"year required to parse date",
1920 );
1921 insta::assert_snapshot!(
1922 p("%d", "25"),
1923 @"year required to parse date",
1924 );
1925 insta::assert_snapshot!(
1926 p("%Y-%m", "2024-7"),
1927 @"a month/day, day-of-year or week date must be present to create a date, but none were found",
1928 );
1929 insta::assert_snapshot!(
1930 p("%Y-%d", "2024-25"),
1931 @"a month/day, day-of-year or week date must be present to create a date, but none were found",
1932 );
1933 insta::assert_snapshot!(
1934 p("%m-%d", "7-25"),
1935 @"year required to parse date",
1936 );
1937
1938 insta::assert_snapshot!(
1939 p("%m/%d/%y", "6/31/24"),
1940 @"invalid date: parameter 'day' for `2024-06` is invalid, must be in range `1..=30`",
1941 );
1942 insta::assert_snapshot!(
1943 p("%m/%d/%y", "2/29/23"),
1944 @"invalid date: parameter 'day' for `2023-02` is invalid, must be in range `1..=28`",
1945 );
1946 insta::assert_snapshot!(
1947 p("%a %m/%d/%y", "Mon 7/14/24"),
1948 @"parsed weekday `Monday` does not match weekday `Sunday` from parsed date",
1949 );
1950 insta::assert_snapshot!(
1951 p("%A %m/%d/%y", "Monday 7/14/24"),
1952 @"parsed weekday `Monday` does not match weekday `Sunday` from parsed date",
1953 );
1954
1955 insta::assert_snapshot!(
1956 p("%Y-%U-%u", "2025-00-2"),
1957 @"weekday `Tuesday` is not valid for Sunday based week number",
1958 );
1959 insta::assert_snapshot!(
1960 p("%Y-%W-%u", "2025-00-2"),
1961 @"weekday `Tuesday` is not valid for Monday based week number",
1962 );
1963 }
1964
1965 #[test]
1966 fn err_parse_time() {
1967 let p = |fmt: &str, input: &str| {
1968 BrokenDownTime::parse_mono(fmt.as_bytes(), input.as_bytes())
1969 .unwrap()
1970 .to_time()
1971 .unwrap_err()
1972 .to_string()
1973 };
1974
1975 insta::assert_snapshot!(
1976 p("%M", "59"),
1977 @"parsing format did not include hour directive, but did include minute directive (cannot have smaller time units with bigger time units missing)",
1978 );
1979 insta::assert_snapshot!(
1980 p("%S", "59"),
1981 @"parsing format did not include hour directive, but did include second directive (cannot have smaller time units with bigger time units missing)",
1982 );
1983 insta::assert_snapshot!(
1984 p("%M:%S", "59:59"),
1985 @"parsing format did not include hour directive, but did include minute directive (cannot have smaller time units with bigger time units missing)",
1986 );
1987 insta::assert_snapshot!(
1988 p("%H:%S", "15:59"),
1989 @"parsing format did not include minute directive, but did include second directive (cannot have smaller time units with bigger time units missing)",
1990 );
1991 }
1992
1993 #[test]
1994 fn err_parse_offset() {
1995 let p = |fmt: &str, input: &str| {
1996 BrokenDownTime::parse_mono(fmt.as_bytes(), input.as_bytes())
1997 .unwrap_err()
1998 .to_string()
1999 };
2000
2001 insta::assert_snapshot!(
2002 p("%z", "+05:30"),
2003 @"strptime parsing failed: %z failed: parsed hour component of time zone offset, but found colon after hours which is not allowed",
2004 );
2005 insta::assert_snapshot!(
2006 p("%:z", "+0530"),
2007 @"strptime parsing failed: %:z failed: parsed hour component of time zone offset, but could not find required colon separator",
2008 );
2009 insta::assert_snapshot!(
2010 p("%::z", "+0530"),
2011 @"strptime parsing failed: %::z failed: parsed hour component of time zone offset, but could not find required colon separator",
2012 );
2013 insta::assert_snapshot!(
2014 p("%:::z", "+0530"),
2015 @"strptime parsing failed: %:::z failed: parsed hour component of time zone offset, but could not find required colon separator",
2016 );
2017
2018 insta::assert_snapshot!(
2019 p("%z", "+05"),
2020 @"strptime parsing failed: %z failed: parsed hour component of time zone offset, but could not find required minute component",
2021 );
2022 insta::assert_snapshot!(
2023 p("%:z", "+05"),
2024 @"strptime parsing failed: %:z failed: parsed hour component of time zone offset, but could not find required minute component",
2025 );
2026 insta::assert_snapshot!(
2027 p("%::z", "+05"),
2028 @"strptime parsing failed: %::z failed: parsed hour component of time zone offset, but could not find required minute component",
2029 );
2030 insta::assert_snapshot!(
2031 p("%::z", "+05:30"),
2032 @"strptime parsing failed: %::z failed: parsed hour and minute components of time zone offset, but could not find required second component",
2033 );
2034 insta::assert_snapshot!(
2035 p("%:::z", "+5"),
2036 @"strptime parsing failed: %:::z failed: failed to parse hours in UTC numeric offset: expected two digit hour after sign, but found end of input",
2037 );
2038
2039 insta::assert_snapshot!(
2040 p("%z", "+0530:15"),
2041 @"strptime expects to consume the entire input, but `:15` remains unparsed",
2042 );
2043 insta::assert_snapshot!(
2044 p("%:z", "+05:3015"),
2045 @"strptime expects to consume the entire input, but `15` remains unparsed",
2046 );
2047 insta::assert_snapshot!(
2048 p("%::z", "+05:3015"),
2049 @"strptime parsing failed: %::z failed: parsed hour and minute components of time zone offset, but could not find required second component",
2050 );
2051 insta::assert_snapshot!(
2052 p("%:::z", "+05:3015"),
2053 @"strptime expects to consume the entire input, but `15` remains unparsed",
2054 );
2055 }
2056
2057 #[test]
2061 fn err_parse_large_century() {
2062 let p = |fmt: &str, input: &str| {
2063 BrokenDownTime::parse_mono(fmt.as_bytes(), input.as_bytes())
2064 .unwrap_err()
2065 .to_string()
2066 };
2067
2068 insta::assert_snapshot!(
2069 p("%^50C%", "2000000000000000000#0077)()"),
2070 @"strptime parsing failed: %C failed: failed to parse year number for century: parameter 'century' is not in the required range of 0..=99",
2071 );
2072 }
2073}