Skip to main content

time_zone/
parse.rs

1//! Parser for POSIX TZ strings, the `TZ` format of POSIX `tzset`:
2//! `std offset [dst [offset] [,rule,rule]]`.
3//!
4//! See [`TimeZone::parse`] for the accepted format and the defaults. A name is
5//! either at least three letters (`CET`) or quoted in angle brackets
6//! (`<+03>`); a quoted name may hold only ASCII alphanumeric characters, `+`
7//! and `-`, and at most 7 bytes so that it fits the abbreviation buffer of
8//! [`TimeZone`]. Offsets are `[+-]hh[:mm[:ss]]` within 24 hours. Rules are
9//! `Mm.w.d[/time]`, `Jn[/time]` or `n[/time]`; a rule time is a signed
10//! `[+-]hh[:mm[:ss]]` within the POSIX 2024 range of 167 hours, and it defaults
11//! to 02:00:00. Minutes and seconds are always 0 to 59.
12
13use crate::rule::{Rule, RuleKind};
14use crate::zone::{ABBREVIATION_MAX, Abbreviation, TimeZone};
15use core::fmt;
16
17/// Default start rule when a daylight saving name is given without rules:
18/// `M3.2.0`, with the default time 02:00:00.
19const DEFAULT_START: Rule = Rule::implicit(RuleKind::MonthWeekDay, 77);
20
21/// Default end rule when a daylight saving name is given without rules:
22/// `M11.1.0`, with the default time 02:00:00.
23const DEFAULT_END: Rule = Rule::implicit(RuleKind::MonthWeekDay, 350);
24
25/// The largest zone offset of POSIX: 24 hours.
26const MAX_OFFSET_SECONDS: i64 = 24 * 3600;
27
28/// The largest rule time of POSIX 2024: 167:59:59.
29const MAX_RULE_TIME_SECONDS: i64 = 167 * 3600 + 59 * 60 + 59;
30
31/// Why a POSIX TZ string was rejected.
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
33#[repr(u8)]
34pub enum ParseError {
35    /// The string is empty.
36    Empty,
37    /// The string does not start with a zone name.
38    MissingName,
39    /// A zone name has fewer than three bytes.
40    NameTooShort,
41    /// A zone name has a character that is not allowed: a quoted name may hold
42    /// only ASCII alphanumeric characters, `+` and `-`.
43    InvalidNameCharacter,
44    /// A zone name is longer than the 7 bytes of the abbreviation buffer.
45    NameTooLong,
46    /// A quoted name is not closed with `>`.
47    UnterminatedName,
48    /// The standard offset is missing.
49    MissingOffset,
50    /// The standard offset is malformed, or its minutes or seconds are above
51    /// 59.
52    InvalidOffset,
53    /// The standard offset is larger than 24 hours.
54    OffsetOutOfRange,
55    /// Rules are given without a daylight saving name.
56    RulesWithoutDaylightSaving,
57    /// A transition rule is malformed.
58    InvalidRule,
59    /// A number of a rule is out of its range.
60    RuleOutOfRange,
61    /// A rule time is malformed, or its minutes or seconds are above 59.
62    InvalidTime,
63    /// A rule time is larger than 167 hours.
64    TimeOutOfRange,
65    /// The comma-separated rule pair has only one rule.
66    MissingEndRule,
67    /// Extra characters follow a complete TZ string.
68    TrailingCharacters,
69}
70
71impl fmt::Display for ParseError {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.write_str(match self {
74            ParseError::Empty => "the TZ string is empty",
75            ParseError::MissingName => "a zone name is missing",
76            ParseError::NameTooShort => "a zone name has fewer than three bytes",
77            ParseError::InvalidNameCharacter => {
78                "a quoted zone name has a character that is not ASCII alphanumeric, + or -"
79            }
80            ParseError::NameTooLong => "a zone name is longer than 7 bytes",
81            ParseError::UnterminatedName => "a quoted zone name is not closed",
82            ParseError::MissingOffset => "the standard offset is missing",
83            ParseError::InvalidOffset => {
84                "the standard offset is malformed, or its minutes or seconds are above 59"
85            }
86            ParseError::OffsetOutOfRange => "the standard offset is larger than 24 hours",
87            ParseError::RulesWithoutDaylightSaving => {
88                "rules are given without a daylight saving name"
89            }
90            ParseError::InvalidRule => "a transition rule is malformed",
91            ParseError::RuleOutOfRange => "a number of a rule is out of range",
92            ParseError::InvalidTime => {
93                "a rule time is malformed, or its minutes or seconds are above 59"
94            }
95            ParseError::TimeOutOfRange => "a rule time is larger than 167 hours",
96            ParseError::MissingEndRule => "the rule pair has only one rule",
97            ParseError::TrailingCharacters => "extra characters follow the TZ string",
98        })
99    }
100}
101
102impl core::error::Error for ParseError {}
103
104/// Parse a POSIX TZ string into an owned [`TimeZone`].
105pub(crate) fn parse(input: &str) -> Result<TimeZone, ParseError> {
106    Parser { input, pos: 0 }.parse_zone()
107}
108
109struct Parser<'a> {
110    input: &'a str,
111    pos: usize,
112}
113
114impl<'a> Parser<'a> {
115    fn peek(&self) -> Option<u8> {
116        self.input.as_bytes().get(self.pos).copied()
117    }
118
119    fn eat(&mut self, byte: u8) -> bool {
120        if self.peek() == Some(byte) {
121            self.pos += 1;
122            true
123        } else {
124            false
125        }
126    }
127
128    /// Read up to `max` decimal digits. Returns the value and how many digits
129    /// were read, or None when there is no digit.
130    fn digits(&mut self, max: usize) -> Option<(i64, usize)> {
131        let start = self.pos;
132        let bytes = self.input.as_bytes();
133        let mut value: i64 = 0;
134        while self.pos < bytes.len() && self.pos - start < max && bytes[self.pos].is_ascii_digit() {
135            value = value * 10 + i64::from(bytes[self.pos] - b'0');
136            self.pos += 1;
137        }
138        if self.pos == start {
139            None
140        } else {
141            Some((value, self.pos - start))
142        }
143    }
144
145    /// Read `[+-]hh[:mm[:ss]]` and return the signed value in seconds. The
146    /// minutes and seconds must be 0 to 59.
147    fn parse_hours_minutes_seconds(
148        &mut self,
149        missing: ParseError,
150        invalid: ParseError,
151    ) -> Result<i64, ParseError> {
152        let sign = match self.peek() {
153            Some(b'-') => {
154                self.pos += 1;
155                -1
156            }
157            Some(b'+') => {
158                self.pos += 1;
159                1
160            }
161            _ => 1,
162        };
163        let (hours, _) = self.digits(3).ok_or(missing)?;
164        let mut total = hours * 3600;
165        if self.peek() == Some(b':') {
166            self.pos += 1;
167            let (minutes, count) = self.digits(2).ok_or(invalid)?;
168            if count != 2 || minutes > 59 {
169                return Err(invalid);
170            }
171            total += minutes * 60;
172            if self.peek() == Some(b':') {
173                self.pos += 1;
174                let (seconds, count) = self.digits(2).ok_or(invalid)?;
175                if count != 2 || seconds > 59 {
176                    return Err(invalid);
177                }
178                total += seconds;
179            }
180        }
181        Ok(sign * total)
182    }
183
184    /// Read a zone name: `<...>` or at least three letters. Returns the name
185    /// and its end position.
186    fn parse_name(&mut self) -> Result<&'a str, ParseError> {
187        if self.peek() == Some(b'<') {
188            self.pos += 1;
189            let start = self.pos;
190            loop {
191                match self.peek() {
192                    None => return Err(ParseError::UnterminatedName),
193                    Some(b'>') => {
194                        let name = &self.input[start..self.pos];
195                        self.pos += 1;
196                        if name.len() < 3 {
197                            return Err(ParseError::NameTooShort);
198                        }
199                        if name.len() > ABBREVIATION_MAX {
200                            return Err(ParseError::NameTooLong);
201                        }
202                        if !name.bytes().all(|byte| {
203                            byte.is_ascii_alphanumeric() || byte == b'+' || byte == b'-'
204                        }) {
205                            return Err(ParseError::InvalidNameCharacter);
206                        }
207                        return Ok(name);
208                    }
209                    Some(_) => self.pos += 1,
210                }
211            }
212        }
213        let start = self.pos;
214        while matches!(self.peek(), Some(byte) if byte.is_ascii_alphabetic()) {
215            self.pos += 1;
216        }
217        let name = &self.input[start..self.pos];
218        if name.is_empty() {
219            return Err(ParseError::MissingName);
220        }
221        if name.len() < 3 {
222            return Err(ParseError::NameTooShort);
223        }
224        if name.len() > ABBREVIATION_MAX {
225            return Err(ParseError::NameTooLong);
226        }
227        Ok(name)
228    }
229
230    /// Read a zone offset and return it in POSIX form, positive west of UTC.
231    fn parse_zone_offset(&mut self) -> Result<i64, ParseError> {
232        let value =
233            self.parse_hours_minutes_seconds(ParseError::MissingOffset, ParseError::InvalidOffset)?;
234        if value.abs() > MAX_OFFSET_SECONDS {
235            return Err(ParseError::OffsetOutOfRange);
236        }
237        Ok(value)
238    }
239
240    /// Read one transition rule.
241    fn parse_rule(&mut self) -> Result<Rule, ParseError> {
242        let (kind, date) = match self.peek() {
243            Some(b'M') => {
244                self.pos += 1;
245                let (month, _) = self.digits(2).ok_or(ParseError::InvalidRule)?;
246                if !(1..=12).contains(&month) {
247                    return Err(ParseError::RuleOutOfRange);
248                }
249                if !self.eat(b'.') {
250                    return Err(ParseError::InvalidRule);
251                }
252                let (week, _) = self.digits(1).ok_or(ParseError::InvalidRule)?;
253                if !(1..=5).contains(&week) {
254                    return Err(ParseError::RuleOutOfRange);
255                }
256                if !self.eat(b'.') {
257                    return Err(ParseError::InvalidRule);
258                }
259                let (weekday, _) = self.digits(1).ok_or(ParseError::InvalidRule)?;
260                if weekday > 6 {
261                    return Err(ParseError::RuleOutOfRange);
262                }
263                let code = ((month - 1) * 5 + (week - 1)) * 7 + weekday;
264                (RuleKind::MonthWeekDay, code as u16)
265            }
266            Some(b'J') => {
267                self.pos += 1;
268                let (day, _) = self.digits(3).ok_or(ParseError::InvalidRule)?;
269                if !(1..=365).contains(&day) {
270                    return Err(ParseError::RuleOutOfRange);
271                }
272                (RuleKind::JulianNoLeap, (day - 1) as u16)
273            }
274            Some(byte) if byte.is_ascii_digit() => {
275                let (day, _) = self.digits(3).ok_or(ParseError::InvalidRule)?;
276                if day > 365 {
277                    return Err(ParseError::RuleOutOfRange);
278                }
279                (RuleKind::ZeroBasedDay, day as u16)
280            }
281            _ => return Err(ParseError::InvalidRule),
282        };
283        if self.eat(b'/') {
284            let value =
285                self.parse_hours_minutes_seconds(ParseError::InvalidTime, ParseError::InvalidTime)?;
286            if value.abs() > MAX_RULE_TIME_SECONDS {
287                return Err(ParseError::TimeOutOfRange);
288            }
289            Ok(Rule::new(kind, date, value as i32))
290        } else {
291            Ok(Rule::implicit(kind, date))
292        }
293    }
294
295    fn parse_zone(&mut self) -> Result<TimeZone, ParseError> {
296        if self.input.is_empty() {
297            return Err(ParseError::Empty);
298        }
299        let standard_name = self.parse_name()?;
300        // POSIX offsets are positive west of UTC; store seconds east of UTC.
301        let standard_offset = -self.parse_zone_offset()? as i32;
302        if self.pos >= self.input.len() {
303            return Ok(TimeZone::fixed(
304                Abbreviation::from_name(standard_name).ok_or(ParseError::NameTooLong)?,
305                standard_offset,
306            ));
307        }
308        if self.peek() == Some(b',') {
309            return Err(ParseError::RulesWithoutDaylightSaving);
310        }
311        let daylight_saving_name = self.parse_name()?;
312        let next_starts_offset = match self.peek() {
313            Some(b'+') | Some(b'-') => true,
314            Some(byte) => byte.is_ascii_digit(),
315            None => false,
316        };
317        let daylight_saving_offset = if next_starts_offset {
318            -self.parse_zone_offset()? as i32
319        } else {
320            standard_offset + 3600
321        };
322        let (start, end) = if self.eat(b',') {
323            let start = self.parse_rule()?;
324            if !self.eat(b',') {
325                return Err(ParseError::MissingEndRule);
326            }
327            let end = self.parse_rule()?;
328            (start, end)
329        } else {
330            (DEFAULT_START, DEFAULT_END)
331        };
332        if self.pos < self.input.len() {
333            return Err(ParseError::TrailingCharacters);
334        }
335        Ok(TimeZone::with_daylight_saving(
336            Abbreviation::from_name(standard_name).ok_or(ParseError::NameTooLong)?,
337            standard_offset,
338            Abbreviation::from_name(daylight_saving_name).ok_or(ParseError::NameTooLong)?,
339            daylight_saving_offset,
340            start,
341            end,
342        ))
343    }
344}