Skip to main content

nodejs/
tzif.rs

1//! Named IANA time zones, read from RFC 8536 TZif data — the copy embedded by
2//! `jiff_tzdb`, falling back to the system's `/usr/share/zoneinfo` — what
3//! `Intl` and `toLocaleString` need for a `timeZone: "America/New_York"` option.
4//!
5//! A TZif file lists every transition up to some year and then, in its footer,
6//! the POSIX `TZ` rule that continues past the last one (`EST5EDT,M3.2.0,
7//! M11.1.0`). macOS ships "slim" files whose transitions stop early and lean on
8//! that rule, so both halves are read.
9
10use std::collections::HashMap;
11use std::rc::Rc;
12
13/// One local-time type: offset east of UTC in seconds, its abbreviation, and
14/// whether it is daylight time (`tt_isdst`).
15#[derive(Clone, Debug, PartialEq)]
16pub struct LocalType {
17    pub offset: i64,
18    pub abbrev: String,
19    pub dst: bool,
20}
21
22/// A parsed zone.
23#[derive(Debug)]
24pub struct Tz {
25    /// The canonical name as found on disk.
26    pub name: String,
27    transitions: Vec<i64>,
28    type_of: Vec<usize>,
29    types: Vec<LocalType>,
30    rule: Option<PosixRule>,
31}
32
33/// The POSIX `TZ` rule of the footer: standard time, and optionally daylight
34/// time between two yearly transition dates.
35#[derive(Debug)]
36struct PosixRule {
37    std: LocalType,
38    dst: Option<(LocalType, RuleDate, RuleDate)>,
39}
40
41/// `Mm.w.d/time` — day `d` (0 = Sunday) of week `w` (5 = last) of month `m`,
42/// at `time` seconds of LOCAL time. `Jn` and plain-`n` dates are read as
43/// day-of-year forms.
44#[derive(Debug, Clone, Copy)]
45enum RuleDate {
46    MonthWeekDay {
47        month: i64,
48        week: i64,
49        day: i64,
50        time: i64,
51    },
52    /// `Jn`: day 1..=365, February 29 never counted.
53    Julian1 { day: i64, time: i64 },
54    /// `n`: day 0..=365, February 29 counted.
55    Julian0 { day: i64, time: i64 },
56}
57
58impl Tz {
59    /// The local type in force at `t` (seconds since the epoch, UTC).
60    pub fn at(&self, t: i64) -> LocalType {
61        match self.transitions.binary_search(&t) {
62            Ok(i) => self.types[self.type_of[i]].clone(),
63            // Past the last transition (or with none at all), the footer's
64            // rule continues the zone.
65            Err(i) if i == self.transitions.len() && self.rule.is_some() => {
66                self.rule.as_ref().map(|r| r.at(t)).expect("checked")
67            }
68            // Before the first transition: type 0 (RFC 8536 3.2).
69            Err(0) => self.types[0].clone(),
70            Err(i) => self.types[self.type_of[i - 1]].clone(),
71        }
72    }
73}
74
75thread_local! {
76    static CACHE: std::cell::RefCell<HashMap<String, Option<Rc<Tz>>>> =
77        std::cell::RefCell::new(HashMap::new());
78}
79
80/// The zone named `name`, from the embedded database (matched without regard
81/// to ASCII case) or else the system copy; `..` and absolute paths are refused.
82pub fn load(name: &str) -> Option<Rc<Tz>> {
83    if name.is_empty()
84        || name.starts_with('/')
85        || name
86            .split('/')
87            .any(|p| p.is_empty() || p == "." || p == "..")
88        || !name
89            .chars()
90            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '_' | '-' | '+'))
91    {
92        return None;
93    }
94    if let Some(hit) = CACHE.with(|c| c.borrow().get(name).cloned()) {
95        return hit;
96    }
97    // The embedded database first, like Node's bundled ICU data: system
98    // copies differ by distro build (backzone or not), which changes
99    // pre-1970 offsets. The system dirs cover names the bundle lacks.
100    let tz = jiff_tzdb::get(name)
101        .and_then(|(_, bytes)| parse(bytes, name))
102        .or_else(|| {
103            [
104                "/usr/share/zoneinfo",
105                "/usr/lib/zoneinfo",
106                "/usr/share/lib/zoneinfo",
107            ]
108            .iter()
109            .find_map(|dir| std::fs::read(format!("{dir}/{name}")).ok())
110            .and_then(|bytes| parse(&bytes, name))
111        })
112        .map(Rc::new);
113    CACHE.with(|c| c.borrow_mut().insert(name.to_string(), tz.clone()));
114    tz
115}
116
117fn be32(b: &[u8], at: usize) -> Option<i64> {
118    Some(i32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?) as i64)
119}
120
121fn be64(b: &[u8], at: usize) -> Option<i64> {
122    Some(i64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
123}
124
125/// The six counts of a TZif header: isutcnt, isstdcnt, leapcnt, timecnt,
126/// typecnt, charcnt.
127fn counts(b: &[u8], at: usize) -> Option<[usize; 6]> {
128    let mut c = [0usize; 6];
129    for (i, slot) in c.iter_mut().enumerate() {
130        *slot = be32(b, at + 20 + i * 4)? as usize;
131    }
132    Some(c)
133}
134
135fn parse(b: &[u8], name: &str) -> Option<Tz> {
136    if b.get(..4)? != b"TZif" {
137        return None;
138    }
139    let version = *b.get(4)?;
140    let c1 = counts(b, 0)?;
141    let v1_len = c1[3] * 5 + c1[4] * 6 + c1[5] + c1[2] * 8 + c1[1] + c1[0];
142    // Version 2+ repeats the data with 64-bit times after the v1 block.
143    let (base, c, time_size) = if version >= b'2' {
144        let at = 44 + v1_len;
145        (at, counts(b, at)?, 8)
146    } else {
147        (0, c1, 4)
148    };
149    let [isutcnt, isstdcnt, leapcnt, timecnt, typecnt, charcnt] = c;
150    let mut p = base + 44;
151    let mut transitions = Vec::with_capacity(timecnt);
152    for i in 0..timecnt {
153        transitions.push(if time_size == 8 {
154            be64(b, p + i * 8)?
155        } else {
156            be32(b, p + i * 4)?
157        });
158    }
159    p += timecnt * time_size;
160    let type_of: Vec<usize> = b.get(p..p + timecnt)?.iter().map(|&x| x as usize).collect();
161    p += timecnt;
162    let mut raw_types = Vec::with_capacity(typecnt);
163    for i in 0..typecnt {
164        let at = p + i * 6;
165        raw_types.push((be32(b, at)?, *b.get(at + 4)? != 0, *b.get(at + 5)? as usize));
166    }
167    p += typecnt * 6;
168    let chars = b.get(p..p + charcnt)?;
169    let types: Vec<LocalType> = raw_types
170        .into_iter()
171        .map(|(offset, dst, idx)| {
172            let end = chars[idx.min(chars.len())..]
173                .iter()
174                .position(|&ch| ch == 0)
175                .map_or(chars.len(), |e| idx + e);
176            LocalType {
177                offset,
178                abbrev: String::from_utf8_lossy(&chars[idx.min(end)..end]).into_owned(),
179                dst,
180            }
181        })
182        .collect();
183    if types.is_empty() || type_of.iter().any(|&t| t >= types.len()) {
184        return None;
185    }
186    p += charcnt + leapcnt * (time_size + 4) + isstdcnt + isutcnt;
187    let rule = if version >= b'2' {
188        b.get(p..).and_then(|rest| {
189            let text = std::str::from_utf8(rest).ok()?;
190            let line = text.strip_prefix('\n')?.split('\n').next()?;
191            PosixRule::parse(line)
192        })
193    } else {
194        None
195    };
196    Some(Tz {
197        name: name.to_string(),
198        transitions,
199        type_of,
200        types,
201        rule,
202    })
203}
204
205impl PosixRule {
206    fn parse(s: &str) -> Option<PosixRule> {
207        let mut cur = s;
208        let std_name = take_name(&mut cur)?;
209        // POSIX offsets are WEST of Greenwich.
210        let std_off = -take_offset(&mut cur)?;
211        let std = LocalType {
212            offset: std_off,
213            abbrev: std_name,
214            dst: false,
215        };
216        if cur.is_empty() {
217            return Some(PosixRule { std, dst: None });
218        }
219        let dst_name = take_name(&mut cur)?;
220        let dst_off = if cur.starts_with(',') {
221            std_off + 3600
222        } else {
223            -take_offset(&mut cur)?
224        };
225        let rest = cur.strip_prefix(',')?;
226        let (start, end) = rest.split_once(',')?;
227        Some(PosixRule {
228            std,
229            dst: Some((
230                LocalType {
231                    offset: dst_off,
232                    abbrev: dst_name,
233                    dst: true,
234                },
235                RuleDate::parse(start)?,
236                RuleDate::parse(end)?,
237            )),
238        })
239    }
240
241    fn at(&self, t: i64) -> LocalType {
242        let Some((dst, start, end)) = &self.dst else {
243            return self.std.clone();
244        };
245        // The transitions of the year `t` falls in (in standard time), as UTC
246        // instants: the start is read in standard time, the end in daylight.
247        let year = crate::stdlib::date::civil_from_days((t + self.std.offset).div_euclid(86_400)).0;
248        let begin = start.local_secs(year) - self.std.offset;
249        let finish = end.local_secs(year) - dst.offset;
250        let in_dst = if begin < finish {
251            t >= begin && t < finish
252        } else {
253            // Southern hemisphere: daylight time spans the new year.
254            !(t >= finish && t < begin)
255        };
256        if in_dst {
257            dst.clone()
258        } else {
259            self.std.clone()
260        }
261    }
262}
263
264/// A zone abbreviation: letters, or anything between `<` and `>`.
265fn take_name(cur: &mut &str) -> Option<String> {
266    if let Some(rest) = cur.strip_prefix('<') {
267        let end = rest.find('>')?;
268        let name = rest[..end].to_string();
269        *cur = &rest[end + 1..];
270        return Some(name);
271    }
272    let end = cur
273        .find(|c: char| !c.is_ascii_alphabetic())
274        .unwrap_or(cur.len());
275    if end < 3 {
276        return None;
277    }
278    let name = cur[..end].to_string();
279    *cur = &cur[end..];
280    Some(name)
281}
282
283/// `[+-]hh[:mm[:ss]]` in seconds.
284fn take_offset(cur: &mut &str) -> Option<i64> {
285    let (sign, rest) = match cur.as_bytes().first()? {
286        b'-' => (-1, &cur[1..]),
287        b'+' => (1, &cur[1..]),
288        _ => (1, *cur),
289    };
290    let end = rest
291        .find(|c: char| !(c.is_ascii_digit() || c == ':'))
292        .unwrap_or(rest.len());
293    let secs = hms(&rest[..end])?;
294    *cur = &rest[end..];
295    Some(sign * secs)
296}
297
298fn hms(s: &str) -> Option<i64> {
299    let mut total = 0;
300    let mut scale = 3600;
301    for part in s.split(':') {
302        if part.is_empty() || scale == 0 {
303            return None;
304        }
305        total += part.parse::<i64>().ok()? * scale;
306        scale /= 60;
307    }
308    Some(total)
309}
310
311impl RuleDate {
312    fn parse(s: &str) -> Option<RuleDate> {
313        let (date, time) = match s.split_once('/') {
314            Some((d, t)) => {
315                let (neg, t) = match t.strip_prefix('-') {
316                    Some(t) => (true, t),
317                    None => (false, t.strip_prefix('+').unwrap_or(t)),
318                };
319                let secs = hms(t)?;
320                (d, if neg { -secs } else { secs })
321            }
322            None => (s, 7200),
323        };
324        if let Some(m) = date.strip_prefix('M') {
325            let mut it = m.split('.').map(|x| x.parse::<i64>().ok());
326            let (month, week, day) = (it.next()??, it.next()??, it.next()??);
327            return Some(RuleDate::MonthWeekDay {
328                month,
329                week,
330                day,
331                time,
332            });
333        }
334        if let Some(n) = date.strip_prefix('J') {
335            return Some(RuleDate::Julian1 {
336                day: n.parse().ok()?,
337                time,
338            });
339        }
340        Some(RuleDate::Julian0 {
341            day: date.parse().ok()?,
342            time,
343        })
344    }
345
346    /// Seconds since the epoch, in LOCAL time, of this date in `year`.
347    fn local_secs(&self, year: i64) -> i64 {
348        use crate::stdlib::date::days_from_civil;
349        let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
350        let (days, time) = match *self {
351            RuleDate::MonthWeekDay {
352                month,
353                week,
354                day,
355                time,
356            } => {
357                let first = days_from_civil(year, month - 1, 1);
358                // 1970-01-01 was a Thursday (4).
359                let first_wd = (first + 4).rem_euclid(7);
360                let mut d = first + (day - first_wd).rem_euclid(7) + (week - 1) * 7;
361                let next_month = if month == 12 {
362                    days_from_civil(year + 1, 0, 1)
363                } else {
364                    days_from_civil(year, month, 1)
365                };
366                while d >= next_month {
367                    d -= 7;
368                }
369                (d, time)
370            }
371            RuleDate::Julian1 { day, time } => {
372                let skip = if leap && day >= 60 { 1 } else { 0 };
373                (days_from_civil(year, 0, 1) + day - 1 + skip, time)
374            }
375            RuleDate::Julian0 { day, time } => (days_from_civil(year, 0, 1) + day, time),
376        };
377        days * 86_400 + time
378    }
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384
385    #[test]
386    fn posix_rule_new_york() {
387        let r = PosixRule::parse("EST5EDT,M3.2.0,M11.1.0").unwrap();
388        // 2030-07-01T12:00Z is daylight time; 2030-01-01T12:00Z is not.
389        assert_eq!(r.at(1_909_137_600).abbrev, "EDT");
390        assert_eq!(r.at(1_893_499_200).abbrev, "EST");
391        let r = PosixRule::parse("<+0530>-5:30").unwrap();
392        assert_eq!(r.at(0).offset, 19_800);
393        assert_eq!(r.at(0).abbrev, "+0530");
394    }
395}