Coverage Report

Created: 2025-10-29 07:05

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/time-0.3.37/src/parsing/parsable.rs
Line
Count
Source
1
//! A trait that can be used to parse an item from an input.
2
3
use core::ops::Deref;
4
5
use num_conv::prelude::*;
6
7
use crate::error::TryFromParsed;
8
use crate::format_description::well_known::iso8601::EncodedConfig;
9
use crate::format_description::well_known::{Iso8601, Rfc2822, Rfc3339};
10
use crate::format_description::BorrowedFormatItem;
11
#[cfg(feature = "alloc")]
12
use crate::format_description::OwnedFormatItem;
13
use crate::internal_macros::bug;
14
use crate::parsing::{Parsed, ParsedItem};
15
use crate::{error, Date, Month, OffsetDateTime, Time, UtcOffset, Weekday};
16
17
/// A type that can be parsed.
18
#[cfg_attr(docsrs, doc(notable_trait))]
19
#[doc(alias = "Parseable")]
20
pub trait Parsable: sealed::Sealed {}
21
impl Parsable for BorrowedFormatItem<'_> {}
22
impl Parsable for [BorrowedFormatItem<'_>] {}
23
#[cfg(feature = "alloc")]
24
impl Parsable for OwnedFormatItem {}
25
#[cfg(feature = "alloc")]
26
impl Parsable for [OwnedFormatItem] {}
27
impl Parsable for Rfc2822 {}
28
impl Parsable for Rfc3339 {}
29
impl<const CONFIG: EncodedConfig> Parsable for Iso8601<CONFIG> {}
30
impl<T: Deref> Parsable for T where T::Target: Parsable {}
31
32
/// Seal the trait to prevent downstream users from implementing it, while still allowing it to
33
/// exist in generic bounds.
34
mod sealed {
35
    #[allow(clippy::wildcard_imports)]
36
    use super::*;
37
    use crate::PrimitiveDateTime;
38
39
    /// Parse the item using a format description and an input.
40
    pub trait Sealed {
41
        /// Parse the item into the provided [`Parsed`] struct.
42
        ///
43
        /// This method can be used to parse a single component without parsing the full value.
44
        fn parse_into<'a>(
45
            &self,
46
            input: &'a [u8],
47
            parsed: &mut Parsed,
48
        ) -> Result<&'a [u8], error::Parse>;
49
50
        /// Parse the item into a new [`Parsed`] struct.
51
        ///
52
        /// This method can only be used to parse a complete value of a type. If any characters
53
        /// remain after parsing, an error will be returned.
54
0
        fn parse(&self, input: &[u8]) -> Result<Parsed, error::Parse> {
55
0
            let mut parsed = Parsed::new();
56
0
            if self.parse_into(input, &mut parsed)?.is_empty() {
57
0
                Ok(parsed)
58
            } else {
59
0
                Err(error::Parse::ParseFromDescription(
60
0
                    error::ParseFromDescription::UnexpectedTrailingCharacters,
61
0
                ))
62
            }
63
0
        }
Unexecuted instantiation: <alloc::vec::Vec<time::format_description::borrowed_format_item::BorrowedFormatItem> as time::parsing::parsable::sealed::Sealed>::parse
Unexecuted instantiation: <_ as time::parsing::parsable::sealed::Sealed>::parse
64
65
        /// Parse a [`Date`] from the format description.
66
0
        fn parse_date(&self, input: &[u8]) -> Result<Date, error::Parse> {
67
0
            Ok(self.parse(input)?.try_into()?)
68
0
        }
Unexecuted instantiation: <alloc::vec::Vec<time::format_description::borrowed_format_item::BorrowedFormatItem> as time::parsing::parsable::sealed::Sealed>::parse_date
Unexecuted instantiation: <_ as time::parsing::parsable::sealed::Sealed>::parse_date
69
70
        /// Parse a [`Time`] from the format description.
71
0
        fn parse_time(&self, input: &[u8]) -> Result<Time, error::Parse> {
72
0
            Ok(self.parse(input)?.try_into()?)
73
0
        }
74
75
        /// Parse a [`UtcOffset`] from the format description.
76
0
        fn parse_offset(&self, input: &[u8]) -> Result<UtcOffset, error::Parse> {
77
0
            Ok(self.parse(input)?.try_into()?)
78
0
        }
79
80
        /// Parse a [`PrimitiveDateTime`] from the format description.
81
0
        fn parse_primitive_date_time(
82
0
            &self,
83
0
            input: &[u8],
84
0
        ) -> Result<PrimitiveDateTime, error::Parse> {
85
0
            Ok(self.parse(input)?.try_into()?)
86
0
        }
87
88
        /// Parse a [`OffsetDateTime`] from the format description.
89
0
        fn parse_offset_date_time(&self, input: &[u8]) -> Result<OffsetDateTime, error::Parse> {
90
0
            Ok(self.parse(input)?.try_into()?)
91
0
        }
92
    }
93
}
94
95
// region: custom formats
96
impl sealed::Sealed for BorrowedFormatItem<'_> {
97
0
    fn parse_into<'a>(
