Debian Codegraph @

rust/src/parsing.rs

raw
1 use core::str;
2 use std::{fmt, str::CharIndices};
3
4 use crate::{
5 constants::MONTHS_OFFSETS,
6 helpers::{days_in_year, is_leap, is_long_year, week_day},
7 };
8
9 #[derive(Debug, Clone)]
10 pub struct ParseError {
11 index: usize,
12 message: String,
13 }
14
15 impl fmt::Display for ParseError {
16 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17 write!(f, "{} (Position: {})", self.message, self.index)
18 }
19 }
20
21 pub struct ParsedDateTime {
22 pub year: u32,
23 pub month: u32,
24 pub day: u32,
25 pub hour: u32,
26 pub minute: u32,
27 pub second: u32,
28 pub microsecond: u32,
29 pub offset: Option<i32>,
30 #[allow(dead_code)]
31 pub has_offset: bool,
32 pub tzname: Option<String>,
33 pub has_date: bool,
34 pub has_time: bool,
35 pub extended_date_format: bool,
36 pub time_is_midnight: bool,
37 }
38
39 impl ParsedDateTime {
40 pub fn new() -> ParsedDateTime {
41 ParsedDateTime {
42 year: 0,
43 month: 1,
44 day: 1,
45 hour: 0,
46 minute: 0,
47 second: 0,
48 microsecond: 0,
49 offset: None,
50 has_offset: false,
51 tzname: None,
52 has_date: false,
53 has_time: false,
54 extended_date_format: false,
55 time_is_midnight: false,
56 }
57 }
58 }
59
60 pub struct ParsedDuration {
61 pub years: u32,
62 pub months: u32,
63 pub weeks: u32,
64 pub days: u32,
65 pub hours: u32,
66 pub minutes: u32,
67 pub seconds: u32,
68 pub microseconds: u32,
69 }
70
71 impl ParsedDuration {
72 pub fn new() -> ParsedDuration {
73 ParsedDuration {
74 years: 0,
75 months: 0,
76 weeks: 0,
77 days: 0,
78 hours: 0,
79 minutes: 0,
80 seconds: 0,
81 microseconds: 0,
82 }
83 }
84 }
85
86 pub struct Parsed {
87 pub datetime: Option<ParsedDateTime>,
88 pub duration: Option<ParsedDuration>,
89 pub second_datetime: Option<ParsedDateTime>,
90 }
91
92 impl Parsed {
93 pub fn new() -> Parsed {
94 Parsed {
95 datetime: None,
96 duration: None,
97 second_datetime: None,
98 }
99 }
100 }
101
102 pub struct Parser<'a> {
103 /// Input to parse.
104 src: &'a str,
105 /// Iterator used for getting characters from `src`.
106 chars: CharIndices<'a>,
107 /// Current byte offset into `src`.
108 idx: usize,
109 /// Current character
110 current: char,
111 }
112
113 impl<'a> Parser<'a> {
114 /// Creates a new parser from a &str.
115 pub fn new(input: &'a str) -> Parser<'a> {
116 let mut p = Parser {
117 src: input,
118 chars: input.char_indices(),
119 idx: 0,
120 current: '\0',
121 };
122 p.inc();
123 p
124 }
125
126 /// Increments the parser if the end of the input has not been reached.
127 /// Returns whether or not it was able to advance.
128 fn inc(&mut self) -> Option<char> {
129 if let Some((i, ch)) = self.chars.next() {
130 self.idx = i;
131 self.current = ch;
132 Some(ch)
133 } else {
134 self.idx = self.src.len();
135 self.current = '\0';
136 None
137 }
138 }
139
140 fn parse_error(&mut self, message: String) -> ParseError {
141 ParseError {
142 index: self.idx,
143 message,
144 }
145 }
146
147 fn unexpected_character_error(
148 &mut self,
149 field_name: &str,
150 expected_character_count: usize,
151 ) -> ParseError {
152 if self.end() {
153 return self.parse_error(format!(
154 "Unexpected end of string while parsing {}. Expected {} more character{}.",
155 field_name,
156 expected_character_count,
157 if expected_character_count == 1 {
158 ""
159 } else {
160 "s"
161 }
162 ));
163 }
164
165 self.parse_error(format!(
166 "Invalid character while parsing {}: {}.",
167 field_name, self.current,
168 ))
169 }
170
171 /// Returns true if the parser has reached the end of the input.
172 fn end(&self) -> bool {
173 self.idx >= self.src.len()
174 }
175
176 fn parse_integer(&mut self, length: usize, field_name: &str) -> Result<u32, ParseError> {
177 let mut value: u32 = 0;
178
179 for i in 0..length {
180 if self.end() {
181 return Err(self.parse_error(format!(
182 "Unexpected end of string while parsing \"{}\". Expected {} more character{}",
183 field_name,
184 length - i,
185 if (length - i) != 1 { "s" } else { "" }
186 )));
187 }
188
189 if let Some(digit) = self.current.to_digit(10) {
190 value = 10 * value + digit;
191 self.inc();
192 } else {
193 return Err(self.unexpected_character_error(field_name, length - i));
194 }
195 }
196
197 Ok(value)
198 }
199
200 pub fn parse(&mut self) -> Result<Parsed, ParseError> {
201 let mut parsed = Parsed::new();
202
203 if self.current == 'P' {
204 // Duration (and possibly time interval)
205 self.parse_duration(&mut parsed)?;
206 } else {
207 self.parse_datetime(&mut parsed)?;
208 }
209
210 Ok(parsed)
211 }
212
213 fn parse_datetime(&mut self, parsed: &mut Parsed) -> Result<(), ParseError> {
214 let mut datetime = ParsedDateTime::new();
215
216 if self.current == 'T' {
217 self.parse_time(&mut datetime, false)?;
218
219 if !self.end() {
220 return Err(self.parse_error("Unconverted data remains".to_string()));
221 }
222
223 match &parsed.datetime {
224 Some(_) => {
225 parsed.second_datetime = Some(datetime);
226 }
227 None => match &parsed.duration {
228 Some(_) => {
229 parsed.second_datetime = Some(datetime);
230 }
231 None => {
232 parsed.datetime = Some(datetime);
233 }
234 },
235 }
236
237 return Ok(());
238 }
239
240 datetime.year = self.parse_integer(2, "year")?;
241
242 if self.current == ':' {
243 // Time in extended format
244 datetime.hour = datetime.year;
245 datetime.year = 0;
246 datetime.extended_date_format = true;
247 self.parse_time(&mut datetime, true)?;
248
249 if !self.end() {
250 return Err(self.parse_error("Unconverted data remains".to_string()));
251 }
252
253 match &parsed.datetime {
254 Some(_) => {
255 parsed.second_datetime = Some(datetime);
256 }
257 None => match &parsed.duration {
258 Some(_) => {
259 parsed.second_datetime = Some(datetime);
260 }
261 None => {
262 parsed.datetime = Some(datetime);
263 }
264 },
265 }
266
267 return Ok(());
268 }
269
270 datetime.has_date = true;
271 datetime.year = datetime.year * 100 + self.parse_integer(2, "year")?;
272
273 if self.current == '-' {
274 self.inc();
275 datetime.extended_date_format = true;
276
277 if self.current == 'W' {
278 // ISO week and day in extended format (i.e. Www-D)
279 self.inc();
280
281 let iso_week = self.parse_integer(2, "iso week")?;
282 let mut iso_day: u32 = 1;
283
284 if !self.end() && self.current != ' ' && self.current != 'T' {
285 // Optional day
286 if self.current != '-' {
287 return Err(self.parse_error(format!(
288 "Invalid character \"{}\" while parsing {}",
289 self.current, "date separator"
290 )));
291 }
292
293 self.inc();
294
295 iso_day = self.parse_integer(1, "iso day")?;
296 }
297
298 let (year, month, day) = self.iso_to_ymd(datetime.year, iso_week, iso_day)?;
299
300 datetime.year = year;
301 datetime.month = month;
302 datetime.day = day;
303 } else {
304 /*
305 Month and day in extended format (MM-DD) or ordinal date (DDD)
306 We'll assume first that the next part is a month and adjust if not.
307 */
308 datetime.month = self.parse_integer(2, "month")?;
309
310 if !self.end() && self.current != ' ' && self.current != 'T' {
311 if self.current == '-' {
312 // Optional day
313 self.inc();
314 datetime.day = self.parse_integer(2, "day")?;
315 } else {
316 // Ordinal day
317 let ordinal_day =
318 (datetime.month * 10 + self.parse_integer(1, "ordinal day")?) as i32;
319
320 let (year, month, day) =
321 self.ordinal_to_ymd(datetime.year, ordinal_day, false)?;
322
323 datetime.year = year;
324 datetime.month = month;
325 datetime.day = day;
326 }
327 } else {
328 datetime.day = 1;
329 }
330 }
331 } else if self.current == 'W' {
332 // Compact ISO week and day (WwwD)
333 self.inc();
334
335 let iso_week = self.parse_integer(2, "iso week")?;
336 let mut iso_day: u32 = 1;
337
338 if !self.end() && self.current != ' ' && self.current != 'T' {
339 iso_day = self.parse_integer(1, "iso day")?;
340 }
341
342 match self.iso_to_ymd(datetime.year, iso_week, iso_day) {
343 Ok((year, month, day)) => {
344 datetime.year = year;
345 datetime.month = month;
346 datetime.day = day;
347 }
348 Err(error) => return Err(error),
349 }
350 } else {
351 /*
352 Month and day in compact format (MMDD) or ordinal date (DDD)
353 We'll assume first that the next part is a month and adjust if not.
354 */
355 datetime.month = self.parse_integer(2, "month")?;
356 let mut ordinal_day = self.parse_integer(1, "ordinal day")? as i32;
357
358 if self.end() || self.current == ' ' || self.current == 'T' {
359 // Ordinal day
360 ordinal_day += datetime.month as i32 * 10;
361
362 let (year, month, day) = self.ordinal_to_ymd(datetime.year, ordinal_day, false)?;
363
364 datetime.year = year;
365 datetime.month = month;
366 datetime.day = day;
367 } else {
368 // Day
369 datetime.day = ordinal_day as u32 * 10 + self.parse_integer(1, "day")?;
370 }
371 }
372
373 if !self.end() {
374 self.parse_time(&mut datetime, false)?;
375 }
376
377 if !self.end() {
378 if self.current == '/' && parsed.datetime.is_none() && parsed.duration.is_none() {
379 // Interval
380 parsed.datetime = Some(datetime);
381
382 self.inc();
383
384 if self.current == 'P' {
385 // Duration
386 self.parse_duration(parsed)?;
387 } else {
388 self.parse_datetime(parsed)?;
389 }
390
391 return Ok(());
392 }
393
394 return Err(self.parse_error("Unconverted data remains".to_string()));
395 }
396
397 match &parsed.datetime {
398 Some(_) => {
399 parsed.second_datetime = Some(datetime);
400 }
401 None => match &parsed.duration {
402 Some(_) => {
403 parsed.second_datetime = Some(datetime);
404 }
405 None => {
406 parsed.datetime = Some(datetime);
407 }
408 },
409 }
410
411 Ok(())
412 }
413
414 fn parse_time(
415 &mut self,
416 datetime: &mut ParsedDateTime,
417 skip_hour: bool,
418 ) -> Result<(), ParseError> {
419 // TODO: Add support for decimal units
420
421 // Date/Time separator
422 if self.current != 'T' && self.current != ' ' && !skip_hour {
423 return Err(self.parse_error(format!(
424 "Invalid character \"{}\" while parsing {}",
425 self.current, "date and time separator (\"T\" or \" \")"
426 )));
427 }
428
429 datetime.has_time = true;
430
431 if !skip_hour {
432 self.inc();
433
434 // Hour
435 datetime.hour = self.parse_integer(2, "hour")?;
436 }
437
438 if !self.end() && self.current != 'Z' && self.current != '+' && self.current != '-' {
439 // Optional minute and second
440 if self.current == ':' {
441 // Minute and second in extended format (mm:ss)
442 self.inc();
443
444 // Minute
445 datetime.minute = self.parse_integer(2, "minute")?;
446
447 if !self.end() && self.current != 'Z' && self.current != '+' && self.current != '-'
448 {
449 // Optional second
450 if self.current != ':' {
451 return Err(self.parse_error(format!(
452 "Invalid character \"{}\" while parsing {}",
453 self.current, "time separator (\":\")"
454 )));
455 }
456
457 self.inc();
458
459 // Second
460 datetime.second = self.parse_integer(2, "second")?;
461
462 if self.current == '.' || self.current == ',' {
463 // Optional fractional second
464 self.inc();
465
466 datetime.microsecond = 0;
467 let mut i: u8 = 0;
468
469 while i < 6 {
470 if let Some(digit) = self.current.to_digit(10) {
471 datetime.microsecond = datetime.microsecond * 10 + digit;
472 } else if i == 0 {
473 // One digit minimum is required
474 return Err(self.unexpected_character_error("subsecond", 1));
475 } else {
476 break;
477 }
478
479 self.inc();
480 i += 1;
481 }
482
483 // Drop extraneous digits
484 while self.current.is_ascii_digit() {
485 self.inc();
486 }
487
488 // Expand missing microsecond
489 while i < 6 {
490 datetime.microsecond *= 10;
491 i += 1;
492 }
493 }
494
495 if !datetime.extended_date_format {
496 return Err(self.parse_error("Cannot combine \"basic\" date format with \"extended\" time format (Should be either `YYYY-MM-DDThh:mm:ss` or `YYYYMMDDThhmmss`).".to_string()));
497 }
498 }
499 } else {
500 // Minute and second in compact format (mmss)
501
502 // Minute
503 datetime.minute = self.parse_integer(2, "minute")?;
504
505 if !self.end() && self.current != 'Z' && self.current != '+' && self.current != '-'
506 {
507 // Optional second
508
509 datetime.second = self.parse_integer(2, "second")?;
510
511 if self.current == '.' || self.current == ',' {
512 // Optional fractional second
513 self.inc();
514
515 datetime.microsecond = 0;
516 let mut i: u8 = 0;
517
518 while i < 6 {
519 if let Some(digit) = self.current.to_digit(10) {
520 datetime.microsecond = datetime.microsecond * 10 + digit;
521 } else if i == 0 {
522 // One digit minimum is required
523 return Err(self.unexpected_character_error("subsecond", 1));
524 } else {
525 break;
526 }
527
528 self.inc();
529 i += 1;
530 }
531
532 // Drop extraneous digits
533 while self.current.is_ascii_digit() {
534 self.inc();
535 }
536
537 // Expand missing microsecond
538 while i < 6 {
539 datetime.microsecond *= 10;
540 i += 1;
541 }
542 }
543 }
544
545 if datetime.extended_date_format {
546 return Err(self.parse_error("Cannot combine \"extended\" date format with \"basic\" time format (Should be either `YYYY-MM-DDThh:mm:ss` or `YYYYMMDDThhmmss`).".to_string()));
547 }
548 }
549 }
550
551 if datetime.hour == 24
552 && datetime.minute == 0
553 && datetime.second == 0
554 && datetime.microsecond == 0
555 {
556 // Special case for 24:00:00, which is valid for ISO 8601.
557 // This is equivalent to 00:00:00 the next day.
558 // We will store the information for now.
559 datetime.time_is_midnight = true;
560 }
561
562 if self.current == 'Z' {
563 // UTC
564 datetime.offset = Some(0);
565 datetime.tzname = Some("UTC".to_string());
566 self.inc();
567 } else if matches!(self.current, '+' | '-') {
568 // Optional timezone offset
569 let tzsign = if self.current == '+' { 1 } else { -1 };
570 self.inc();
571 // Offset hour
572 let tzhour = self.parse_integer(2, "timezone hour")? as i32;
573 if self.current == ':' {
574 // Optional separator
575 self.inc();
576 }
577 let mut tzminute = if self.end() {
578 0
579 } else {
580 // Optional minute
581 self.parse_integer(2, "timezone minute")? as i32
582 };
583 tzminute += tzhour * 60;
584 tzminute *= tzsign;
585 if tzminute > 24 * 60 {
586 return Err(self.parse_error("Timezone offset is too large".to_string()));
587 }
588 datetime.offset = Some(tzminute * 60);
589 }
590
591 Ok(())
592 }
593
594 fn parse_duration(&mut self, parsed: &mut Parsed) -> Result<(), ParseError> {
595 // Removing P operator
596 self.inc();
597
598 let mut duration: ParsedDuration = ParsedDuration::new();
599 let mut got_t: bool = false;
600 let mut last_had_fraction = false;
601
602 loop {
603 match self.current {
604 'T' => {
605 if got_t {
606 return Err(
607 self.parse_error("Repeated time declaration in duration".to_string())
608 );
609 }
610
611 got_t = true;
612 }
613 _c => {
614 let (value, op_fraction) = self.parse_duration_number_frac()?;
615 if last_had_fraction {
616 return Err(self.parse_error("Invalid duration fraction".to_string()));
617 }
618
619 if op_fraction.is_some() {
620 last_had_fraction = true;
621 }
622
623 if got_t {
624 match self.current {
625 'H' => {
626 if duration.minutes != 0
627 || duration.seconds != 0
628 || duration.microseconds != 0
629 {
630 return Err(
631 self.parse_error("Duration units out of order".to_string())
632 );
633 }
634
635 duration.hours += value;
636
637 if let Some(fraction) = op_fraction {
638 let extra_minutes = fraction * 60_f64;
639 let extra_full_minutes: f64 = extra_minutes.trunc();
640 duration.minutes += extra_full_minutes as u32;
641 let extra_seconds =
642 ((extra_minutes - extra_full_minutes) * 60.0).round();
643 let extra_full_seconds = extra_seconds.trunc();
644 duration.seconds += extra_full_seconds as u32;
645 let micro_extra = ((extra_seconds - extra_full_seconds)
646 * 1_000_000.0)
647 .round()
648 as u32;
649 duration.microseconds += micro_extra;
650 }
651 }
652 'M' => {
653 if duration.seconds != 0 || duration.microseconds != 0 {
654 return Err(
655 self.parse_error("Duration units out of order".to_string())
656 );
657 }
658
659 duration.minutes += value;
660
661 if let Some(fraction) = op_fraction {
662 let extra_seconds = fraction * 60_f64;
663 let extra_full_seconds = extra_seconds.trunc();
664 duration.seconds += extra_full_seconds as u32;
665 let micro_extra = ((extra_seconds - extra_full_seconds)
666 * 1_000_000.0)
667 .round()
668 as u32;
669 duration.microseconds += micro_extra;
670 }
671 }
672 'S' => {
673 duration.seconds = value;
674
675 if let Some(fraction) = op_fraction {
676 duration.microseconds +=
677 (fraction * 1_000_000.0).round() as u32;
678 }
679 }
680 _ => {
681 return Err(
682 self.parse_error("Invalid duration time unit".to_string())
683 )
684 }
685 }
686 } else {
687 match self.current {
688 'Y' => {
689 if last_had_fraction {
690 return Err(self.parse_error(
691 "Fractional years in duration are not supported"
692 .to_string(),
693 ));
694 }
695
696 if duration.months != 0 || duration.days != 0 {
697 return Err(
698 self.parse_error("Duration units out of order".to_string())
699 );
700 }
701
702 duration.years = value;
703 }
704 'M' => {
705 if last_had_fraction {
706 return Err(self.parse_error(
707 "Fractional months in duration are not supported"
708 .to_string(),
709 ));
710 }
711
712 if duration.days != 0 {
713 return Err(
714 self.parse_error("Duration units out of order".to_string())
715 );
716 }
717
718 duration.months = value;
719 }
720 'W' => {
721 if duration.years != 0 || duration.months != 0 {
722 return Err(self.parse_error(
723 "Basic format durations cannot have weeks".to_string(),
724 ));
725 }
726
727 duration.weeks = value;
728
729 if let Some(fraction) = op_fraction {
730 let extra_days = fraction * 7_f64;
731 let extra_full_days = extra_days.trunc();
732 duration.days += extra_full_days as u32;
733 let extra_hours = (extra_days - extra_full_days) * 24.0;
734 let extra_full_hours = extra_hours.trunc();
735 duration.hours += extra_full_hours as u32;
736 let extra_minutes =
737 ((extra_hours - extra_full_hours) * 60.0).round();
738 let extra_full_minutes: f64 = extra_minutes.trunc();
739 duration.minutes += extra_full_minutes as u32;
740 let extra_seconds =
741 ((extra_minutes - extra_full_minutes) * 60.0).round();
742 let extra_full_seconds = extra_seconds.trunc();
743 duration.seconds += extra_full_seconds as u32;
744 let micro_extra = ((extra_seconds - extra_full_seconds)
745 * 1_000_000.0)
746 .round()
747 as u32;
748 duration.microseconds += micro_extra;
749 }
750 }
751 'D' => {
752 if duration.weeks != 0 {
753 return Err(self.parse_error(
754 "Week format durations cannot have days".to_string(),
755 ));
756 }
757
758 duration.days += value;
759 if let Some(fraction) = op_fraction {
760 let extra_hours = fraction * 24.0;
761 let extra_full_hours = extra_hours.trunc();
762 duration.hours += extra_full_hours as u32;
763 let extra_minutes =
764 ((extra_hours - extra_full_hours) * 60.0).round();
765 let extra_full_minutes: f64 = extra_minutes.trunc();
766 duration.minutes += extra_full_minutes as u32;
767 let extra_seconds =
768 ((extra_minutes - extra_full_minutes) * 60.0).round();
769 let extra_full_seconds = extra_seconds.trunc();
770 duration.seconds += extra_full_seconds as u32;
771 let micro_extra = ((extra_seconds - extra_full_seconds)
772 * 1_000_000.0)
773 .round()
774 as u32;
775 duration.microseconds += micro_extra;
776 }
777 }
778 _ => {
779 return Err(
780 self.parse_error("Invalid duration time unit".to_string())
781 )
782 }
783 }
784 }
785 }
786 }
787 self.inc();
788
789 if self.end() {
790 break;
791 }
792 }
793
794 parsed.duration = Some(duration);
795
796 Ok(())
797 }
798
799 fn parse_duration_number_frac(&mut self) -> Result<(u32, Option<f64>), ParseError> {
800 let value = self.parse_duration_number()?;
801 let fraction = matches!(self.current, '.' | ',').then(|| {
802 let mut decimal = 0_f64;
803 let mut denominator = 1_f64;
804
805 while let Some(digit) = self.inc().and_then(|ch| ch.to_digit(10)) {
806 decimal *= 10.0;
807 decimal += f64::from(digit);
808 denominator *= 10.0;
809 }
810
811 decimal / denominator
812 });
813
814 Ok((value, fraction))
815 }
816
817 fn parse_duration_number(&mut self) -> Result<u32, ParseError> {
818 let Some(mut value) = self.current.to_digit(10) else {
819 return Err(self.parse_error("Invalid number in duration".to_string()));
820 };
821
822 while let Some(digit) = self.inc().and_then(|ch| ch.to_digit(10)) {
823 value *= 10;
824 value += digit;
825 }
826
827 Ok(value)
828 }
829
830 fn iso_to_ymd(
831 &mut self,
832 iso_year: u32,
833 iso_week: u32,
834 iso_day: u32,
835 ) -> Result<(u32, u32, u32), ParseError> {
836 if iso_week > 53 || iso_week > 52 && !is_long_year(iso_year as i32) {
837 return Err(ParseError {
838 index: self.idx,
839 message: format!(
840 "Invalid ISO date: week {iso_week} out of range for year {iso_year}"
841 ),
842 });
843 }
844
845 if iso_day > 7 {
846 return Err(ParseError {
847 index: self.idx,
848 message: "Invalid ISO date: week day is invalid".to_string(),
849 });
850 }
851
852 let ordinal: i32 =
853 iso_week as i32 * 7 + iso_day as i32 - (week_day(iso_year as i32, 1, 4) as i32 + 3);
854
855 self.ordinal_to_ymd(iso_year, ordinal, true)
856 }
857
858 fn ordinal_to_ymd(
859 &mut self,
860 year: u32,
861 ordinal: i32,
862 allow_out_of_bounds: bool,
863 ) -> Result<(u32, u32, u32), ParseError> {
864 let mut ord: i32 = ordinal;
865 let mut y: u32 = year;
866 let mut leap: usize = usize::from(is_leap(y as i32));
867
868 if ord < 1 {
869 if !allow_out_of_bounds {
870 return Err(self.parse_error(format!(
871 "Invalid ordinal day: {ordinal} is too small for year {year}"
872 )));
873 }
874 // Previous year
875 ord += days_in_year((year - 1) as i32) as i32;
876 y -= 1;
877 leap = usize::from(is_leap(y as i32));
878 }
879
880 if ord > days_in_year(y as i32) as i32 {
881 if !allow_out_of_bounds {
882 return Err(self.parse_error(format!(
883 "Invalid ordinal day: {ordinal} is too large for year {year}"
884 )));
885 }
886
887 // Next year
888 ord -= days_in_year(y as i32) as i32;
889 y += 1;
890 leap = usize::from(is_leap(y as i32));
891 }
892
893 for i in 1..14 {
894 if ord <= MONTHS_OFFSETS[leap][i] {
895 let day = ord as u32 - MONTHS_OFFSETS[leap][i - 1] as u32;
896 let month = (i - 1) as u32;
897
898 return Ok((y, month, day));
899 }
900 }
901
902 Err(self.parse_error(format!(
903 "Invalid ordinal day: {ordinal} is too large for year {year}"
904 )))
905 }
906 }