sql_values/postgres/zone/
tznames.rs1use alloc::{borrow::Cow, string::String, vec::Vec};
6
7const TOKEN_MAX_LEN: usize = 10;
9const MAX_OFFSET: i64 = 14 * 3_600;
11const LINE_BUFFER: usize = 1_024;
13const MAX_DEPTH: usize = 3;
15const WHITESPACE: &[u8] = b" \t\n\r";
17
18#[derive(Debug, Clone, PartialEq, Eq, Hash)]
20pub(crate) enum Meaning {
21 Fixed { offset: i32, dst: bool },
23 Zone(Cow<'static, str>),
25}
26
27#[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#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
37pub enum TimeZoneAbbreviationsError {
38 #[error("invalid time zone file name \"{file}\"")]
40 InvalidFileName {
41 file: String,
43 },
44 #[error("time zone file recursion limit exceeded in file \"{file}\"")]
46 RecursionLimit {
47 file: String,
49 },
50 #[error("could not read time zone file \"{file}\"")]
52 FileNotFound {
53 file: String,
55 },
56 #[error("line is too long in time zone file \"{file}\", line {line}")]
58 LineTooLong {
59 file: String,
61 line: usize,
63 },
64 #[error("@INCLUDE without file name in time zone file \"{file}\", line {line}")]
66 IncludeWithoutFileName {
67 file: String,
69 line: usize,
71 },
72 #[error("missing time zone offset in time zone file \"{file}\", line {line}")]
74 MissingOffset {
75 file: String,
77 line: usize,
79 },
80 #[error("invalid number for time zone offset in time zone file \"{file}\", line {line}")]
82 InvalidOffset {
83 file: String,
85 line: usize,
87 },
88 #[error("invalid syntax in time zone file \"{file}\", line {line}")]
90 InvalidSyntax {
91 file: String,
93 line: usize,
95 },
96 #[error(
98 "time zone abbreviation \"{abbreviation}\" is too long (maximum 10 characters) in time zone file \"{file}\", line {line}"
99 )]
100 AbbreviationTooLong {
101 abbreviation: String,
103 file: String,
105 line: usize,
107 },
108 #[error("time zone offset {offset} is out of range in time zone file \"{file}\", line {line}")]
110 OffsetOutOfRange {
111 offset: i32,
113 file: String,
115 line: usize,
117 },
118 #[error("time zone abbreviation \"{abbreviation}\" is multiply defined")]
121 MultiplyDefined {
122 abbreviation: String,
124 file: String,
126 line: usize,
128 },
129}
130
131struct 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
143const fn is_space(byte: u8) -> bool {
145 matches!(byte, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
146}
147
148fn 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
159fn 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 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 Some(long as i32)
178}
179
180fn 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
234fn 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
260pub(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
322pub(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}