98
0
        &self,
99
0
        input: &'a [u8],
100
0
        parsed: &mut Parsed,
101
0
    ) -> Result<&'a [u8], error::Parse> {
102
0
        Ok(parsed.parse_item(input, self)?)
103
0
    }
104
}
105
106
impl sealed::Sealed for [BorrowedFormatItem<'_>] {
107
0
    fn parse_into<'a>(
108
0
        &self,
109
0
        input: &'a [u8],
110
0
        parsed: &mut Parsed,
111
0
    ) -> Result<&'a [u8], error::Parse> {
112
0
        Ok(parsed.parse_items(input, self)?)
113
0
    }
114
}
115
116
#[cfg(feature = "alloc")]
117
impl sealed::Sealed for OwnedFormatItem {
118
0
    fn parse_into<'a>(
119
0
        &self,
120
0
        input: &'a [u8],
121
0
        parsed: &mut Parsed,
122
0
    ) -> Result<&'a [u8], error::Parse> {
123
0
        Ok(parsed.parse_item(input, self)?)
124
0
    }
125
}
126
127
#[cfg(feature = "alloc")]
128
impl sealed::Sealed for [OwnedFormatItem] {
129
0
    fn parse_into<'a>(
130
0
        &self,
131
0
        input: &'a [u8],
132
0
        parsed: &mut Parsed,
133
0
    ) -> Result<&'a [u8], error::Parse> {
134
0
        Ok(parsed.parse_items(input, self)?)
135
0
    }
136
}
137
138
impl<T: Deref> sealed::Sealed for T
139
where
140
    T::Target: sealed::Sealed,
141
{
142
0
    fn parse_into<'a>(
143
0
        &self,
144
0
        input: &'a [u8],
145
0
        parsed: &mut Parsed,
146
0
    ) -> Result<&'a [u8], error::Parse> {
147
0
        self.deref().parse_into(input, parsed)
148
0
    }
Unexecuted instantiation: <alloc::vec::Vec<time::format_description::borrowed_format_item::BorrowedFormatItem> as time::parsing::parsable::sealed::Sealed>::parse_into
Unexecuted instantiation: <_ as time::parsing::parsable::sealed::Sealed>::parse_into
149
}
150
// endregion custom formats
151
152
// region: well-known formats
153
impl sealed::Sealed for Rfc2822 {
154
0
    fn parse_into<'a>(
155
0
        &self,
156
0
        input: &'a [u8],
157
0
        parsed: &mut Parsed,
158
0
    ) -> Result<&'a [u8], error::Parse> {
159
        use crate::error::ParseFromDescription::{InvalidComponent, InvalidLiteral};
160
        use crate::parsing::combinator::rfc::rfc2822::{cfws, fws};
161
        use crate::parsing::combinator::{
162
            ascii_char, exactly_n_digits, first_match, n_to_m_digits, opt, sign,
163
        };
164
165
0
        let colon = ascii_char::<b':'>;
166
0
        let comma = ascii_char::<b','>;
167
168
0
        let input = opt(cfws)(input).into_inner();
169
0
        let weekday = first_match(
170
0
            [
171
0
                (b"Mon".as_slice(), Weekday::Monday),
172
0
                (b"Tue".as_slice(), Weekday::Tuesday),
173
0
                (b"Wed".as_slice(), Weekday::Wednesday),
174
0
                (b"Thu".as_slice(), Weekday::Thursday),
175
0
                (b"Fri".as_slice(), Weekday::Friday),
176
0
                (b"Sat".as_slice(), Weekday::Saturday),
177
0
                (b"Sun".as_slice(), Weekday::Sunday),
178
0
            ],
179
0
            false,
180
0
        )(input);
181
0
        let input = if let Some(item) = weekday {
182
0
            let input = item
183
0
                .consume_value(|value| parsed.set_weekday(value))
184
0
                .ok_or(InvalidComponent("weekday"))?;
185
0
            let input = comma(input).ok_or(InvalidLiteral)?.into_inner();
186
0
            opt(cfws)(input).into_inner()
187
        } else {
188
0
            input
189
        };
190
0
        let input = n_to_m_digits::<1, 2, _>(input)
191
0
            .and_then(|item| item.consume_value(|value| parsed.set_day(value)))
192
0
            .ok_or(InvalidComponent("day"))?;
193
0
        let input = cfws(input).ok_or(InvalidLiteral)?.into_inner();
