trivet 3.1.0

The trivet Parser Library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
// Trivet
// Copyright (c) 2025 by Stacy Prowell.  All rights reserved.
// https://gitlab.com/binary-tools/trivet

//! Parse and generate date and time expressions based on [RFC 3339](https://datatracker.ietf.org/doc/html/rfc3339).
//! This is a profile of [ISO 8601](https://www.iso.org/standard/70908.html).  Do you like Venn diagrams?
//! Visit [here](https://ijmacd.github.io/rfc3339-iso8601/) for the ISO 8601 and RFC 3339 Venn diagram.
//!
//! You are encouraged to see the [chrono](https://crates.io/crates/chrono) package for time and date routines.
//! Because **Trivet** is intended to have no dependencies, `chrono` is not included here.  However, effort
//! has been made to make integration with `chrono` simple.
//!
//! ```text
//!    date-fullyear   = 4DIGIT
//!    date-month      = 2DIGIT  ; 01-12
//!    date-mday       = 2DIGIT  ; 01-28, 01-29, 01-30, 01-31 based on
//!                              ; month/year
//!    time-hour       = 2DIGIT  ; 00-23
//!    time-minute     = 2DIGIT  ; 00-59
//!    time-second     = 2DIGIT  ; 00-58, 00-59, 00-60 based on leap second
//!                              ; rules
//!    time-secfrac    = "." 1*DIGIT
//!    time-numoffset  = ("+" / "-") time-hour ":" time-minute
//!    time-offset     = "Z" / time-numoffset
//!
//!    partial-time    = time-hour ":" time-minute ":" time-second
//!                      [time-secfrac]
//!    full-date       = date-fullyear "-" date-month "-" date-mday
//!    full-time       = partial-time time-offset
//!
//!    date-time       = full-date "T" full-time
//! ```
//!
//! A space can be used between a date and time, as allowed by RFC 3339.  This parser does not
//! check the leap second or the time offset.

use std::fmt::{Display, Formatter};

use crate::{
    errors::{syntax_error, ParseResult},
    Parser,
};

/// Package a possible date/time combination.
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum DateTime {
    /// Date without corresponding time.
    Date(Date),
    /// Time without corresponding date.
    Time(Time),
    /// Both date and time.
    DateTime(Date, Time),
}

impl Display for DateTime {
    fn fmt(&self, form: &mut Formatter) -> std::fmt::Result {
        match self {
            Self::Date(date) => write!(form, "{}", date),
            Self::Time(time) => write!(form, "{}", time),
            Self::DateTime(date, time) => write!(form, "{}T{}", date, time),
        }
    }
}

/// Specify a time offset.  This essentially encodes a timezone with respect to UTC, so (for instance)
/// New York City is UTC-4, giving an offset of `TimeOffset::Offset { plus: false, hours: 4, minutes: 0 }`.
/// Note that UTC itself is `TimeOffset::Offset { plus: true, hours: 0, minutes: 0 }`.
///
/// [`TimeOffset::Local`] specifies that the time is given without respect to UTC. This is outside the
/// scope of RFC 3339, but is included here for its utility.
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum TimeOffset {
    /// Specify local time without reference to UTC.
    Local,

    /// Specify a time zone by giving the offset from UTC.  For example, eastern time in the United
    /// States is UTC-4.
    Offset {
        /// If true, the offset is added.  If false, the offset is subtracted.
        plus: bool,
        /// Offset hours.
        hours: u32,
        /// Offset minutes.
        minutes: u32,
    },
}

impl Display for TimeOffset {
    fn fmt(&self, form: &mut Formatter) -> std::fmt::Result {
        if let Self::Offset {
            plus,
            hours,
            minutes,
        } = self
        {
            if *hours == 0 && *minutes == 0 {
                write!(form, "Z")
            } else if *plus {
                write!(form, "+{:02}:{:02}", hours, minutes)
            } else {
                write!(form, "-{:02}:{:02}", hours, minutes)
            }
        } else {
            write!(form, "")
        }
    }
}

/// Specify a fraction of a second to a defined resolution.
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum SecondsFraction {
    None,
    Milliseconds(u32),
    Microseconds(u32),
    Nanoseconds(u32),
}

