ixdtf 0.6.5

Parser for Internet eXtended DateTime Format
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
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

//! The parser module contains the implementation details for `IxdtfParser` and `IsoDurationParser`

use crate::core::Cursor;
use crate::encoding::{EncodingType, Utf16, Utf8};
use crate::ParserResult;

#[cfg(feature = "duration")]
use crate::records::DurationParseRecord;
use crate::records::{IxdtfParseRecord, TimeZoneRecord, UtcOffsetRecord};

use crate::records::Annotation;

mod annotations;
pub(crate) mod datetime;
#[cfg(feature = "duration")]
pub(crate) mod duration;
mod grammar;
mod time;
pub(crate) mod timezone;

#[cfg(test)]
mod tests;

/// `assert_syntax!` is a parser specific utility macro for asserting a syntax test, and returning the
/// the provided provided error if the assertion fails.
#[macro_export]
macro_rules! assert_syntax {
    ($cond:expr, $err:ident $(,)?) => {
        if !$cond {
            return Err(ParseError::$err);
        }
    };
}

/// `IxdtfParser` is the primary parser implementation of `ixdtf`.
///
/// This parser provides various options for parsing date/time strings with the extended notation
/// laid out in [RFC9557][rfc9557] along with other variations laid out in the [`Temporal`][temporal-proposal].
///
/// ```rust
/// use ixdtf::{
///     parsers::IxdtfParser,
///     records::{Sign, TimeZoneRecord, UtcOffsetRecord},
/// };
///
/// let ixdtf_str = "2024-03-02T08:48:00-05:00[America/New_York]";
///
/// let result = IxdtfParser::from_str(ixdtf_str).parse().unwrap();
///
/// let date = result.date.unwrap();
/// let time = result.time.unwrap();
/// let offset = result.offset.unwrap().resolve_rfc_9557();
/// let tz_annotation = result.tz.unwrap();
///
/// assert_eq!(date.year, 2024);
/// assert_eq!(date.month, 3);
/// assert_eq!(date.day, 2);
/// assert_eq!(time.hour, 8);
/// assert_eq!(time.minute, 48);
/// assert_eq!(offset.sign(), Sign::Negative);
/// assert_eq!(offset.hour(), 5);
/// assert_eq!(offset.minute(), 0);
/// assert_eq!(offset.second(), None);
/// assert_eq!(offset.fraction(), None);
/// assert!(!tz_annotation.critical);
/// assert_eq!(
///     tz_annotation.tz,
///     TimeZoneRecord::Name("America/New_York".as_bytes())
/// );
/// ```
///
/// [rfc9557]: https://datatracker.ietf.org/doc/rfc9557/
/// [temporal-proposal]: https://tc39.es/proposal-temporal/
#[derive(Debug)]
pub struct IxdtfParser<'a, T: EncodingType> {
    cursor: Cursor<'a, T>,
}

impl<'a> IxdtfParser<'a, Utf8> {
    /// Creates a new `IxdtfParser` from a source `&str`.
    #[inline]
    #[must_use]
    #[expect(clippy::should_implement_trait)]
    pub fn from_str(source: &'a str) -> Self {
        Self::from_utf8(source.as_bytes())
    }

    /// Creates a new `IxdtfParser` from a slice of utf-8 bytes.
    #[inline]
    #[must_use]
    pub fn from_utf8(source: &'a [u8]) -> Self {
        Self::new(source)
    }
}

impl<'a> IxdtfParser<'a, Utf16> {
    /// Creates a new `IxdtfParser` from a slice of utf-16 bytes.
    pub fn from_utf16(source: &'a [u16]) -> Self {
        Self::new(source)
    }
}

impl<'a, T: EncodingType> IxdtfParser<'a, T> {
    /// Create a new `IxdtfParser` for the specified encoding.
    #[inline]
    #[must_use]
    pub fn new(source: &'a [T::CodeUnit]) -> Self {
        Self {
            cursor: Cursor::new(source),
        }
    }