194
0
        let input = first_match(
195
0
            [
196
0
                (b"Jan".as_slice(), Month::January),
197
0
                (b"Feb".as_slice(), Month::February),
198
0
                (b"Mar".as_slice(), Month::March),
199
0
                (b"Apr".as_slice(), Month::April),
200
0
                (b"May".as_slice(), Month::May),
201
0
                (b"Jun".as_slice(), Month::June),
202
0
                (b"Jul".as_slice(), Month::July),
203
0
                (b"Aug".as_slice(), Month::August),
204
0
                (b"Sep".as_slice(), Month::September),
205
0
                (b"Oct".as_slice(), Month::October),
206
0
                (b"Nov".as_slice(), Month::November),
207
0
                (b"Dec".as_slice(), Month::December),
208
0
            ],
209
0
            false,
210
0
        )(input)
211
0
        .and_then(|item| item.consume_value(|value| parsed.set_month(value)))
212
0
        .ok_or(InvalidComponent("month"))?;
213
0
        let input = cfws(input).ok_or(InvalidLiteral)?.into_inner();
214
0
        let input = match exactly_n_digits::<4, u32>(input) {
215
0
            Some(item) => {
216
0
                let input = item
217
0
                    .flat_map(|year| if year >= 1900 { Some(year) } else { None })
218
0
                    .and_then(|item| {
219
0
                        item.consume_value(|value| parsed.set_year(value.cast_signed()))
220
0
                    })
221
0
                    .ok_or(InvalidComponent("year"))?;
222
0
                fws(input).ok_or(InvalidLiteral)?.into_inner()
223
            }
224
            None => {
225
0
                let input = exactly_n_digits::<2, u32>(input)
226
0
                    .and_then(|item| {
227
0
                        item.map(|year| if year < 50 { year + 2000 } else { year + 1900 })
228
0
                            .map(|year| year.cast_signed())
229
0
                            .consume_value(|value| parsed.set_year(value))
230
0
                    })
231
0
                    .ok_or(InvalidComponent("year"))?;
232
0
                cfws(input).ok_or(InvalidLiteral)?.into_inner()
233
            }
234
        };
235
236
0
        let input = exactly_n_digits::<2, _>(input)
237
0
            .and_then(|item| item.consume_value(|value| parsed.set_hour_24(value)))
238
0
            .ok_or(InvalidComponent("hour"))?;
239
0
        let input = opt(cfws)(input).into_inner();
240
0
        let input = colon(input).ok_or(InvalidLiteral)?.into_inner();
241
0
        let input = opt(cfws)(input).into_inner();
242
0
        let input = exactly_n_digits::<2, _>(input)
243
0
            .and_then(|item| item.consume_value(|value| parsed.set_minute(value)))
244
0
            .ok_or(InvalidComponent("minute"))?;
245
246
0
        let input = if let Some(input) = colon(opt(cfws)(input).into_inner()) {
247
0
            let input = input.into_inner(); // discard the colon
248
0
            let input = opt(cfws)(input).into_inner();
249
0
            let input = exactly_n_digits::<2, _>(input)
250
0
                .and_then(|item| item.consume_value(|value| parsed.set_second(value)))
251
0
                .ok_or(InvalidComponent("second"))?;
252
0
            cfws(input).ok_or(InvalidLiteral)?.into_inner()
253
        } else {
254
0
            cfws(input).ok_or(InvalidLiteral)?.into_inner()
255
        };
256
257
        // The RFC explicitly allows leap seconds.
258
0
        parsed.leap_second_allowed = true;
259
260
        #[allow(clippy::unnecessary_lazy_evaluations)] // rust-lang/rust-clippy#8522
261
0
        let zone_literal = first_match(
262
0
            [
263
0
                (b"UT".as_slice(), 0),
264
0
                (b"GMT".as_slice(), 0),
265
0
                (b"EST".as_slice(), -5),
266
0
                (b"EDT".as_slice(), -4),
267
0
                (b"CST".as_slice(), -6),
268
0
                (b"CDT".as_slice(), -5),
269
0
                (b"MST".as_slice(), -7),
270
0
                (b"MDT".as_slice(), -6),
271
0
                (b"PST".as_slice(), -8),
272
0
                (b"PDT".as_slice(), -7),
273
0
            ],
274
0
            false,
275
0
        )(input)
276
0
        .or_else(|| match input {
277
0
            [b'a'..=b'i' | b'k'..=b'z' | b'A'..=b'I' | b'K'..=b'Z', rest @ ..] => {
278
0
                Some(ParsedItem(rest, 0))
279
            }
280
0
            _ => None,
281
0
        });
282
0
        if let Some(zone_literal) = zone_literal {
283
0
            let input = zone_literal
284
0
                .consume_value(|value| parsed.set_offset_hour(value))
285
0
                .ok_or(InvalidComponent("offset hour"))?;
286
0
            parsed
287
0
                .set_offset_minute_signed(0)
288
0
                .ok_or(InvalidComponent("offset minute"))?;
289
0
            parsed
290
0
                .set_offset_second_signed(0)
291
0
                .ok_or(InvalidComponent("offset second"))?;
292
0
            return Ok(input);
293
0
        }
