garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /tz/src/lib.rs

raw

//! Time zones, as IANA's database has them (`zoneinfo/`): a zone's TZif
//! file (RFC 8536) read, and from it the offset from UTC at any moment,
//! summer time included. A file lists the zone's past changes; after the
//! last one its footer's rule (POSIX's `TZ`, `CET-1CEST,M3.5.0,M10.5.0/3`)
//! gives every later year, so a file made today stays right until a
//! country changes its rules, and then a system update brings the new one.
//!
//! And the civil calendar, which every program that shows a date needs:
//! days since 1970 to a date and back, and the weekday.

#![no_std]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;

/// What a zone says of a moment: how far its clocks are ahead of UTC,
/// whether that is summer time, and its abbreviation ("CEST").
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Local {
    /// Seconds ahead of UTC (negative west of Greenwich).
    pub offset: i32,
    pub dst: bool,
    pub name: String,
}

impl Local {
    fn utc() -> Local {
        Local {
            offset: 0,
            dst: false,
            name: "UTC".into(),
        }
    }
}

/// A zone: its transitions, the kinds of local time they switch to, and
/// the rule after the last.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Zone {
    /// When each transition happens, seconds since 1970 (UTC), ascending.
    transitions: Vec<i64>,
    /// The kind each transition switches to, an index into `kinds`.
    to: Vec<u8>,
    kinds: Vec<Local>,
    rule: Option<Rule>,
}

impl Zone {
    /// UTC: no offset, ever.
    pub fn utc() -> Zone {
        Zone {
            transitions: Vec::new(),
            to: Vec::new(),
            kinds: alloc::vec![Local::utc()],
            rule: None,
        }
    }

    /// A TZif file, version 1 to 4. Only the 64-bit part of a file of
    /// version 2 or later is read (the 32-bit one before it is skipped), as
    /// RFC 8536 asks of a reader that can.
    pub fn parse(bytes: &[u8]) -> Option<Zone> {
        let first = Header::read(bytes)?;
        if first.version == 0 {
            return first.zone(bytes, 44, 4, None);
        }
        let second = 44 + first.data_len(4);
        let header = Header::read(bytes.get(second..)?)?;
        let data = second + 44;
        let footer_at = data + header.data_len(8);
        // "\n<TZ>\n" after the data.
        let footer = bytes.get(footer_at..).and_then(|f| {
            let f = f.strip_prefix(b"\n")?;
            let end = f.iter().position(|&b| b == b'\n')?;
            core::str::from_utf8(&f[..end]).ok()
        });
        header.zone(bytes, data, 8, footer)
    }

    /// The zone's local time at `utc` (seconds since 1970).
    pub fn at(&self, utc: i64) -> Local {
        if self.transitions.last().is_some_and(|&last| utc >= last)
            && let Some(rule) = &self.rule
        {
            return rule.at(utc);
        }
        // Before the first transition: the first kind (RFC 8536, 3.2).
        let kind = match self.transitions.partition_point(|&t| t <= utc) {
            0 if self.transitions.is_empty() => match &self.rule {
                Some(rule) => return rule.at(utc),
                None => 0,
            },
            0 => 0,
            n => usize::from(self.to[n - 1]),
        };
        self.kinds.get(kind).cloned().unwrap_or_else(Local::utc)
    }

    /// The local time at `utc` as a date and a time of day, and what the
    /// zone says of it.
    pub fn civil(&self, utc: i64) -> (DateTime, Local) {
        let local = self.at(utc);
        (DateTime::from_seconds(utc + i64::from(local.offset)), local)
    }
}

/// A TZif header's counts.
struct Header {
    version: u8,
    isutcnt: usize,
    isstdcnt: usize,
    leapcnt: usize,
    timecnt: usize,
    typecnt: usize,
    charcnt: usize,
}