    /// Parses the source as an [extended Date/Time string][rfc9557].
    ///
    /// This is the baseline parse method for `ixdtf`. For this method, the
    /// [`TimeRecord`](crate::records::TimeRecord), [`UtcOffsetRecord`],
    /// and all annotations are optional.
    ///
    /// # Example
    ///
    /// [rfc9557]: https://datatracker.ietf.org/doc/rfc9557/
    pub fn parse(&mut self) -> ParserResult<IxdtfParseRecord<'a, T>> {
        self.parse_with_annotation_handler(Some)
    }

    /// Parses the source as an extended Date/Time string with an Annotation handler.
    ///
    /// For more, see [Implementing Annotation Handlers](crate#implementing-annotation-handlers)
    pub fn parse_with_annotation_handler(
        &mut self,
        handler: impl FnMut(Annotation<'a, T>) -> Option<Annotation<'a, T>>,
    ) -> ParserResult<IxdtfParseRecord<'a, T>> {
        datetime::parse_annotated_date_time(&mut self.cursor, handler)
    }

    /// Parses the source as an extended [YearMonth string][temporal-ym].
    ///
    /// # Example
    ///
    /// ```rust
    /// # use ixdtf::parsers::IxdtfParser;
    ///
    /// let extended_year_month = "2020-11[u-ca=iso8601]";
    ///
    /// let result = IxdtfParser::from_str(extended_year_month)
    ///     .parse_year_month()
    ///     .unwrap();
    ///
    /// let date = result.date.unwrap();
    ///
    /// assert_eq!(date.year, 2020);
    /// assert_eq!(date.month, 11);
    /// ```
    ///
    /// [temporal-ym]: https://tc39.es/proposal-temporal/#prod-TemporalYearMonthString
    pub fn parse_year_month(&mut self) -> ParserResult<IxdtfParseRecord<'a, T>> {
        self.parse_year_month_with_annotation_handler(Some)
    }

    /// Parses the source as an extended `YearMonth` string with an Annotation handler.
    ///
    /// For more, see [Implementing Annotation Handlers](crate#implementing-annotation-handlers)
    pub fn parse_year_month_with_annotation_handler(
        &mut self,
        handler: impl FnMut(Annotation<'a, T>) -> Option<Annotation<'a, T>>,
    ) -> ParserResult<IxdtfParseRecord<'a, T>> {
        datetime::parse_annotated_year_month(&mut self.cursor, handler)
    }

    /// Parses the source as an extended [MonthDay string][temporal-md].
    ///
    /// # Example
    ///
    /// ```rust
    /// # use ixdtf::parsers::IxdtfParser;
    /// let extended_month_day = "1107[+04:00]";
    ///
    /// let result = IxdtfParser::from_str(extended_month_day)
    ///     .parse_month_day()
    ///     .unwrap();
    ///
    /// let date = result.date.unwrap();
    ///
    /// assert_eq!(date.month, 11);
    /// assert_eq!(date.day, 7);
    /// ```
    ///
    /// [temporal-md]: https://tc39.es/proposal-temporal/#prod-TemporalMonthDayString
    pub fn parse_month_day(&mut self) -> ParserResult<IxdtfParseRecord<'a, T>> {
        self.parse_month_day_with_annotation_handler(Some)
    }

    /// Parses the source as an extended `MonthDay` string with an Annotation handler.
    ///
    /// For more, see [Implementing Annotation Handlers](crate#implementing-annotation-handlers)
    pub fn parse_month_day_with_annotation_handler(
        &mut self,
        handler: impl FnMut(Annotation<'a, T>) -> Option<Annotation<'a, T>>,
    ) -> ParserResult<IxdtfParseRecord<'a, T>> {
        datetime::parse_annotated_month_day(&mut self.cursor, handler)
    }

    /// Parses the source as an extended [Time string][temporal-time].
    ///
    /// # Example
    ///
    /// ```rust
    /// # use ixdtf::{parsers::IxdtfParser, records::{Sign, TimeZoneRecord}};
    /// let extended_time = "12:01:04-05:00[America/New_York][u-ca=iso8601]";
    ///
    /// let result = IxdtfParser::from_str(extended_time).parse_time().unwrap();
    ///
    /// let time = result.time.unwrap();
    /// let offset = result.offset.unwrap().resolve_rfc_9557();
    /// let tz_annotation = result.tz.unwrap();
    ///
    /// assert_eq!(time.hour, 12);
    /// assert_eq!(time.minute, 1);
    /// assert_eq!(time.second, 4);
    /// assert_eq!(offset.sign(), Sign::Negative);
    /// assert_eq!(offset.hour(), 5);
    /// assert_eq!(offset.minute(), 0);
    /// assert!(!tz_annotation.critical);
    /// assert_eq!(
    ///     tz_annotation.tz,
    ///     TimeZoneRecord::Name("America/New_York".as_bytes())
    /// );
    /// ```
    ///
    /// [temporal-time]: https://tc39.es/proposal-temporal/#prod-TemporalTimeString
    pub fn parse_time(&mut self) -> ParserResult<IxdtfParseRecord<'a, T>> {
        self.parse_time_with_annotation_handler(Some)
    }

    /// Parses the source as an extended Time string with an Annotation handler.
    ///
    /// For more, see [Implementing Annotation Handlers](crate#implementing-annotation-handlers)
    pub fn parse_time_with_annotation_handler(
        &mut self,
        handler: impl FnMut(Annotation<'a, T>) -> Option<Annotation<'a, T>>,
    ) -> ParserResult<IxdtfParseRecord<'a, T>> {
        time::parse_annotated_time_record(&mut self.cursor, handler)
    }
}