294
295
0
        let ParsedItem(input, offset_sign) = sign(input).ok_or(InvalidComponent("offset hour"))?;
296
0
        let input = exactly_n_digits::<2, u8>(input)
297
0
            .and_then(|item| {
298
0
                item.map(|offset_hour| {
299
0
                    if offset_sign == b'-' {
300
0
                        -offset_hour.cast_signed()
301
                    } else {
302
0
                        offset_hour.cast_signed()
303
                    }
304
0
                })
305
0
                .consume_value(|value| parsed.set_offset_hour(value))
306
0
            })
307
0
            .ok_or(InvalidComponent("offset hour"))?;
308
0
        let input = exactly_n_digits::<2, u8>(input)
309
0
            .and_then(|item| {
310
0
                item.consume_value(|value| parsed.set_offset_minute_signed(value.cast_signed()))
311
0
            })
312
0
            .ok_or(InvalidComponent("offset minute"))?;
313
314
0
        let input = opt(cfws)(input).into_inner();
315
316
0
        Ok(input)
317
0
    }
318
319
0
    fn parse_offset_date_time(&self, input: &[u8]) -> Result<OffsetDateTime, error::Parse> {
320
        use crate::error::ParseFromDescription::{InvalidComponent, InvalidLiteral};
321
        use crate::parsing::combinator::rfc::rfc2822::{cfws, fws};
322
        use crate::parsing::combinator::{
323
            ascii_char, exactly_n_digits, first_match, n_to_m_digits, opt, sign,
324
        };
325
326
0
        let colon = ascii_char::<b':'>;
327
0
        let comma = ascii_char::<b','>;
328
329
0
        let input = opt(cfws)(input).into_inner();
330
        // This parses the weekday, but we don't actually use the value anywhere. Because of this,
331
        // just return `()` to avoid unnecessary generated code.
332
0
        let weekday = first_match(
333
0
            [
334
0
                (b"Mon".as_slice(), ()),
335
0
                (b"Tue".as_slice(), ()),
336
0
                (b"Wed".as_slice(), ()),
337
0
                (b"Thu".as_slice(), ()),
338
0
                (b"Fri".as_slice(), ()),
339
0
                (b"Sat".as_slice(), ()),
340
0
                (b"Sun".as_slice(), ()),
341
0
            ],
342
0
            false,
343
0
        )(input);
344
0
        let input = if let Some(item) = weekday {
345
0
            let input = item.into_inner();
346
0
            let input = comma(input).ok_or(InvalidLiteral)?.into_inner();
347
0
            opt(cfws)(input).into_inner()
348
        } else {
349
0
            input
350
        };
351
0
        let ParsedItem(input, day) =
352
0
            n_to_m_digits::<1, 2, _>(input).ok_or(InvalidComponent("day"))?;
353
0
        let input = cfws(input).ok_or(InvalidLiteral)?.into_inner();
354
0
        let ParsedItem(input, month) = first_match(
355
0
            [
356
0
                (b"Jan".as_slice(), Month::January),
357
0
                (b"Feb".as_slice(), Month::February),
358
0
                (b"Mar".as_slice(), Month::March),
359
0
                (b"Apr".as_slice(), Month::April),
360
0
                (b"May".as_slice(), Month::May),
361
0
                (b"Jun".as_slice(), Month::June),
362
0
                (b"Jul".as_slice(), Month::July),
363
0
                (b"Aug".as_slice(), Month::August),
364
0
                (b"Sep".as_slice(), Month::September),
365
0
                (b"Oct".as_slice(), Month::October),
366
0
                (b"Nov".as_slice(), Month::November),
367
0
                (b"Dec".as_slice(), Month::December),
368
0
            ],
369
0
            false,
370
0
        )(input)
371
0
        .ok_or(InvalidComponent("month"))?;
372
0
        let input = cfws(input).ok_or(InvalidLiteral)?.into_inner();
373
0
        let (input, year) = match exactly_n_digits::<4, u32>(input) {
374
0
            Some(item) => {
375
0
                let ParsedItem(input, year) = item
376
0
                    .flat_map(|year| if year >= 1900 { Some(year) } else { None })
377
0
                    .ok_or(InvalidComponent("year"))?;
378
0
                let input = fws(input).ok_or(InvalidLiteral)?.into_inner();
379
0
                (input, year)
380
            }
381
            None => {
382
0
                let ParsedItem(input, year) = exactly_n_digits::<2, u32>(input)
383
0
                    .map(|item| item.map(|year| if year < 50 { year + 2000 } else { year + 1900 }))
384
0
                    .ok_or(InvalidComponent("year"))?;
385
0
                let input = cfws(input).ok_or(InvalidLiteral)?.into_inner();
386
0
                (input, year)
387
            }
388
        };
389
390
0
        let ParsedItem(input, hour) =
391
0
            exactly_n_digits::<2, _>(input).ok_or(InvalidComponent("hour"))?;
392
0
        let input = opt(cfws)(input).into_inner();
393
0
        let input = colon(input).ok_or(InvalidLiteral)?.into_inner();
394
0
        let input = opt(cfws)(input).into_inner();
395
0
        let ParsedItem(input, minute) =
396
0
            exactly_n_digits::<2, _>(input).ok_or(InvalidComponent("minute"))?;
397
398
0
        let (input, mut second) = if let Some(input) = colon(opt(cfws)(input).into_inner()) {
399
0
            let input = input.into_inner(); // discard the colon
400
0
            let input = opt(cfws)(input).into_inner();
401
0
            let ParsedItem(input, second) =
402
0
                exactly_n_digits::<2, _>(input).ok_or(InvalidComponent("second"))?;
403
0
            let input = cfws(input).ok_or(InvalidLiteral)?.into_inner();
404
0
            (input, second)
405
        } else {
406
0
            (cfws(input).ok_or(InvalidLiteral)?.into_inner(), 0)
407
        };
408
409
        #[allow(clippy::unnecessary_lazy_evaluations)] // rust-lang/rust-clippy#8522
410
0
        let zone_literal = first_match(
411
0
            [
412
0
                (b"UT".as_slice(), 0),
413
0
                (b"GMT".as_slice(), 0),
414
0
                (b"EST".as_slice(), -5),
415
0
                (b"EDT".as_slice(), -4),
416
0
                (b"CST".as_slice(), -6),
417
0
                (b"CDT".as_slice(), -5),
418
0
                (b"MST".as_slice(), -7),
419
0
                (b"MDT".as_slice(), -6),
420
0
                (b"PST".as_slice(), -8),
421
0
                (b"PDT".as_slice(), -7),
422
0
            ],
423
0
            false,
424
0
        )(input)
425
0
        .or_else(|| match input {
426
0
            [b'a'..=b'i' | b'k'..=b'z' | b'A'..=b'I' | b'K'..=b'Z', rest @ ..] => {
427
0
                Some(ParsedItem(rest, 0))
428
            }
429
0
            _ => None,
430
0
        });
431
432
0
        let (input, offset_hour, offset_minute) = if let Some(zone_literal) = zone_literal {
433
0
            let ParsedItem(input, offset_hour) = zone_literal;
434
0
            (input, offset_hour, 0)
435
        } else {
436
0
            let ParsedItem(input, offset_sign) =
437
0
                sign(input).ok_or(InvalidComponent("offset hour"))?;
438
0
            let ParsedItem(input, offset_hour) = exactly_n_digits::<2, u8>(input)
439
0
                .map(|item| {
440
0
                    item.map(|offset_hour| {
441
0
                        if offset_sign == b'-' {
442
0
                            -offset_hour.cast_signed()
443
                        } else {
444
0
                            offset_hour.cast_signed()
445
                        }
446
0
                    })
447
0
                })
448
0
                .ok_or(InvalidComponent("offset hour"))?;
449
0
            let ParsedItem(input, offset_minute) =
450
0
                exactly_n_digits::<2, u8>(input).ok_or(InvalidComponent("offset minute"))?;
451
0
            (input, offset_hour, offset_minute.cast_signed())
452
        };
453
454
0
        let input = opt(cfws)(input).into_inner();
455
456
0
        if !input.is_empty() {
457
0
            return Err(error::Parse::ParseFromDescription(
458
0
                error::ParseFromDescription::UnexpectedTrailingCharacters,
459
0
            ));
460
0
        }
461
462
0
        let mut nanosecond = 0;
463
0
        let leap_second_input = if second == 60 {
464
0
            second = 59;
465
0
            nanosecond = 999_999_999;
466
0
            true
467
        } else {
468
0
            false
469
        };
470
471
0
        let dt = (|| {
472
0
            let date = Date::from_calendar_date(year.cast_signed(), month, day)?;
473
0
            let time = Time::from_hms_nano(hour, minute, second, nanosecond)?;
474
0
            let offset = UtcOffset::from_hms(offset_hour, offset_minute, 0)?;
475
0
            Ok(OffsetDateTime::new_in_offset(date, time, offset))
476
        })()
477
0
        .map_err(TryFromParsed::ComponentRange)?;
478
479
0
        if leap_second_input && !dt.is_valid_leap_second_stand_in() {
480
0
            return Err(error::Parse::TryFromParsed(TryFromParsed::ComponentRange(
481
0
                error::ComponentRange {
482
0
                    name: "second",
483
0
                    minimum: 0,
484
0
                    maximum: 59,
485
0
                    value: 60,
486
0
                    conditional_range: true,
487
0
                },
488
0
            )));
489
0
        }
490
491
0
        Ok(dt)
492
0
    }