impl Header {
    fn read(bytes: &[u8]) -> Option<Header> {
        if bytes.get(..4)? != b"TZif" {
            return None;
        }
        let version = match *bytes.get(4)? {
            0 => 0,
            v @ b'2'..=b'4' => v - b'0',
            _ => return None,
        };
        let count = |i: usize| -> Option<usize> {
            let b = bytes.get(20 + 4 * i..24 + 4 * i)?;
            Some(u32::from_be_bytes(b.try_into().ok()?) as usize)
        };
        Some(Header {
            version,
            isutcnt: count(0)?,
            isstdcnt: count(1)?,
            leapcnt: count(2)?,
            timecnt: count(3)?,
            typecnt: count(4)?,
            charcnt: count(5)?,
        })
    }

    /// The data block's length, with times of `size` bytes.
    fn data_len(&self, size: usize) -> usize {
        self.timecnt * size
            + self.timecnt
            + self.typecnt * 6
            + self.charcnt
            + self.leapcnt * (size + 4)
            + self.isstdcnt
            + self.isutcnt
    }

    fn zone(&self, bytes: &[u8], at: usize, size: usize, footer: Option<&str>) -> Option<Zone> {
        let data = bytes.get(at..at + self.data_len(size))?;
        let (times, rest) = data.split_at(self.timecnt * size);
        let (to, rest) = rest.split_at(self.timecnt);
        let (types, rest) = rest.split_at(self.typecnt * 6);
        let chars = &rest[..self.charcnt];
        let transitions = times
            .chunks(size)
            .map(|t| match size {
                4 => i64::from(i32::from_be_bytes(t.try_into().unwrap())),
                _ => i64::from_be_bytes(t.try_into().unwrap()),
            })
            .collect();
        let kinds = types
            .chunks(6)
            .map(|t| {
                let name = chars.get(usize::from(t[5])..).unwrap_or(&[]);
                let end = name.iter().position(|&b| b == 0).unwrap_or(name.len());
                Local {
                    offset: i32::from_be_bytes(t[..4].try_into().unwrap()),
                    dst: t[4] != 0,
                    name: String::from_utf8_lossy(&name[..end]).into(),
                }
            })
            .collect::<Vec<_>>();
        if kinds.is_empty() || to.iter().any(|&k| usize::from(k) >= kinds.len()) {
            return None;
        }
        Some(Zone {
            transitions,
            to: to.into(),
            kinds,
            rule: footer.filter(|f| !f.is_empty()).and_then(Rule::parse),
        })
    }
}

/// A POSIX `TZ` rule: standard time, and summer time between two days of
/// every year if the zone keeps one.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rule {
    standard: Local,
    summer: Option<(Local, Day, i32, Day, i32)>,
}

/// A day of the year a change happens on, as POSIX writes them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Day {
    /// `Jn`: 1–365, never counting 29 February.
    Julian(u16),
    /// `n`: 0–365, counting it.
    Zero(u16),
    /// `Mm.w.d`: weekday `d` (0 Sunday) of week `w` (5 the last) of month `m`.
    Month(u8, u8, u8),
}

impl Rule {
    /// `CET-1CEST,M3.5.0,M10.5.0/3`, `<+03>-3`, `EST5EDT,M3.2.0,M11.1.0`.
    pub fn parse(text: &str) -> Option<Rule> {
        let mut s = text.as_bytes();
        let standard_name = name(&mut s)?;
        let standard_offset = -offset(&mut s)?;
        let standard = Local {
            offset: standard_offset,
            dst: false,
            name: standard_name,
        };
        if s.is_empty() {
            return Some(Rule {
                standard,
                summer: None,
            });
        }
        let summer_name = name(&mut s)?;
        let summer_offset = match s.first() {
            Some(b',') | None => standard_offset + 3600,
            _ => -offset(&mut s)?,
        };
        let summer = Local {
            offset: summer_offset,
            dst: true,
            name: summer_name,
        };
        // No rule given: the United States' of 2007, as POSIX lets a
        // reader choose and as glibc does.
        let (start, start_time, end, end_time) = if s.is_empty() {
            (Day::Month(3, 2, 0), 7200, Day::Month(11, 1, 0), 7200)
        } else {
            let change = |s: &mut &[u8]| -> Option<(Day, i32)> {
                *s = s.strip_prefix(b",")?;
                let d = day(s)?;
                let time = match s.strip_prefix(b"/") {
                    Some(rest) => {
                        *s = rest;
                        offset(s)?
                    }
                    None => 7200,
                };
                Some((d, time))
            };
            let (start, start_time) = change(&mut s)?;
            let (end, end_time) = change(&mut s)?;
            (start, start_time, end, end_time)
        };
        if !s.is_empty() {
            return None;
        }
        Some(Rule {
            standard,
            summer: Some((summer, start, start_time, end, end_time)),
        })
    }

