use alloc::{borrow::Cow, string::String, vec::Vec};
const TOKEN_MAX_LEN: usize = 10;
const MAX_OFFSET: i64 = 14 * 3_600;
const LINE_BUFFER: usize = 1_024;
const MAX_DEPTH: usize = 3;
const WHITESPACE: &[u8] = b" \t\n\r";
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum Meaning {
Fixed { offset: i32, dst: bool },
Zone(Cow<'static, str>),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct Abbreviation {
pub(crate) token: Cow<'static, str>,
pub(crate) meaning: Meaning,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
pub enum TimeZoneAbbreviationsError {
#[error("invalid time zone file name \"{file}\"")]
InvalidFileName {
file: String,
},
#[error("time zone file recursion limit exceeded in file \"{file}\"")]
RecursionLimit {
file: String,
},
#[error("could not read time zone file \"{file}\"")]
FileNotFound {
file: String,
},
#[error("line is too long in time zone file \"{file}\", line {line}")]
LineTooLong {
file: String,
line: usize,
},
#[error("@INCLUDE without file name in time zone file \"{file}\", line {line}")]
IncludeWithoutFileName {
file: String,
line: usize,
},
#[error("missing time zone offset in time zone file \"{file}\", line {line}")]
MissingOffset {
file: String,
line: usize,
},
#[error("invalid number for time zone offset in time zone file \"{file}\", line {line}")]
InvalidOffset {
file: String,
line: usize,
},
#[error("invalid syntax in time zone file \"{file}\", line {line}")]
InvalidSyntax {
file: String,
line: usize,
},
#[error(
"time zone abbreviation \"{abbreviation}\" is too long (maximum 10 characters) in time zone file \"{file}\", line {line}"
)]
AbbreviationTooLong {
abbreviation: String,
file: String,
line: usize,
},
#[error("time zone offset {offset} is out of range in time zone file \"{file}\", line {line}")]
OffsetOutOfRange {
offset: i32,
file: String,
line: usize,
},
#[error("time zone abbreviation \"{abbreviation}\" is multiply defined")]
MultiplyDefined {
abbreviation: String,
file: String,
line: usize,
},
}
struct Place<'a> {
file: &'a str,
line: usize,
}
impl Place<'_> {
fn file(&self) -> String {
String::from(self.file)
}
}
const fn is_space(byte: u8) -> bool {
matches!(byte, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
}
fn next_token(bytes: &[u8]) -> Option<(&[u8], &[u8])> {
let start = bytes.iter().position(|b| !WHITESPACE.contains(b))?;
let rest = &bytes[start..];
let end = rest
.iter()
.position(|b| WHITESPACE.contains(b))
.unwrap_or(rest.len());
Some((&rest[..end], &rest[end..]))
}
fn strtol_int(token: &[u8]) -> Option<i32> {
let (negative, digits) = match token.split_first() {
Some((b'-', rest)) => (true, rest),
Some((b'+', rest)) => (false, rest),
_ => (false, token),
};
if digits.is_empty() || !digits.iter().all(u8::is_ascii_digit) {
return None;
}
let magnitude = digits.iter().fold(0i128, |value, &digit| {
(value * 10 + i128::from(digit - b'0')).min(1 << 64)
});
let signed = if negative { -magnitude } else { magnitude };
let long = signed.clamp(i128::from(i64::MIN), i128::from(i64::MAX));
Some(long as i32)
}
fn split_line(line: &[u8], place: &Place<'_>) -> Result<Abbreviation, TimeZoneAbbreviationsError> {
let (abbreviation, rest) = next_token(line).expect("a line past its blanks has a token");
let Some((value, rest)) = next_token(rest) else {
return Err(TimeZoneAbbreviationsError::MissingOffset {
file: place.file(),
line: place.line,
});
};
let (meaning, rest) = if matches!(value.first(), Some(b'0'..=b'9' | b'+' | b'-')) {
let offset =
strtol_int(value).ok_or_else(|| TimeZoneAbbreviationsError::InvalidOffset {
file: place.file(),
line: place.line,
})?;
match next_token(rest) {
Some((flag, after)) if flag.eq_ignore_ascii_case(b"D") => {
(Meaning::Fixed { offset, dst: true }, after)
}
_ => (Meaning::Fixed { offset, dst: false }, rest),
}
} else {
let zone = String::from_utf8_lossy(value).into_owned();
(Meaning::Zone(Cow::Owned(zone)), rest)
};
if next_token(rest).is_some_and(|(remain, _)| remain[0] != b'#') {
return Err(TimeZoneAbbreviationsError::InvalidSyntax {
file: place.file(),
line: place.line,
});
}
let written = String::from_utf8_lossy(abbreviation).into_owned();
if abbreviation.len() > TOKEN_MAX_LEN {
return Err(TimeZoneAbbreviationsError::AbbreviationTooLong {
abbreviation: written,
file: place.file(),
line: place.line,
});
}
if let Meaning::Fixed { offset, .. } = meaning
&& !(-MAX_OFFSET..=MAX_OFFSET).contains(&i64::from(offset))
{
return Err(TimeZoneAbbreviationsError::OffsetOutOfRange {
offset,
file: place.file(),
line: place.line,
});
}
Ok(Abbreviation {
token: Cow::Owned(written.to_ascii_lowercase()),
meaning,
})
}
fn add(
entries: &mut Vec<Abbreviation>,
entry: Abbreviation,
replace: bool,
place: &Place<'_>,
) -> Result<(), TimeZoneAbbreviationsError> {
match entries.binary_search_by(|probe| probe.token.as_bytes().cmp(entry.token.as_bytes())) {
Ok(at) if entries[at].meaning == entry.meaning => Ok(()),
Ok(at) if replace => {
entries[at].meaning = entry.meaning;
Ok(())
}
Ok(_) => Err(TimeZoneAbbreviationsError::MultiplyDefined {
abbreviation: String::from(entry.token),
file: place.file(),
line: place.line,
}),
Err(at) => {
entries.insert(at, entry);
Ok(())
}
}
}
pub(crate) fn parse_file<'f>(
name: &str,
depth: usize,
files: &mut dyn FnMut(&str) -> Option<&'f str>,
entries: &mut Vec<Abbreviation>,
) -> Result<(), TimeZoneAbbreviationsError> {
if !name.bytes().all(|b| b.is_ascii_alphabetic()) {
return Err(TimeZoneAbbreviationsError::InvalidFileName {
file: String::from(name),
});
}
if depth > MAX_DEPTH {
return Err(TimeZoneAbbreviationsError::RecursionLimit {
file: String::from(name),
});
}
let text = files(name).ok_or_else(|| TimeZoneAbbreviationsError::FileNotFound {
file: String::from(name),
})?;
let mut replace = false;
for (index, raw) in text.as_bytes().split_inclusive(|&b| b == b'\n').enumerate() {
let place = Place {
file: name,
line: index + 1,
};
if raw.len() >= LINE_BUFFER - 1 {
return Err(TimeZoneAbbreviationsError::LineTooLong {
file: place.file(),
line: place.line,
});
}
let start = raw.iter().take_while(|&&b| is_space(b)).count();
let line = &raw[start..];
if line.is_empty() || line[0] == b'#' {
continue;
}
let directive = |word: &[u8]| {
line.get(..word.len())
.is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
};
if directive(b"@INCLUDE") {
let Some((include, _)) = next_token(&line[8..]) else {
return Err(TimeZoneAbbreviationsError::IncludeWithoutFileName {
file: place.file(),
line: place.line,
});
};
let include = String::from_utf8_lossy(include);
parse_file(&include, depth + 1, files, entries)?;
continue;
}
if directive(b"@OVERRIDE") {
replace = true;
continue;
}
let entry = split_line(line, &place)?;
add(entries, entry, replace, &place)?;
}
Ok(())
}
pub(crate) fn search<'e>(entries: &'e [Abbreviation], key: &[u8]) -> Option<&'e Abbreviation> {
let key = &key[..key.len().min(TOKEN_MAX_LEN)];
entries
.binary_search_by(|probe| probe.token.as_bytes().cmp(key))
.ok()
.map(|at| &entries[at])
}