493
}
494
495
impl sealed::Sealed for Rfc3339 {
496
0
    fn parse_into<'a>(
497
0
        &self,
498
0
        input: &'a [u8],
499
0
        parsed: &mut Parsed,
500
0
    ) -> Result<&'a [u8], error::Parse> {
501
        use crate::error::ParseFromDescription::{InvalidComponent, InvalidLiteral};
502
        use crate::parsing::combinator::{
503
            any_digit, ascii_char, ascii_char_ignore_case, exactly_n_digits, sign,
504
        };
505
506
0
        let dash = ascii_char::<b'-'>;
507
0
        let colon = ascii_char::<b':'>;
508
509
0
        let input = exactly_n_digits::<4, u32>(input)
510
0
            .and_then(|item| item.consume_value(|value| parsed.set_year(value.cast_signed())))
511
0
            .ok_or(InvalidComponent("year"))?;
512
0
        let input = dash(input).ok_or(InvalidLiteral)?.into_inner();
513
0
        let input = exactly_n_digits::<2, _>(input)
514
0
            .and_then(|item| item.flat_map(|value| Month::from_number(value).ok()))
515
0
            .and_then(|item| item.consume_value(|value| parsed.set_month(value)))
516
0
            .ok_or(InvalidComponent("month"))?;