impl Display for SecondsFraction {
    fn fmt(&self, form: &mut Formatter) -> std::fmt::Result {
        match self {
            Self::None => write!(form, ""),
            Self::Milliseconds(millis) => write!(form, ".{:03}", millis),
            Self::Microseconds(micros) => write!(form, ".{:06}", micros),
            Self::Nanoseconds(nanos) => write!(form, ".{:09}", nanos),
        }
    }
}

/// Specify a date.
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct Date {
    /// The nonnegative year (CE only).
    pub year: u32,
    /// A month in the range [1..12].
    pub month: u32,
    /// A day of the month in one of the ranges [1..28], [1..29], [1..30], or [1..31], depending.
    pub day: u32,
}

impl Display for Date {
    fn fmt(&self, form: &mut Formatter) -> std::fmt::Result {
        write!(form, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
    }
}

/// Specify a time.
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct Time {
    /// The hour in the range [0..23].
    pub hour: u32,
    /// The minute in the range [0..59].
    pub minute: u32,
    /// The second in the range [0..60].  This range allows for the specification of a leap-second.
    pub second: u32,
    /// A fraction of a second.
    pub fraction: SecondsFraction,
    /// A time offset with respect to UTC.
    pub offset: TimeOffset,
}

impl Display for Time {
    fn fmt(&self, form: &mut Formatter) -> std::fmt::Result {
        write!(
            form,
            "{:02}:{:02}:{:02}{}{}",
            self.hour, self.minute, self.second, self.fraction, self.offset
        )
    }
}

/// Parse a fixed-length sequence of ASCII digits from the stream.  The return is
/// checked against the provided range and, if outside the range, an error is
/// generated.
///
/// If a non-digit or the end of stream is encountered, an error is generated.
fn parse_fixed_number(parser: &mut Parser, digits: usize) -> ParseResult<u32> {
    let mut value = 0;
    for _ in 0..digits {
        if parser.is_at_eof() {
            return Err(syntax_error(
                parser.loc(),
                "Expected a digit but reached end of stream.",
            ));
        }
        let ch = parser.peek();
        if !ch.is_ascii_digit() {
            return Err(syntax_error(
                parser.loc(),
                &format!("Expected a digit but found {:?} instead.", ch),
            ));
        }
        parser.consume();
        value *= 10;
        value += (ch as u32) - ('0' as u32);
    }
    Ok(value)
}

/// Parse a date from the stream.  On entry the parser is expected to be at the first character
/// of the date.
fn parse_date(parser: &mut Parser) -> ParseResult<Date> {
    // Parse the date parts.
    let year = parse_fixed_number(parser, 4)?;
    parser.expect('-')?;
    let month_loc = parser.loc();
    let month = parse_fixed_number(parser, 2)?;
    parser.expect('-')?;
    let day_loc = parser.loc();
    let day = parse_fixed_number(parser, 2)?;

    // Validate the date parts.
    if !(1..=12).contains(&month) {
        return Err(syntax_error(
            month_loc,
            &format!(
                "Month value {} is out of range; it must be in [1..12].",
                month
            ),
        ));
    }
    if !(1..=31).contains(&day) {
        return Err(syntax_error(
            day_loc,
            &format!("The day index {} is out of range for month {}.", day, month),
        ));
    }
    match month {
        4 | 6 | 9 | 11 => {
            if day > 30 {
                return Err(syntax_error(
                    day_loc,
                    &format!("The day index {} is out of range for month {}.", day, month),
                ));
            }
        }
        2 => {
            if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) {
                // Leap year.
                if day > 29 {
                    return Err(syntax_error(
                        day_loc,
                        &format!("The day index {} is out of range for month {}.", day, month),
                    ));
                }
            } else {
                // Not leap year.
                if day > 28 {
                    return Err(syntax_error(
                        day_loc,
                        &format!("The day index {} is out of range for month {}.", day, month),
                    ));
                }
            }
        }
        _ => {}
    }
    if ['+', '-'].contains(&parser.peek()) {
        return Err(syntax_error(
            parser.loc(),
            &format!(
                "Found unexpected character {:?} at end of date string.",
                parser.peek()
            ),
        ));
    }
    if ![' ', 'T', 't'].contains(&parser.peek()) && parser.peek().is_ascii_alphanumeric() {
        return Err(syntax_error(
            parser.loc(),
            &format!(
                "Found unexpected character {:?} at end of date string.",
                parser.peek()
            ),
        ));
    }

