Skip to main content

sql_values/zone/
tznames.rs

1//! PostgreSQL 18's `timezone_abbreviations` files as `tzparser.c` reads them, and the lookup
2//! `DecodeTimezoneAbbrev` runs in the table they make. The build script compiles this module
3//! too, to bundle PostgreSQL's own sets as static tables.
4
5use alloc::{borrow::Cow, string::String, vec::Vec};
6
7/// `TOKMAXLEN`, the longest abbreviation a set holds and the prefix a lookup compares.
8const TOKEN_MAX_LEN: usize = 10;
9/// The largest offset `validateTzEntry` takes, 14 hours in seconds.
10const MAX_OFFSET: i64 = 14 * 3_600;
11/// `fgets`' buffer, which a line must leave a byte of.
12const LINE_BUFFER: usize = 1_024;
13/// The deepest `@INCLUDE` nesting `ParseTzFile` follows.
14const MAX_DEPTH: usize = 3;
15/// `WHITESPACE`, the bytes `strtok_r` splits a line at.
16const WHITESPACE: &[u8] = b" \t\n\r";
17
18/// What an abbreviation stands for.
19#[derive(Debug, Clone, PartialEq, Eq, Hash)]
20pub(crate) enum Meaning {
21    /// A fixed offset east of UTC in seconds, `TZ` or, for daylight saving time, `DTZ`.
22    Fixed { offset: i32, dst: bool },
23    /// `DYNTZ`, the meaning the abbreviation has in a time zone at the literal's date.
24    Zone(Cow<'static, str>),
25}
26
27/// One entry of a set, its abbreviation lowercased as `validateTzEntry` leaves it.
28#[derive(Debug, Clone, PartialEq, Eq, Hash)]
29pub(crate) struct Abbreviation {
30    pub(crate) token: Cow<'static, str>,
31    pub(crate) meaning: Meaning,
32}
33
34/// Why PostgreSQL refuses a time zone abbreviation file, one variant per message `tzparser.c`
35/// raises.
36#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
37pub enum TimeZoneAbbreviationsError {
38    /// A file name with a character that is not a letter.
39    #[error("invalid time zone file name \"{file}\"")]
40    InvalidFileName {
41        /// The file named.
42        file: String,
43    },
44    /// An `@INCLUDE` nested more than three deep.
45    #[error("time zone file recursion limit exceeded in file \"{file}\"")]
46    RecursionLimit {
47        /// The file that would have been read.
48        file: String,
49    },
50    /// A file the caller's files do not have.
51    #[error("could not read time zone file \"{file}\"")]
52    FileNotFound {
53        /// The file named.
54        file: String,
55    },
56    /// A line of 1023 bytes or more.
57    #[error("line is too long in time zone file \"{file}\", line {line}")]
58    LineTooLong {
59        /// The file holding the line.
60        file: String,
61        /// The line, from 1.
62        line: usize,
63    },
64    /// An `@INCLUDE` naming no file.
65    #[error("@INCLUDE without file name in time zone file \"{file}\", line {line}")]
66    IncludeWithoutFileName {
67        /// The file holding the line.
68        file: String,
69        /// The line, from 1.
70        line: usize,
71    },
72    /// An abbreviation with nothing after it.
73    #[error("missing time zone offset in time zone file \"{file}\", line {line}")]
74    MissingOffset {
75        /// The file holding the line.
76        file: String,
77        /// The line, from 1.
78        line: usize,
79    },
80    /// An offset with characters after its digits.
81    #[error("invalid number for time zone offset in time zone file \"{file}\", line {line}")]
82    InvalidOffset {
83        /// The file holding the line.
84        file: String,
85        /// The line, from 1.
86        line: usize,
87    },
88    /// Something other than a comment after an entry.
89    #[error("invalid syntax in time zone file \"{file}\", line {line}")]
90    InvalidSyntax {
91        /// The file holding the line.
92        file: String,
93        /// The line, from 1.
94        line: usize,
95    },
96    /// An abbreviation longer than 10 bytes.
97    #[error(
98        "time zone abbreviation \"{abbreviation}\" is too long (maximum 10 characters) in time zone file \"{file}\", line {line}"
99    )]
100    AbbreviationTooLong {
101        /// The abbreviation as written.
102        abbreviation: String,
103        /// The file holding the line.
104        file: String,
105        /// The line, from 1.
106        line: usize,
107    },
108    /// An offset beyond 14 hours either side of UTC.
109    #[error("time zone offset {offset} is out of range in time zone file \"{file}\", line {line}")]
110    OffsetOutOfRange {
111        /// The offset in seconds, as C's `int` holds it.
112        offset: i32,
113        /// The file holding the line.
114        file: String,
115        /// The line, from 1.
116        line: usize,
117    },
118    /// An abbreviation defined twice with different meanings and no `@OVERRIDE` before the
119    /// second.
120    #[error("time zone abbreviation \"{abbreviation}\" is multiply defined")]
121    MultiplyDefined {
122        /// The abbreviation, lowercased.
123        abbreviation: String,
124        /// The file holding the second definition.
125        file: String,
126        /// Its line, from 1.
127        line: usize,
128    },
129}
130
131/// Where an entry was read, for its errors.
132struct Place<'a> {
133    file: &'a str,
134    line: usize,
135}
136
137impl Place<'_> {
138    fn file(&self) -> String {
139        String::from(self.file)
140    }
141}
142
143/// C's `isspace` in the C locale.
144const fn is_space(byte: u8) -> bool {
145    matches!(byte, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
146}
147
148/// `strtok_r` over `WHITESPACE`, the next token and what follows it.
149fn next_token(bytes: &[u8]) -> Option<(&[u8], &[u8])> {
150    let start = bytes.iter().position(|b| !WHITESPACE.contains(b))?;
151    let rest = &bytes[start..];
152    let end = rest
153        .iter()
154        .position(|b| WHITESPACE.contains(b))
155        .unwrap_or(rest.len());
156    Some((&rest[..end], &rest[end..]))
157}
158
159/// C's `strtol` in base 10 over a whole token, saturating on overflow, then the conversion to
160/// `int` that keeps its low 32 bits. `None` when characters follow the digits.
161fn strtol_int(token: &[u8]) -> Option<i32> {
162    let (negative, digits) = match token.split_first() {
163        Some((b'-', rest)) => (true, rest),
164        Some((b'+', rest)) => (false, rest),
165        _ => (false, token),
166    };
167    if digits.is_empty() || !digits.iter().all(u8::is_ascii_digit) {
168        return None;
169    }
170    // Past 2^64 every value saturates to `LONG_MIN` or `LONG_MAX` alike.
171    let magnitude = digits.iter().fold(0i128, |value, &digit| {
172        (value * 10 + i128::from(digit - b'0')).min(1 << 64)
173    });
174    let signed = if negative { -magnitude } else { magnitude };
175    let long = signed.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
176    // Intended loss, as C's assignment of a `long` to an `int` keeps its low 32 bits.
177    Some(long as i32)
178}
179
180/// `splitTzLine` and `validateTzEntry`, the entry a line defines.
181fn split_line(line: &[u8], place: &Place<'_>) -> Result<Abbreviation, TimeZoneAbbreviationsError> {
182    let (abbreviation, rest) = next_token(line).expect("a line past its blanks has a token");
183    let Some((value, rest)) = next_token(rest) else {
184        return Err(TimeZoneAbbreviationsError::MissingOffset {
185            file: place.file(),
186            line: place.line,
187        });
188    };
189    let (meaning, rest) = if matches!(value.first(), Some(b'0'..=b'9' | b'+' | b'-')) {
190        let offset =
191            strtol_int(value).ok_or_else(|| TimeZoneAbbreviationsError::InvalidOffset {
192                file: place.file(),
193                line: place.line,
194            })?;
195        match next_token(rest) {
196            Some((flag, after)) if flag.eq_ignore_ascii_case(b"D") => {
197                (Meaning::Fixed { offset, dst: true }, after)
198            }
199            _ => (Meaning::Fixed { offset, dst: false }, rest),
200        }
201    } else {
202        let zone = String::from_utf8_lossy(value).into_owned();
203        (Meaning::Zone(Cow::Owned(zone)), rest)
204    };
205    if next_token(rest).is_some_and(|(remain, _)| remain[0] != b'#') {
206        return Err(TimeZoneAbbreviationsError::InvalidSyntax {
207            file: place.file(),
208            line: place.line,
209        });
210    }
211    let written = String::from_utf8_lossy(abbreviation).into_owned();
212    if abbreviation.len() > TOKEN_MAX_LEN {
213        return Err(TimeZoneAbbreviationsError::AbbreviationTooLong {
214            abbreviation: written,
215            file: place.file(),
216            line: place.line,
217        });
218    }
219    if let Meaning::Fixed { offset, .. } = meaning
220        && !(-MAX_OFFSET..=MAX_OFFSET).contains(&i64::from(offset))
221    {
222        return Err(TimeZoneAbbreviationsError::OffsetOutOfRange {
223            offset,
224            file: place.file(),
225            line: place.line,
226        });
227    }
228    Ok(Abbreviation {
229        token: Cow::Owned(written.to_ascii_lowercase()),
230        meaning,
231    })
232}
233
234/// `addToArray`, inserting `entry` in token order, keeping an identical earlier entry, and
235/// replacing a different one only after `@OVERRIDE`.
236fn add(
237    entries: &mut Vec<Abbreviation>,
238    entry: Abbreviation,
239    replace: bool,
240    place: &Place<'_>,
241) -> Result<(), TimeZoneAbbreviationsError> {
242    match entries.binary_search_by(|probe| probe.token.as_bytes().cmp(entry.token.as_bytes())) {
243        Ok(at) if entries[at].meaning == entry.meaning => Ok(()),
244        Ok(at) if replace => {
245            entries[at].meaning = entry.meaning;
246            Ok(())
247        }
248        Ok(_) => Err(TimeZoneAbbreviationsError::MultiplyDefined {
249            abbreviation: String::from(entry.token),
250            file: place.file(),
251            line: place.line,
252        }),
253        Err(at) => {
254            entries.insert(at, entry);
255            Ok(())
256        }
257    }
258}
259
260/// `ParseTzFile`, reading the file `name` the caller's `files` hold into `entries`.
261pub(crate) fn parse_file<'f>(
262    name: &str,
263    depth: usize,
264    files: &mut dyn FnMut(&str) -> Option<&'f str>,
265    entries: &mut Vec<Abbreviation>,
266) -> Result<(), TimeZoneAbbreviationsError> {
267    if !name.bytes().all(|b| b.is_ascii_alphabetic()) {
268        return Err(TimeZoneAbbreviationsError::InvalidFileName {
269            file: String::from(name),
270        });
271    }
272    if depth > MAX_DEPTH {
273        return Err(TimeZoneAbbreviationsError::RecursionLimit {
274            file: String::from(name),
275        });
276    }
277    let text = files(name).ok_or_else(|| TimeZoneAbbreviationsError::FileNotFound {
278        file: String::from(name),
279    })?;
280    let mut replace = false;
281    for (index, raw) in text.as_bytes().split_inclusive(|&b| b == b'\n').enumerate() {
282        let place = Place {
283            file: name,
284            line: index + 1,
285        };
286        if raw.len() >= LINE_BUFFER - 1 {
287            return Err(TimeZoneAbbreviationsError::LineTooLong {
288                file: place.file(),
289                line: place.line,
290            });
291        }
292        let start = raw.iter().take_while(|&&b| is_space(b)).count();
293        let line = &raw[start..];
294        if line.is_empty() || line[0] == b'#' {
295            continue;
296        }
297        let directive = |word: &[u8]| {
298            line.get(..word.len())
299                .is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
300        };
301        if directive(b"@INCLUDE") {
302            let Some((include, _)) = next_token(&line[8..]) else {
303                return Err(TimeZoneAbbreviationsError::IncludeWithoutFileName {
304                    file: place.file(),
305                    line: place.line,
306                });
307            };
308            let include = String::from_utf8_lossy(include);
309            parse_file(&include, depth + 1, files, entries)?;
310            continue;
311        }
312        if directive(b"@OVERRIDE") {
313            replace = true;
314            continue;
315        }
316        let entry = split_line(line, &place)?;
317        add(entries, entry, replace, &place)?;
318    }
319    Ok(())
320}
321
322/// `datebsearch` with `strncmp` over `TOKMAXLEN` bytes, so that a key longer than ten bytes
323/// matches the ten-byte abbreviation it starts with.
324pub(crate) fn search<'e>(entries: &'e [Abbreviation], key: &[u8]) -> Option<&'e Abbreviation> {
325    let key = &key[..key.len().min(TOKEN_MAX_LEN)];
326    entries
327        .binary_search_by(|probe| probe.token.as_bytes().cmp(key))
328        .ok()
329        .map(|at| &entries[at])
330}