517
0
        let input = dash(input).ok_or(InvalidLiteral)?.into_inner();
518
0
        let input = exactly_n_digits::<2, _>(input)
519
0
            .and_then(|item| item.consume_value(|value| parsed.set_day(value)))
520
0
            .ok_or(InvalidComponent("day"))?;
521
522
        // RFC3339 allows any separator, not just `T`, not just `space`.
523
        // cf. Section 5.6: Internet Date/Time Format:
524
        //   NOTE: ISO 8601 defines date and time separated by "T".
525
        //   Applications using this syntax may choose, for the sake of
526
        //   readability, to specify a full-date and full-time separated by
527
        //   (say) a space character.
528
        // Specifically, rusqlite uses space separators.
529
0
        let input = input.get(1..).ok_or(InvalidComponent("separator"))?;
530
531
0
        let input = exactly_n_digits::<2, _>(input)
532
0
            .and_then(|item| item.consume_value(|value| parsed.set_hour_24(value)))
533
0
            .ok_or(InvalidComponent("hour"))?;
534
0
        let input = colon(input).ok_or(InvalidLiteral)?.into_inner();
535
0
        let input = exactly_n_digits::<2, _>(input)
536
0
            .and_then(|item| item.consume_value(|value| parsed.set_minute(value)))
537
0
            .ok_or(InvalidComponent("minute"))?;
538
0
        let input = colon(input).ok_or(InvalidLiteral)?.into_inner();
539
0
        let input = exactly_n_digits::<2, _>(input)
540
0
            .and_then(|item| item.consume_value(|value| parsed.set_second(value)))
541
0
            .ok_or(InvalidComponent("second"))?;
542
0
        let input = if let Some(ParsedItem(input, ())) = ascii_char::<b'.'>(input) {
543
0
            let ParsedItem(mut input, mut value) = any_digit(input)
544
0
                .ok_or(InvalidComponent("subsecond"))?
545
0
                .map(|v| (v - b'0').extend::<u32>() * 100_000_000);
546
547
0
            let mut multiplier = 10_000_000;
548
0
            while let Some(ParsedItem(new_input, digit)) = any_digit(input) {
549
0
                value += (digit - b'0').extend::<u32>() * multiplier;
550
0
                input = new_input;
551
0
                multiplier /= 10;
552
0
            }
553
554
0
            parsed
555
0
                .set_subsecond(value)
556
0
                .ok_or(InvalidComponent("subsecond"))?;
557
0
            input
558
        } else {
559
0
            input
560
        };
561
562
        // The RFC explicitly allows leap seconds.
563
0
        parsed.leap_second_allowed = true;
564
565
0
        if let Some(ParsedItem(input, ())) = ascii_char_ignore_case::<b'Z'>(input) {
566
0
            parsed
567
0
                .set_offset_hour(0)
568
0
                .ok_or(InvalidComponent("offset hour"))?;
569
0
            parsed
570
0
                .set_offset_minute_signed(0)
571
0
                .ok_or(InvalidComponent("offset minute"))?;
572
0
            parsed
573
0
                .set_offset_second_signed(0)
574
0
                .ok_or(InvalidComponent("offset second"))?;
575
0
            return Ok(input);
576
0
        }
577
578
0
        let ParsedItem(input, offset_sign) = sign(input).ok_or(InvalidComponent("offset hour"))?;
579
0
        let input = exactly_n_digits::<2, u8>(input)