    /// Its local time at `utc`.
    pub fn at(&self, utc: i64) -> Local {
        let Some((summer, start, start_time, end, end_time)) = &self.summer else {
            return self.standard.clone();
        };
        let (std_off, dst_off) = (i64::from(self.standard.offset), i64::from(summer.offset));
        let year = DateTime::from_seconds(utc + std_off).year;
        // The change to summer time is at a standard local time, back at a
        // summer one.
        let on = day_seconds(year, *start) + i64::from(*start_time) - std_off;
        let off = day_seconds(year, *end) + i64::from(*end_time) - dst_off;
        let summer_now = if on < off {
            (on..off).contains(&utc)
        } else {
            // The southern half: summer across New Year.
            !(off..on).contains(&utc)
        };
        if summer_now {
            summer.clone()
        } else {
            self.standard.clone()
        }
    }
}

/// A zone's abbreviation: letters, or anything between `<` and `>`.
fn name(s: &mut &[u8]) -> Option<String> {
    let (text, rest) = if let Some(quoted) = s.strip_prefix(b"<") {
        let end = quoted.iter().position(|&b| b == b'>')?;
        (&quoted[..end], &quoted[end + 1..])
    } else {
        let end = s.iter().position(|b| !b.is_ascii_alphabetic()).unwrap_or(s.len());
        (&s[..end], &s[end..])
    };
    if text.len() < 3 {
        return None;
    }
    *s = rest;
    Some(String::from_utf8_lossy(text).into())
}

/// `[+-]hh[:mm[:ss]]` in seconds; hours up to 167 (a time of day in
/// TZif's version 3 may reach past 24, or before 0).
fn offset(s: &mut &[u8]) -> Option<i32> {
    let sign = match s.first() {
        Some(b'-') => {
            *s = &s[1..];
            -1
        }
        Some(b'+') => {
            *s = &s[1..];
            1
        }
        _ => 1,
    };
    let mut total = 0;
    for (i, scale) in [3600, 60, 1].into_iter().enumerate() {
        if i > 0 {
            match s.strip_prefix(b":") {
                Some(rest) => *s = rest,
                None => break,
            }
        }
        let n = number(s)?;
        if n > if i == 0 { 167 } else { 59 } {
            return None;
        }
        total += n * scale;
    }
    Some(sign * total)
}

fn number(s: &mut &[u8]) -> Option<i32> {
    let end = s.iter().position(|b| !b.is_ascii_digit()).unwrap_or(s.len());
    if end == 0 || end > 3 {
        return None;
    }
    let n = core::str::from_utf8(&s[..end]).ok()?.parse().ok()?;
    *s = &s[end..];
    Some(n)
}

fn day(s: &mut &[u8]) -> Option<Day> {
    if let Some(rest) = s.strip_prefix(b"M") {
        *s = rest;
        let m = number(s)?;
        *s = s.strip_prefix(b".")?;
        let w = number(s)?;
        *s = s.strip_prefix(b".")?;
        let d = number(s)?;
        ((1..=12).contains(&m) && (1..=5).contains(&w) && (0..=6).contains(&d))
            .then_some(Day::Month(m as u8, w as u8, d as u8))
    } else if let Some(rest) = s.strip_prefix(b"J") {
        *s = rest;
        let n = number(s)?;
        (1..=365).contains(&n).then_some(Day::Julian(n as u16))
    } else {
        let n = number(s)?;
        (0..=365).contains(&n).then_some(Day::Zero(n as u16))
    }
}