    Ok(Date { year, month, day })
}

/// Parse a time expression from the stream.  On entry the parser is assumed to be at the first
/// digit of the time expression.  This method halts parsing if a comma is used as a fraction
/// separator, but does generate an error if a fractional hour or minute is attempted.
fn parse_time(parser: &mut Parser) -> ParseResult<Time> {
    // Parse the time parts.
    let hour_loc = parser.loc();
    let hour = parse_fixed_number(parser, 2)?;
    if parser.peek() == '.' {
        return Err(syntax_error(
            parser.loc(),
            "Fractional hours are not permitted.",
        ));
    }
    parser.expect(':')?;
    let minute_loc = parser.loc();
    let minute = parse_fixed_number(parser, 2)?;
    if parser.peek() == '.' {
        return Err(syntax_error(
            parser.loc(),
            "Fractional minutes are not permitted.",
        ));
    }
    let (second, fraction, second_loc) = if parser.peek_and_consume(':') {
        let second_loc = parser.loc();
        let second = parse_fixed_number(parser, 2)?;
        let (mut fraction, mut fraction_digits) = if parser.peek_and_consume('.') {
            // Parse the second fraction.
            let fraction_loc = parser.loc();
            let digits = parser.take_while(|ch| ch.is_ascii_digit());
            if digits.is_empty() {
                return Err(syntax_error(
                    fraction_loc,
                    "Expected digits following decimal point (fractional seconds), but did not find any."
                ));
            }

            // We permit at most nanosecond resolution.
            // T.001 (millisecond)
            // T.000001 (microsecond)
            // T.000000001 (nanosecond)
            if digits.len() > 9 {
                // The resolution is higher than nanosecond.  Round to nanosecond.
                let chars: Vec<char> = digits.chars().collect();
                let pivot = chars[9];
                let digits = chars[0..9].iter().collect::<String>();
                let mut value = digits.parse::<u32>().unwrap_or(0);
                if ('5'..='9').contains(&pivot) {
                    value += 1;
                }
                (value, digits.len())
            } else {
                (digits.parse::<u32>().unwrap_or(0), digits.len())
            }
        } else {
            (0, 0)
        };
        while fraction_digits % 3 != 0 {
            fraction_digits += 1;
            fraction *= 10;
        }
        let fraction = if fraction_digits == 0 {
            SecondsFraction::None
        } else if fraction_digits == 3 {
            SecondsFraction::Milliseconds(fraction)
        } else if fraction_digits == 6 {
            SecondsFraction::Microseconds(fraction)
        } else {
            SecondsFraction::Nanoseconds(fraction)
        };
        (second, fraction, second_loc)
    } else {
        (0, SecondsFraction::None, parser.loc())
    };
    let offset = if parser.peek_and_consume('Z') || parser.peek_and_consume('z') {
        TimeOffset::Offset {
            plus: true,
            hours: 0,
            minutes: 0,
        }
    } else if parser.peek_and_consume('+') {
        let hours = parse_fixed_number(parser, 2)?;
        parser.expect(':')?;
        let minutes = parse_fixed_number(parser, 2)?;
        TimeOffset::Offset {
            plus: true,
            hours,
            minutes,
        }
    } else if parser.peek_and_consume('-') {
        let hours = parse_fixed_number(parser, 2)?;
        parser.expect(':')?;
        let minutes = parse_fixed_number(parser, 2)?;
        TimeOffset::Offset {
            plus: false,
            hours,
            minutes,
        }
    } else if parser.peek().is_alphanumeric() {
        return Err(syntax_error(
            parser.loc(),
            &format!(
                "Found unexpected character {:?} at end of time string.",
                parser.peek()
            ),
        ));
    } else {
        TimeOffset::Local
    };
    if !(0..=23).contains(&hour) {
        return Err(syntax_error(
            hour_loc,
            &format!(
                "Hour value {:02} is out of the allowed range [00..23].",
                hour
            ),
        ));
    }
    if !(0..=59).contains(&minute) {
        return Err(syntax_error(
            minute_loc,
            &format!(
                "Minute value {:02} is out of the allowed range [00..59].",
                hour
            ),
        ));
    }
    if !(0..=60).contains(&second) {
        return Err(syntax_error(
            second_loc,
            &format!(
                "Second value {:02} is out of the allowed range [00..59].",
                hour
            ),
        ));
    }
    Ok(Time {
        hour,
        minute,
        second,
        fraction,
        offset,
    })
}