580
0
            .and_then(|item| {
581
0
                item.filter(|&offset_hour| offset_hour <= 23)?
582
0
                    .map(|offset_hour| {
583
0
                        if offset_sign == b'-' {
584
0
                            -offset_hour.cast_signed()
585
                        } else {
586
0
                            offset_hour.cast_signed()
587
                        }
588
0
                    })
589
0
                    .consume_value(|value| parsed.set_offset_hour(value))
590
0
            })
591
0
            .ok_or(InvalidComponent("offset hour"))?;
592
0
        let input = colon(input).ok_or(InvalidLiteral)?.into_inner();
593
0
        let input = exactly_n_digits::<2, u8>(input)
594
0
            .and_then(|item| {
595
0
                item.map(|offset_minute| {
596
0
                    if offset_sign == b'-' {
597
0
                        -offset_minute.cast_signed()
598
                    } else {
599
0
                        offset_minute.cast_signed()
600
                    }
601
0
                })
602
0
                .consume_value(|value| parsed.set_offset_minute_signed(value))
603
0
            })
604
0
            .ok_or(InvalidComponent("offset minute"))?;
605
606
0
        Ok(input)
607
0
    }
608
609
0
    fn parse_offset_date_time(&self, input: &[u8]) -> Result<OffsetDateTime, error::Parse> {
610
        use crate::error::ParseFromDescription::{InvalidComponent, InvalidLiteral};
611
        use crate::parsing::combinator::{
612
            any_digit, ascii_char, ascii_char_ignore_case, exactly_n_digits, sign,
613
        };
614
615
0
        let dash = ascii_char::<b'-'>;
616
0
        let colon = ascii_char::<b':'>;
617
618
0
        let ParsedItem(input, year) =
619
0
            exactly_n_digits::<4, u32>(input).ok_or(InvalidComponent("year"))?;
620
0
        let input = dash(input).ok_or(InvalidLiteral)?.into_inner();
621
0
        let ParsedItem(input, month) =
622
0
            exactly_n_digits::<2, _>(input).ok_or(InvalidComponent("month"))?;
623
0
        let input = dash(input).ok_or(InvalidLiteral)?.into_inner();
624
0
        let ParsedItem(input, day) =
625
0
            exactly_n_digits::<2, _>(input).ok_or(InvalidComponent("day"))?;
626
627
        // RFC3339 allows any separator, not just `T`, not just `space`.
628
        // cf. Section 5.6: Internet Date/Time Format:
629
        //   NOTE: ISO 8601 defines date and time separated by "T".
630
        //   Applications using this syntax may choose, for the sake of
631
        //   readability, to specify a full-date and full-time separated by
632
        //   (say) a space character.
633
        // Specifically, rusqlite uses space separators.
634
0
        let input = input.get(1..).ok_or(InvalidComponent("separator"))?;
635
636
0
        let ParsedItem(input, hour) =
637
0
            exactly_n_digits::<2, _>(input).ok_or(InvalidComponent("hour"))?;
638
0
        let input = colon(input).ok_or(InvalidLiteral)?.into_inner();
639
0
        let ParsedItem(input, minute) =
640
0
            exactly_n_digits::<2, _>(input).ok_or(InvalidComponent("minute"))?;
641
0
        let input = colon(input).ok_or(InvalidLiteral)?.into_inner();
642
0
        let ParsedItem(input, mut second) =
643
0
            exactly_n_digits::<2, _>(input).ok_or(InvalidComponent("second"))?;
644
0
        let ParsedItem(input, mut nanosecond) =
645
0
            if let Some(ParsedItem(input, ())) = ascii_char::<b'.'>(input) {
646
0
                let ParsedItem(mut input, mut value) = any_digit(input)
647
0
                    .ok_or(InvalidComponent("subsecond"))?
648
0
                    .map(|v| (v - b'0').extend::<u32>() * 100_000_000);
649
650
0
                let mut multiplier = 10_000_000;
651
0
                while let Some(ParsedItem(new_input, digit)) = any_digit(input) {
652
0
                    value += (digit - b'0').extend::<u32>() * multiplier;
653
0
                    input = new_input;
654
0
                    multiplier /= 10;
655
0
                }
656
657
0
                ParsedItem(input, value)
658
            } else {
659
0
                ParsedItem(input, 0)
660
            };
661
0
        let ParsedItem(input, offset) = {
662
0
            if let Some(ParsedItem(input, ())) = ascii_char_ignore_case::<b'Z'>(input) {
663
0
                ParsedItem(input, UtcOffset::UTC)
664
            } else {
665
0
                let ParsedItem(input, offset_sign) =
666
0
                    sign(input).ok_or(InvalidComponent("offset hour"))?;
667
0
                let ParsedItem(input, offset_hour) = exactly_n_digits::<2, u8>(input)
668
0
                    .and_then(|parsed| parsed.filter(|&offset_hour| offset_hour <= 23))
669
0
                    .ok_or(InvalidComponent("offset hour"))?;
670
0
                let input = colon(input).ok_or(InvalidLiteral)?.into_inner();
671
0
                let ParsedItem(input, offset_minute) =
672
0
                    exactly_n_digits::<2, u8>(input).ok_or(InvalidComponent("offset minute"))?;
673
0
                UtcOffset::from_hms(
674
0
                    if offset_sign == b'-' {
675
0
                        -offset_hour.cast_signed()
676
                    } else {
677
0
                        offset_hour.cast_signed()
678
                    },
679
0
                    if offset_sign == b'-' {
680
0
                        -offset_minute.cast_signed()
681
                    } else {
682
0
                        offset_minute.cast_signed()
683
                    },
684
                    0,
685
                )
686
0
                .map(|offset| ParsedItem(input, offset))
687
0
                .map_err(|mut err| {
688
                    // Provide the user a more accurate error.
689
0
                    if err.name == "hours" {
690
0
                        err.name = "offset hour";
691
0
                    } else if err.name == "minutes" {
692
0
                        err.name = "offset minute";
693
0
                    }
694
0
                    err
695
0
                })
696
0
                .map_err(TryFromParsed::ComponentRange)?
697
            }
698
        };
699
700
0
        if !input.is_empty() {
701
0
            return Err(error::Parse::ParseFromDescription(
702
0
                error::ParseFromDescription::UnexpectedTrailingCharacters,
703
0
            ));
704
0
        }
705
706
        // The RFC explicitly permits leap seconds. We don't currently support them, so treat it as
707
        // the preceding nanosecond. However, leap seconds can only occur as the last second of the
708
        // month UTC.
709
0
        let leap_second_input = if second == 60 {
710
0
            second = 59;
711
0
            nanosecond = 999_999_999;
712
0
            true
713
        } else {
714
0
            false
715
        };
716
717
0
        let date = Month::from_number(month)
718
0
            .and_then(|month| Date::from_calendar_date(year.cast_signed(), month, day))
719
0
            .map_err(TryFromParsed::ComponentRange)?;
720
0
        let time = Time::from_hms_nano(hour, minute, second, nanosecond)
721
0
            .map_err(TryFromParsed::ComponentRange)?;
722
0
        let dt = OffsetDateTime::new_in_offset(date, time, offset);
723
724
0
        if leap_second_input && !dt.is_valid_leap_second_stand_in() {
725
0
            return Err(error::Parse::TryFromParsed(TryFromParsed::ComponentRange(
726
0
                error::ComponentRange {
727
0
                    name: "second",
728
0
                    minimum: 0,
729
0
                    maximum: 59,
730
0
                    value: 60,
731
0
                    conditional_range: true,
732
0
                },
733
0
            )));
734
0
        }
735
736
0
        Ok(dt)
737
0
    }
