ixdtf/parsers/
duration.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
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
// 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 ).

//! This module implements logic for Duration parsing.

use crate::{
    assert_syntax,
    parsers::{
        grammar::{
            is_day_designator, is_duration_designator, is_hour_designator, is_minute_designator,
            is_month_designator, is_second_designator, is_sign, is_time_designator,
            is_week_designator, is_year_designator,
        },
        records::{DateDurationRecord, DurationParseRecord, TimeDurationRecord},
        time::parse_fraction,
        Cursor,
    },
    ParseError, ParserResult,
};

pub(crate) fn parse_duration(cursor: &mut Cursor) -> ParserResult<DurationParseRecord> {
    let sign = if cursor
        .check(is_sign)
        .ok_or_else(|| ParseError::abrupt_end("DurationStart"))?
    {
        cursor.next_or(ParseError::ImplAssert)? == '+'
    } else {
        true
    };

    assert_syntax!(
        is_duration_designator(cursor.next_or(ParseError::abrupt_end("DurationDesignator"))?),
        DurationDisgnator,
    );

    let date = if cursor.check_or(false, is_time_designator) {
        None
    } else {
        Some(parse_date_duration(cursor)?)
    };

    let time = parse_time_duration(cursor)?;

    cursor.close()?;

    Ok(DurationParseRecord {
        sign: sign.into(),
        date,
        time,
    })
}

#[derive(PartialEq, PartialOrd, Eq, Ord)]
enum DateUnit {
    None = 0,
    Year,
    Month,
    Week,
    Day,
}

pub(crate) fn parse_date_duration(cursor: &mut Cursor) -> ParserResult<DateDurationRecord> {
    let mut date = DateDurationRecord::default();
    let mut previous_unit = DateUnit::None;

    while cursor.check_or(false, |ch| ch.is_ascii_digit()) {
        let mut value: u32 = 0;
        while cursor.check_or(false, |ch| ch.is_ascii_digit()) {
            let digit = cursor
                .next_digit()?
                .ok_or_else(|| ParseError::abrupt_end("DateDuration"))?;
            value = value
                .checked_mul(10)
                .and_then(|v| v.checked_add(u32::from(digit)))
                .ok_or(ParseError::DurationValueExceededRange)?
        }

        match cursor.next() {
            Some(ch) if is_year_designator(ch) => {
                if previous_unit > DateUnit::Year {
                    return Err(ParseError::DateDurationPartOrder);
                }
                date.years = value;
                previous_unit = DateUnit::Year;
            }
            Some(ch) if is_month_designator(ch) => {
                if previous_unit > DateUnit::Month {
                    return Err(ParseError::DateDurationPartOrder);
                }
                date.months = value;
                previous_unit = DateUnit::Month;
            }
            Some(ch) if is_week_designator(ch) => {
                if previous_unit > DateUnit::Week {
                    return Err(ParseError::DateDurationPartOrder);
                }
                date.weeks = value;
                previous_unit = DateUnit::Week;
            }
            Some(ch) if is_day_designator(ch) => {
                if previous_unit > DateUnit::Day {
                    return Err(ParseError::DateDurationPartOrder);
                }
                date.days = value;
                previous_unit = DateUnit::Day;
            }
            Some(_) | None => return Err(ParseError::abrupt_end("DateDurationDesignator")),
        }
    }

    Ok(date)
}

#[derive(PartialEq, PartialOrd, Eq, Ord)]
enum TimeUnit {
    None = 0,
    Hour,
    Minute,
    Second,
}

pub(crate) fn parse_time_duration(cursor: &mut Cursor) -> ParserResult<Option<TimeDurationRecord>> {
    if !cursor.check_or(false, is_time_designator) {
        return Ok(None);
    };

    cursor.advance();
    assert_syntax!(
        cursor.check_or(false, |c| c.is_ascii_digit()),
        TimeDurationDesignator,
    );

    let mut time: (u32, u32, u32, Option<u32>) = (0, 0, 0, None);
    let mut previous_unit = TimeUnit::None;
    while cursor.check_or(false, |c| c.is_ascii_digit()) {
        let mut value: u32 = 0;
        while cursor.check_or(false, |c| c.is_ascii_digit()) {
            let digit = cursor
                .next_digit()?
                .ok_or_else(|| ParseError::abrupt_end("TimeDurationDigit"))?;
            value = value
                .checked_mul(10)
                .and_then(|v| v.checked_add(u32::from(digit)))
                .ok_or(ParseError::DurationValueExceededRange)?
        }

        let fraction = parse_fraction(cursor)?;

        match cursor.next() {
            Some(ch) if is_hour_designator(ch) => {
                if previous_unit > TimeUnit::Hour {
                    return Err(ParseError::TimeDurationPartOrder);
                }
                time.0 = value;
                if let Some(fraction) = fraction {
                    time.3 = Some(fraction);
                };
                previous_unit = TimeUnit::Hour;
            }
            Some(ch) if is_minute_designator(ch) => {
                if previous_unit > TimeUnit::Minute {
                    return Err(ParseError::TimeDurationPartOrder);
                }
                time.1 = value;
                if let Some(fraction) = fraction {
                    time.3 = Some(fraction);
                }
                previous_unit = TimeUnit::Minute;
            }
            Some(ch) if is_second_designator(ch) => {
                if previous_unit > TimeUnit::Second {
                    return Err(ParseError::TimeDurationPartOrder);
                }
                time.2 = value;
                if let Some(fraction) = fraction {
                    time.3 = Some(fraction);
                }
                previous_unit = TimeUnit::Second;
            }
            Some(_) | None => return Err(ParseError::abrupt_end("TimeDurationDesignator")),
        }

        if fraction.is_some() {
            assert_syntax!(cursor.check_or(true, |ch| !ch.is_ascii_digit()), InvalidEnd,);
            break;
        }
    }

    match previous_unit {
        // Safety: Max fraction * 3600 is within u64 -> see test maximum_duration_fraction
        TimeUnit::Hour => Ok(Some(TimeDurationRecord::Hours {
            hours: time.0,
            fraction: time.3.map(|f| 3600 * u64::from(f)).unwrap_or(0),
        })),
        // Safety: Max fraction * 60 is within u64 -> see test maximum_duration_fraction
        TimeUnit::Minute => Ok(Some(TimeDurationRecord::Minutes {
            hours: time.0,
            minutes: time.1,
            fraction: time.3.map(|f| 60 * u64::from(f)).unwrap_or(0),
        })),
        TimeUnit::Second => Ok(Some(TimeDurationRecord::Seconds {
            hours: time.0,
            minutes: time.1,
            seconds: time.2,
            fraction: time.3.unwrap_or(0),
        })),
        TimeUnit::None => Err(ParseError::abrupt_end("TimeDUrationDesignator")),
    }
}