/// Check to see if the next characters in the stream are likely a date.
pub fn is_date(parser: &mut Parser) -> bool {
    let look = parser.peek_n_vec(10);
    look.len() == 10
        && look[0].is_ascii_digit()
        && look[1].is_ascii_digit()
        && look[2].is_ascii_digit()
        && look[3].is_ascii_digit()
        && look[4] == '-'
        && look[5].is_ascii_digit()
        && look[6].is_ascii_digit()
        && look[7] == '-'
        && look[8].is_ascii_digit()
        && look[9].is_ascii_digit()
}

/// Check to see if the next characters in the stream are likely a time.
pub fn is_time(parser: &mut Parser) -> bool {
    let look = parser.peek_n_vec(8);
    look.len() >= 5
        && look[0].is_ascii_digit()
        && look[1].is_ascii_digit()
        && look[2] == ':'
        && look[3].is_ascii_digit()
        && look[4].is_ascii_digit()
}

/// Parse a date/time expression.  This can be a date with a time, a date without a time, or a time
/// without a date.  On entry the parser is expected to be at the first character of the date or time.
///
/// If the stream does not appear to contain a date or time, then `None` is returned.  Otherwise
/// parsing is attempted and may result in a parse error.
pub fn parse_date_time(parser: &mut Parser) -> ParseResult<Option<DateTime>> {
    if is_date(parser) {
        let date = parse_date(parser)?;
        if parser.peek_and_consume('T')
            || parser.peek_and_consume('t')
            || (parser.peek_and_consume(' ') && is_time(parser))
        {
            let time = parse_time(parser)?;
            Ok(Some(DateTime::DateTime(date, time)))
        } else {
            Ok(Some(DateTime::Date(date)))
        }
    } else if is_time(parser) {
        let time = parse_time(parser)?;
        Ok(Some(DateTime::Time(time)))
    } else {
        Ok(None)
    }
}

#[cfg(test)]
mod test {
    use super::parse_date;
    use crate::errors::ParseResult;
    use crate::parse_from_string;
    use crate::parsers::datetime::{
        parse_date_time, parse_time, Date, DateTime, SecondsFraction, Time, TimeOffset,
    };

    #[test]
    fn test_dates() -> ParseResult<()> {
        let mut parser = parse_from_string("1999-01-01");
        assert_eq!(
            parse_date(&mut parser)?,
            Date {
                year: 1999,
                month: 1,
                day: 1
            }
        );

        parser = parse_from_string("2024-12-31");
        assert_eq!(
            parse_date(&mut parser)?,
            Date {
                year: 2024,
                month: 12,
                day: 31
            }
        );

        parser = parse_from_string("2233-03-22");
        assert_eq!(
            parse_date(&mut parser)?,
            Date {
                year: 2233,
                month: 3,
                day: 22
            }
        );

        parser = parse_from_string("2016-01-06");
        assert_eq!(
            parse_date(&mut parser)?,
            Date {
                year: 2016,
                month: 1,
                day: 6
            }
        );

        parser = parse_from_string("0001-12-24");
        assert_eq!(
            parse_date(&mut parser)?,
            Date {
                year: 1,
                month: 12,
                day: 24
            }
        );

        parser = parse_from_string("2031-07-03");
        assert_eq!(
            parse_date(&mut parser)?,
            Date {
                year: 2031,
                month: 7,
                day: 3
            }
        );

        parser = parse_from_string("2032-07-04");
        assert_eq!(
            parse_date(&mut parser)?,
            Date {
                year: 2032,
                month: 7,
                day: 4
            }
        );

        parser = parse_from_string("2004-02-29");
        assert_eq!(
            parse_date(&mut parser)?,
            Date {
                year: 2004,
                month: 2,
                day: 29
            }
        );

        parser = parse_from_string("9999-12-31");
        assert_eq!(
            parse_date(&mut parser)?,
            Date {
                year: 9999,
                month: 12,
                day: 31
            }
        );

        parser = parse_from_string("1900-02-29");
        assert!(parse_date(&mut parser).is_err());

        parser = parse_from_string("2001-04-31");
        assert!(parse_date(&mut parser).is_err());
        Ok(())
    }