/// A parser for time zone offset and IANA identifier strings.
///
/// ✨ *Enabled with the `timezone` Cargo feature.*
#[derive(Debug)]
pub struct TimeZoneParser<'a, T: EncodingType> {
    cursor: Cursor<'a, T>,
}

impl<'a> TimeZoneParser<'a, Utf8> {
    /// Creates a new `TimeZoneParser` from a source `&str`.
    #[inline]
    #[must_use]
    #[expect(clippy::should_implement_trait)]
    pub fn from_str(source: &'a str) -> Self {
        Self::from_utf8(source.as_bytes())
    }

    /// Creates a new `TimeZoneParser` from a slice of utf-8 bytes.
    #[inline]
    #[must_use]
    pub fn from_utf8(source: &'a [u8]) -> Self {
        Self::new(source)
    }
}

impl<'a> TimeZoneParser<'a, Utf16> {
    /// Creates a new `TimeZoneParser` from a slice of utf-16 bytes.
    pub fn from_utf16(source: &'a [u16]) -> Self {
        Self::new(source)
    }
}

impl<'a, T: EncodingType> TimeZoneParser<'a, T> {
    /// Creates a new `TimeZoneParser` for the provided encoding.
    #[inline]
    #[must_use]
    pub fn new(source: &'a [T::CodeUnit]) -> Self {
        Self {
            cursor: Cursor::new(source),
        }
    }