/// Midnight of `day` in `year`, seconds since 1970 as if local were UTC.
fn day_seconds(year: i64, day: Day) -> i64 {
    let jan1 = days_from_civil(year, 1, 1);
    let days = match day {
        Day::Julian(n) => {
            let n = i64::from(n) - 1;
            // Past February in a leap year: one more.
            jan1 + n + i64::from(leap(year) && n >= 59)
        }
        Day::Zero(n) => jan1 + i64::from(n),
        Day::Month(m, w, d) => {
            let first = days_from_civil(year, u32::from(m), 1);
            // The first weekday `d` on or after the 1st, then `w - 1` weeks on.
            let mut day =
                first + (i64::from(d) - weekday(first) as i64).rem_euclid(7) + 7 * (i64::from(w) - 1);
            let len = month_len(year, u32::from(m));
            while day >= first + i64::from(len) {
                day -= 7;
            }
            day
        }
    };
    days * 86_400
}

fn leap(year: i64) -> bool {
    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}

/// The number of days in `month` (1–12) of `year`.
pub fn month_len(year: i64, month: u32) -> u32 {
    match month {
        2 if leap(year) => 29,
        2 => 28,
        4 | 6 | 9 | 11 => 30,
        _ => 31,
    }
}

/// Days since 1970 of a date (Howard Hinnant's days-from-civil).
pub fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
    let y = if month <= 2 { year - 1 } else { year };
    let era = y.div_euclid(400);
    let yoe = y.rem_euclid(400);
    let m = i64::from(month);
    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + i64::from(day) - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

/// Year, month (1–12) and day of days since 1970 (civil-from-days).
pub fn civil_from_days(days: i64) -> (i64, u32, u32) {
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
    (yoe + era * 400 + i64::from(month <= 2), month, day)
}

/// The weekday of days since 1970: 0 Sunday to 6 Saturday (1 January 1970
/// was a Thursday).
pub fn weekday(days: i64) -> u32 {
    (days + 4).rem_euclid(7) as u32
}

/// A date and a time of day.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DateTime {
    pub year: i64,
    /// 1–12.
    pub month: u32,
    /// 1–31.
    pub day: u32,
    pub hour: u32,
    pub minute: u32,
    pub second: u32,
    /// 0 Sunday to 6 Saturday.
    pub weekday: u32,
}

impl DateTime {
    /// Seconds since 1970 as a date and a time, with no zone: give it a
    /// local time ([`Zone::civil`]) to have the local date.
    pub fn from_seconds(seconds: i64) -> DateTime {
        let days = seconds.div_euclid(86_400);
        let rest = seconds.rem_euclid(86_400) as u32;
        let (year, month, day) = civil_from_days(days);
        DateTime {
            year,
            month,
            day,
            hour: rest / 3600,
            minute: rest / 60 % 60,
            second: rest % 60,
            weekday: weekday(days),
        }
    }

    /// Back to seconds since 1970.
    pub fn seconds(&self) -> i64 {
        days_from_civil(self.year, self.month, self.day) * 86_400
            + i64::from(self.hour * 3600 + self.minute * 60 + self.second)
    }
}

/// The names of the zones a `zones` list holds (`zoneinfo/zones`: a name
/// and a country a line, tab between), with their countries.
pub fn zones(list: &str) -> impl Iterator<Item = (&str, &str)> {
    list.lines().filter_map(|l| {
        let (name, country) = l.split_once('\t').unwrap_or((l, ""));
        (!name.is_empty()).then_some((name, country))
    })
}

/// A zone's name as a person reads it: its place, `Europe/Amsterdam` →
/// "Amsterdam", `America/Argentina/Buenos_Aires` → "Buenos Aires".
pub fn place(name: &str) -> String {
    name.rsplit('/').next().unwrap_or(name).replace('_', " ")
}

/// A zone name a file may be read by: letters, digits, `_+-` and single
/// `/` between parts, none of them `.` or `..`.
pub fn valid_name(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 64
        && name.split('/').all(|part| {
            !part.is_empty()
                && !part.starts_with('.')
                && part
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || b"_+-".contains(&b))
        })
}

/// "+01:00", "-03:30", "+00:00": an offset as it is written beside a time.
pub fn offset_text(offset: i32) -> String {
    let sign = if offset < 0 { '-' } else { '+' };
    let a = offset.unsigned_abs();
    alloc::format!("{sign}{:02}:{:02}", a / 3600, a / 60 % 60)
}

#[cfg(test)]
mod tests;