    #[test]
    fn test_times() -> ParseResult<()> {
        let mut parser = parse_from_string("06:17:22");
        assert_eq!(
            parse_time(&mut parser)?,
            Time {
                hour: 6,
                minute: 17,
                second: 22,
                fraction: SecondsFraction::None,
                offset: TimeOffset::Local
            }
        );

        parser = parse_from_string("12:59:59.1Z");
        assert_eq!(
            parse_time(&mut parser)?,
            Time {
                hour: 12,
                minute: 59,
                second: 59,
                fraction: SecondsFraction::Milliseconds(100),
                offset: TimeOffset::Offset {
                    plus: true,
                    hours: 0,
                    minutes: 0
                }
            }
        );

        parser = parse_from_string("12:59:20.000126+02:00");
        assert_eq!(
            parse_time(&mut parser)?,
            Time {
                hour: 12,
                minute: 59,
                second: 20,
                fraction: SecondsFraction::Microseconds(126),
                offset: TimeOffset::Offset {
                    plus: true,
                    hours: 2,
                    minutes: 0
                }
            }
        );

        parser = parse_from_string("23:57:00.000126000-04:00");
        assert_eq!(
            parse_time(&mut parser)?,
            Time {
                hour: 23,
                minute: 57,
                second: 00,
                fraction: SecondsFraction::Nanoseconds(126000),
                offset: TimeOffset::Offset {
                    plus: false,
                    hours: 4,
                    minutes: 0
                }
            }
        );

        Ok(())
    }

    #[test]
    fn test_date_time() -> ParseResult<()> {
        let mut parser = parse_from_string("1999-01-01T16:45:20Z");
        assert_eq!(
            parse_date_time(&mut parser)?,
            Some(DateTime::DateTime(
                Date {
                    year: 1999,
                    month: 1,
                    day: 1
                },
                Time {
                    hour: 16,
                    minute: 45,
                    second: 20,
                    fraction: SecondsFraction::None,
                    offset: TimeOffset::Offset {
                        plus: true,
                        hours: 0,
                        minutes: 0
                    }
                }
            ))
        );

        parser = parse_from_string("2024-12-31 12:59:59.100");
        assert_eq!(
            parse_date_time(&mut parser)?,
            Some(DateTime::DateTime(
                Date {
                    year: 2024,
                    month: 12,
                    day: 31
                },
                Time {
                    hour: 12,
                    minute: 59,
                    second: 59,
                    fraction: SecondsFraction::Milliseconds(100),
                    offset: TimeOffset::Local
                }
            ))
        );

        Ok(())
    }

