ixdtf/parsers/
time.rs

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
// 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 ).

//! Parsing of Time Values

use crate::{
    assert_syntax,
    parsers::{
        grammar::{
            is_annotation_open, is_decimal_separator, is_sign, is_time_designator,
            is_time_separator, is_utc_designator,
        },
        records::{Annotation, TimeRecord},
        timezone::parse_date_time_utc,
        Cursor,
    },
    ParseError, ParserResult,
};

use super::{annotations, records::IxdtfParseRecord};

/// Parse annotated time record is silently fallible returning None in the case that the
/// value does not align
pub(crate) fn parse_annotated_time_record<'a>(
    cursor: &mut Cursor<'a>,
    handler: impl FnMut(Annotation<'a>) -> Option<Annotation<'a>>,
) -> ParserResult<IxdtfParseRecord<'a>> {
    let designator = cursor.check_or(false, is_time_designator);
    cursor.advance_if(designator);

    let time = parse_time_record(cursor)?;

    // If Time was successfully parsed, assume from this point that this IS a
    // valid AnnotatedTimeRecord.

    let offset = if cursor.check_or(false, |ch| is_sign(ch) || is_utc_designator(ch)) {
        Some(parse_date_time_utc(cursor)?)
    } else {
        None
    };

    // Check if annotations exist.
    if !cursor.check_or(false, is_annotation_open) {
        cursor.close()?;

        return Ok(IxdtfParseRecord {
            date: None,
            time: Some(time),
            offset,
            tz: None,
            calendar: None,
        });
    }

    let annotations = annotations::parse_annotation_set(cursor, handler)?;

    cursor.close()?;

    Ok(IxdtfParseRecord {
        date: None,
        time: Some(time),
        offset,
        tz: annotations.tz,
        calendar: annotations.calendar,
    })
}

/// Parse `TimeRecord`
pub(crate) fn parse_time_record(cursor: &mut Cursor) -> ParserResult<TimeRecord> {
    let hour = parse_hour(cursor)?;

    if !cursor.check_or(false, |ch| is_time_separator(ch) || ch.is_ascii_digit()) {
        return Ok(TimeRecord {
            hour,
            minute: 0,
            second: 0,
            nanosecond: 0,
        });
    }

    let separator_present = cursor.check_or(false, is_time_separator);
    cursor.advance_if(separator_present);

    let minute = parse_minute_second(cursor, false)?;

    if !cursor.check_or(false, |ch| is_time_separator(ch) || ch.is_ascii_digit()) {
        return Ok(TimeRecord {
            hour,
            minute,
            second: 0,
            nanosecond: 0,
        });
    }

    let second_separator = cursor.check_or(false, is_time_separator);
    assert_syntax!(separator_present == second_separator, TimeSeparator);
    cursor.advance_if(second_separator);

    let second = parse_minute_second(cursor, true)?;

    let nanosecond = parse_fraction(cursor)?.unwrap_or(0);

    Ok(TimeRecord {
        hour,
        minute,
        second,
        nanosecond,
    })
}

/// Parse an hour value.
#[inline]
pub(crate) fn parse_hour(cursor: &mut Cursor) -> ParserResult<u8> {
    let first = cursor.next_digit()?.ok_or(ParseError::TimeHour)?;
    let hour_value = first * 10 + cursor.next_digit()?.ok_or(ParseError::TimeHour)?;
    if !(0..=23).contains(&hour_value) {
        return Err(ParseError::TimeHour);
    }
    Ok(hour_value)
}

/// Parses `MinuteSecond` value.
#[inline]
pub(crate) fn parse_minute_second(cursor: &mut Cursor, is_second: bool) -> ParserResult<u8> {
    let (valid_range, err) = if is_second {
        (0..=60, ParseError::TimeSecond)
    } else {
        (0..=59, ParseError::TimeMinute)
    };
    let first = cursor.next_digit()?.ok_or(err)?;
    let min_sec_value = first * 10 + cursor.next_digit()?.ok_or(err)?;
    if !valid_range.contains(&min_sec_value) {
        return Err(err);
    }
    Ok(min_sec_value)
}

/// Parse a `Fraction` value
///
/// This is primarily used in ISO8601 to add percision past
/// a second.
#[inline]
pub(crate) fn parse_fraction(cursor: &mut Cursor) -> ParserResult<Option<u32>> {
    // Assert that the first char provided is a decimal separator.
    if !cursor.check_or(false, is_decimal_separator) {
        return Ok(None);
    }
    cursor.next_or(ParseError::FractionPart)?;

    let mut result = 0;
    let mut fraction_len = 0;
    while cursor.check_or(false, |ch| ch.is_ascii_digit()) {
        if fraction_len > 9 {
            return Err(ParseError::FractionPart);
        }
        result = result * 10 + u32::from(cursor.next_digit()?.ok_or(ParseError::FractionPart)?);
        fraction_len += 1;
    }

    // Assert: 10^9-1 should always be a valid u32.
    let result = result
        * 10u32
            .checked_pow(9 - fraction_len)
            .ok_or(ParseError::ImplAssert)?;

    Ok(Some(result))
}