    /// Parse a time zone identifier that can be either an
    /// IANA identifer name or minute precision offset.
    ///
    /// ## IANA identifier example
    ///
    /// ```rust
    /// use ixdtf::{parsers::TimeZoneParser, records::TimeZoneRecord};
    ///
    /// let identifier = "Europe/London";
    /// let record = TimeZoneParser::from_str(identifier)
    ///     .parse_identifier()
    ///     .unwrap();
    /// assert_eq!(record, TimeZoneRecord::Name(identifier.as_bytes()))
    /// ```
    ///
    /// ## Minute precision offset example
    ///
    /// ```rust
    /// use ixdtf::{
    ///     parsers::TimeZoneParser,
    ///     records::{MinutePrecisionOffset, Sign, TimeZoneRecord},
    /// };
    ///
    /// let identifier = "+00:00";
    /// let offset = match TimeZoneParser::from_str(identifier).parse_identifier() {
    ///     Ok(TimeZoneRecord::Offset(o)) => o,
    ///     _ => unreachable!(),
    /// };
    ///
    /// assert_eq!(offset.sign, Sign::Positive);
    /// assert_eq!(offset.hour, 0);
    /// assert_eq!(offset.minute, 0);
    /// ```
    ///
    /// ## Errors
    ///
    /// It is an error to provide a full precision offset as a
    /// time zone identifier.
    ///
    /// **NOTE**: To parse either a full or minute precision,
    /// use [`Self::parse_offset`].
    ///
    /// ```rust
    /// use ixdtf::{parsers::TimeZoneParser, ParseError};
    ///
    /// let identifier = "+00:00:00";
    /// let err = TimeZoneParser::from_str(identifier)
    ///     .parse_identifier()
    ///     .unwrap_err();
    /// assert_eq!(err, ParseError::InvalidMinutePrecisionOffset);
    ///
    /// let identifier = "+00:00.1";
    /// let err = TimeZoneParser::from_str(identifier)
    ///     .parse_identifier()
    ///     .unwrap_err();
    /// assert_eq!(err, ParseError::InvalidEnd);
    /// ```
    pub fn parse_identifier(&mut self) -> ParserResult<TimeZoneRecord<'a, T>> {
        let result = timezone::parse_time_zone(&mut self.cursor)?;
        self.cursor.close()?;
        Ok(result)
    }

    /// Parse a UTC offset from the provided source.
    ///
    /// This method can parse both a minute precision and full
    /// precision offset.
    ///
    /// ## Minute precision offset example
    ///
    /// ```rust
    /// use ixdtf::{parsers::TimeZoneParser, records::Sign};
    ///
    /// let offset_src = "-05:00";
    /// let parse_result =
    ///     TimeZoneParser::from_str(offset_src).parse_offset().unwrap();
    /// assert_eq!(parse_result.sign(), Sign::Negative);
    /// assert_eq!(parse_result.hour(), 5);
    /// assert_eq!(parse_result.minute(), 0);
    /// assert_eq!(parse_result.second(), None);
    /// assert_eq!(parse_result.fraction(), None);
    /// ```
    ///
    /// ## Full precision offset example
    ///
    /// ```rust
    /// use ixdtf::{parsers::TimeZoneParser, records::Sign};
    ///
    /// let offset_src = "-05:00:30.123456789";
    /// let parse_result =
    ///     TimeZoneParser::from_str(offset_src).parse_offset().unwrap();
    /// assert_eq!(parse_result.sign(), Sign::Negative);
    /// assert_eq!(parse_result.hour(), 5);
    /// assert_eq!(parse_result.minute(), 0);
    /// assert_eq!(parse_result.second(), Some(30));
    /// let fraction = parse_result.fraction().unwrap();
    /// assert_eq!(fraction.to_nanoseconds(), Some(123456789));
    /// ```
    #[inline]
    pub fn parse_offset(&mut self) -> ParserResult<UtcOffsetRecord> {
        let result = timezone::parse_utc_offset(&mut self.cursor)?;
        self.cursor.close()?;
        Ok(result)
    }

    /// Parse an IANA identifier name.
    ///
    ///
    /// ```rust
    /// use ixdtf::{parsers::TimeZoneParser, records::Sign};
    ///
    /// let iana_identifier = "America/Chicago";
    /// let parse_result = TimeZoneParser::from_str(iana_identifier)
    ///     .parse_iana_identifier()
    ///     .unwrap();
    /// assert_eq!(parse_result, iana_identifier.as_bytes());
    ///
    /// let iana_identifier = "Europe/Berlin";
    /// let parse_result = TimeZoneParser::from_str(iana_identifier)
    ///     .parse_iana_identifier()
    ///     .unwrap();
    /// assert_eq!(parse_result, iana_identifier.as_bytes());
    /// ```
    #[inline]
    pub fn parse_iana_identifier(&mut self) -> ParserResult<&'a [T::CodeUnit]> {
        let result = timezone::parse_tz_iana_name(&mut self.cursor)?;
        self.cursor.close()?;
        Ok(result)
    }
}

/// A parser for ISO8601 Duration strings.
///
/// ✨ *Enabled with the `duration` Cargo feature.*
///
/// # Example
///
/// ```rust
/// use ixdtf::{parsers::IsoDurationParser, records::{Sign, DurationParseRecord, TimeDurationRecord}};
///
/// let duration_str = "P1Y2M1DT2H10M30S";
///
/// let result = IsoDurationParser::from_str(duration_str).parse().unwrap();
///
/// let date_duration = result.date.unwrap();
///
/// let (hours, minutes, seconds, fraction) = match result.time {
///     // Hours variant is defined as { hours: u32, fraction: Option<Fraction> }
///     Some(TimeDurationRecord::Hours{ hours, fraction }) => (hours, 0, 0, fraction),
///     // Minutes variant is defined as { hours: u32, minutes: u32, fraction: Option<Fraction> }
///     Some(TimeDurationRecord::Minutes{ hours, minutes, fraction }) => (hours, minutes, 0, fraction),
///     // Seconds variant is defined as { hours: u32, minutes: u32, seconds: u32, fraction: Option<Fraction> }
///     Some(TimeDurationRecord::Seconds{ hours, minutes, seconds, fraction }) => (hours, minutes, seconds, fraction),
///     None => (0,0,0, None),
/// };
///
/// assert_eq!(result.sign, Sign::Positive);
/// assert_eq!(date_duration.years, 1);
/// assert_eq!(date_duration.months, 2);
/// assert_eq!(date_duration.weeks, 0);
/// assert_eq!(date_duration.days, 1);//
/// assert_eq!(hours, 2);
/// assert_eq!(minutes, 10);
/// assert_eq!(seconds, 30);
/// assert_eq!(fraction, None);
/// ```
#[cfg(feature = "duration")]
#[derive(Debug)]
pub struct IsoDurationParser<'a, T: EncodingType> {
    cursor: Cursor<'a, T>,
}