    #[test]
    fn test_circular() -> ParseResult<()> {
        // The test cases here are taken from:
        // https://tc39.es/proposal-uniform-interchange-date-parsing/cases.html
        let tests = [
            // Positive leap second.
            ("1972-06-30T23:59:60Z", "1972-06-30T23:59:60Z"),
            // Too few fractional second digits.
            ("2019-03-26T14:00:00.9Z", "2019-03-26T14:00:00.900Z"),
            // Too many fractional second digits
            ("2019-03-26T14:00:00.4999Z", "2019-03-26T14:00:00.499900Z"),
            // Too many fractional second digits (pre-epoch)
            ("1969-03-26T14:00:00.4999Z", "1969-03-26T14:00:00.499900Z"),
            // Lowercase time designator
            ("2019-03-26t14:00Z", "2019-03-26T14:00:00Z"),
            // Lowercase UTC designator
            ("2019-03-26T14:00z", "2019-03-26T14:00:00Z"),
            // Comma as decimal sign
            ("2019-03-26T14:00:00,999Z", "2019-03-26T14:00:00"),
            // Space as time designator
            ("2019-03-26 14:00Z", "2019-03-26T14:00:00Z"),
            // Everything from here down should be rejected ("") or not recognized ("*").

            // Hours-only offset
            ("2019-03-26T10:00-04", ""),
            // Fractional minutes
            ("2019-03-26T14:00.9Z", ""),
            // ISO basic format date and time
            ("20190326T1400Z", "*"), // This is not recognized by lookahead.
            // Out-of-bounds day of month
            ("2019-02-30", ""),
            // Time past end of day
            ("2019-03-25T24:01Z", ""),
            // Zero UTC offset without time elements
            ("2019-03-26Z", ""),
            // Positive UTC offset without time elements
            ("2019-03-26+01:00", ""),
            // Negative UTC offset without time elements
            ("2019-03-26-04:00", ""),
            // ISO basic format UTC offset
            ("2019-03-26T10:00-0400", ""),
            // Too many unsigned year digits
            ("002019-03-26T14:00Z", "*"), // This is not recognized by lookahead.
            // Too few unsigned year digits
            ("019-03-26T14:00Z", "*"), // This is not recognized by lookahead.
            // Non-Z “military” designation letter offset
            ("2019-03-26T10:00Q", ""),
            // Hazardous non-Z “military” designation letter offset
            ("2019-03-26T10:00T", ""),
            // Non-Z “military” designation letter offset without time elements
            ("2019-03-26Q", ""),
            // Hazardous non-Z “military” designation letter offset without time elements
            ("2019-03-26T", ""),
            // No digits after decimal sign
            ("2019-03-26T14:00:00.", ""),
            // These should be rejected, but are accepted by the parser.

            // UTC offset too large
            ("2019-03-26T14:00+24:00", "2019-03-26T14:00:00+24:00"),
            // Unused leap second opportunity
            ("2018-06-30T23:59:60Z", "2018-06-30T23:59:60Z"),
            // Bogus leap second (not at end of month)
            ("2019-03-26T23:59:60Z", "2019-03-26T23:59:60Z"),
            // Really bogus leap second (not even at end of UTC day)
            ("2019-03-26T13:59:60Z", "2019-03-26T13:59:60Z"),
            // Dates without times.
            ("1922-09-12", "1922-09-12"),
            ("1924-03-24", "1924-03-24"),
            // Times without dates.
            ("03:00", "03:00:00"),
            ("03:30:00", "03:30:00"),
            ("03:30:33.3", "03:30:33.300"),
            ("03:30:33.3033", "03:30:33.303300"),
            ("03:30:33.3300333", "03:30:33.330033300"),
            ("03:30:33.3300333336", "03:30:33.330033334"), // These three cases test rounding.
            ("03:30:33.3300333335", "03:30:33.330033334"),
            ("03:30:33.3300333334", "03:30:33.330033333"),
            ("03:30:33+02:00", "03:30:33+02:00"),
            ("03:30:33-02:30", "03:30:33-02:30"),
            // A few additional error conditions.
            ("1900-02-29", ""),
            ("2000-02-30", ""),
            ("2000-02-29", "2000-02-29"),
            ("1968-04-31", ""),
            ("1200-12-99", ""),
            ("1200-99-31", ""),
            ("12:31:5Z", ""),
            ("12:31:61", ""),
            ("12:60:59", ""),
            ("24:59:59", ""),
            // Fragments that should not parse.
            ("1", "X"),
            ("1900-", "X"),
            ("T13:02", "X"),
        ];
        for (input, output) in tests {
            print!("Trying string {:?}... ", input);
            let mut parser = parse_from_string(input);
            if output.is_empty() {
                assert!(parse_date_time(&mut parser).is_err());
            } else if output == "X" {
                assert_eq!(parse_date_time(&mut parser).unwrap(), None);
            } else {
                let result = parse_date_time(&mut parser)?;
                match result {
                    None => assert!(output == "*"),
                    Some(dt) => assert_eq!(dt.to_string(), output),
                }
            }
            println!("Done");
        }

        Ok(())
    }

    #[test]
    fn forced_errors_test() {
        let mut parser = parse_from_string("1X99-01-01");
        assert!(parse_date(&mut parser).is_err());
        let mut parser = parse_from_string("1299-X1-01");
        assert!(parse_date(&mut parser).is_err());
        let mut parser = parse_from_string("1299-01-X1");
        assert!(parse_date(&mut parser).is_err());
        let mut parser = parse_from_string("03.5:01:01");
        assert!(parse_time(&mut parser).is_err());
        let mut parser = parse_from_string("03:01.5:01");
        assert!(parse_time(&mut parser).is_err());
        let mut parser = parse_from_string("199912-23");
        assert!(parse_date(&mut parser).is_err());
        let mut parser = parse_from_string("1999-1223");
        assert!(parse_date(&mut parser).is_err());
        let mut parser = parse_from_string("03:21:45+0100");
        assert!(parse_time(&mut parser).is_err());
    }
}