738
}
739
740
impl<const CONFIG: EncodedConfig> sealed::Sealed for Iso8601<CONFIG> {
741
0
    fn parse_into<'a>(
742
0
        &self,
743
0
        mut input: &'a [u8],
744
0
        parsed: &mut Parsed,
745
0
    ) -> Result<&'a [u8], error::Parse> {
746
        use crate::parsing::combinator::rfc::iso8601::ExtendedKind;
747
748
0
        let mut extended_kind = ExtendedKind::Unknown;
749
0
        let mut date_is_present = false;
750
0
        let mut time_is_present = false;
751
0
        let mut offset_is_present = false;
752
0
        let mut first_error = None;
753
754
0
        parsed.leap_second_allowed = true;
755
756
0
        match Self::parse_date(parsed, &mut extended_kind)(input) {
757
0
            Ok(new_input) => {
758
0
                input = new_input;
759
0
                date_is_present = true;
760
0
            }
761
0
            Err(err) => {
762
0
                first_error.get_or_insert(err);
763
0
            }
764
        }
765
766
0
        match Self::parse_time(parsed, &mut extended_kind, date_is_present)(input) {
767
0
            Ok(new_input) => {
768
0
                input = new_input;
769
0
                time_is_present = true;
770
0
            }
771
0
            Err(err) => {
772
0
                first_error.get_or_insert(err);
773
0
            }
774
        }
775
776
        // If a date and offset are present, a time must be as well.
777
0
        if !date_is_present || time_is_present {
778
0
            match Self::parse_offset(parsed, &mut extended_kind)(input) {
779
0
                Ok(new_input) => {
780
0
                    input = new_input;
781
0
                    offset_is_present = true;
782
0
                }
783
0
                Err(err) => {
784
0
                    first_error.get_or_insert(err);
785
0
                }
786
            }
787
0
        }
788
789
0
        if !date_is_present && !time_is_present && !offset_is_present {
790
0
            match first_error {
791
0
                Some(err) => return Err(err),
792
0
                None => bug!("an error should be present if no components were parsed"),
793
            }
794
0
        }
795
796
0
        Ok(input)
797
0
    }
798
}
799
// endregion well-known formats