#[cfg(feature = "duration")]
impl<'a> IsoDurationParser<'a, Utf8> {
    /// Creates a new `IsoDurationParser` from a source `&str`.
    #[inline]
    #[must_use]
    #[expect(clippy::should_implement_trait)]
    pub fn from_str(source: &'a str) -> Self {
        Self::from_utf8(source.as_bytes())
    }

    /// Creates a new `IsoDurationParser` from a slice of utf-8 bytes.
    #[inline]
    #[must_use]
    pub fn from_utf8(source: &'a [u8]) -> Self {
        Self::new(source)
    }
}

#[cfg(feature = "duration")]
impl<'a> IsoDurationParser<'a, Utf16> {
    /// Creates a new `IsoDurationParser` from a slice of utf-16 bytes.
    #[inline]
    #[must_use]
    pub fn from_utf8(source: &'a [u16]) -> Self {
        Self::new(source)
    }
}

#[cfg(feature = "duration")]
impl<'a, T: EncodingType> IsoDurationParser<'a, T> {
    /// Creates a new `IsoDurationParser` for the provided encoding.
    #[inline]
    #[must_use]
    pub fn new(source: &'a [T::CodeUnit]) -> Self {
        Self {
            cursor: Cursor::new(source),
        }
    }

    /// Parse the contents of this `IsoDurationParser` into a `DurationParseRecord`.
    ///
    /// # Examples
    ///
    /// ## Parsing a date duration
    ///
    /// ```
    /// # use ixdtf::{parsers::IsoDurationParser, records::DurationParseRecord };
    /// let date_duration = "P1Y2M3W1D";
    ///
    /// let result = IsoDurationParser::from_str(date_duration).parse().unwrap();
    ///
    /// let date_duration = result.date.unwrap();
    ///
    /// assert!(result.time.is_none());
    /// assert_eq!(date_duration.years, 1);
    /// assert_eq!(date_duration.months, 2);
    /// assert_eq!(date_duration.weeks, 3);
    /// assert_eq!(date_duration.days, 1);
    /// ```
    ///
    /// ## Parsing a time duration
    ///
    /// ```rust
    /// # use ixdtf::{parsers::IsoDurationParser, records::{DurationParseRecord, TimeDurationRecord }};
    /// let time_duration = "PT2H10M30S";
    ///
    /// let result = IsoDurationParser::from_str(time_duration).parse().unwrap();
    ///
    /// let (hours, minutes, seconds, fraction) = match result.time {
    ///     // Hours variant is defined as { hours: u32, fraction: Option<Fraction> }
    ///     Some(TimeDurationRecord::Hours{ hours, fraction }) => (hours, 0, 0, fraction),
    ///     // Minutes variant is defined as { hours: u32, minutes: u32, fraction: Option<Fraction> }
    ///     Some(TimeDurationRecord::Minutes{ hours, minutes, fraction }) => (hours, minutes, 0, fraction),
    ///     // Seconds variant is defined as { hours: u32, minutes: u32, seconds: u32, fraction: Option<Fraction> }
    ///     Some(TimeDurationRecord::Seconds{ hours, minutes, seconds, fraction }) => (hours, minutes, seconds, fraction),
    ///     None => (0,0,0, None),
    /// };
    /// assert!(result.date.is_none());
    /// assert_eq!(hours, 2);
    /// assert_eq!(minutes, 10);
    /// assert_eq!(seconds, 30);
    /// assert_eq!(fraction, None);
    /// ```
    pub fn parse(&mut self) -> ParserResult<DurationParseRecord> {
        duration::parse_duration(&mut self.cursor)
    }
}