Skip to main content

brrrty_js/
tz.rs

1//! Time zones as JavaScript sees them: broken-down time, the offset, the
2//! zone's id and its long name.
3//!
4//! `Tz::Utc` is exact. `Tz::Local` is the zone `TZ` (or `/etc/localtime`)
5//! names, with offsets from the tz database bundled into Brrrty: release
6//! [`TZDATA_VERSION`], the one Node 26.2.0 ships (`process.versions.tz`).
7//! The operating system's tz data is never read, so a machine with older
8//! or newer data gives the same pages. A `TZ` that names no zone in that
9//! data is refused ([`check_local`]).
10//!
11//! The zone's id (LiquidJS's `%Z` prints it) and its English long name
12//! (`Date.prototype.toString` prints it in parentheses) come from a table
13//! generated from Node (`src/zones.rs`, made by `tools/gen-zones.mjs`).
14//! See [`long_name`] for what is printed when the zone or the offset is
15//! not in it.
16
17use std::sync::OnceLock;
18
19use crate::zones::{PROFILES, ZONE_IDS};
20
21/// The time zone dates are printed and formatted in. JavaScript uses the
22/// process's local zone.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum Tz {
25    /// The machine's local zone, which honors `TZ`. The zone's id and
26    /// name are looked up once per process, so set `TZ` before the first
27    /// date is printed.
28    Local,
29    Utc,
30}
31
32pub const MS_PER_DAY: f64 = 86_400_000.0;
33/// The most JavaScript will hold: 8.64e15 ms either side of the epoch.
34pub const MAX_TIME: f64 = 8.64e15;
35
36/// Broken-down time in one zone.
37#[derive(Debug, Clone, Copy, PartialEq)]
38pub struct Fields {
39    pub year: i64,
40    pub month0: u32,
41    pub day: u32,
42    pub hour: u32,
43    pub minute: u32,
44    pub second: u32,
45    pub millis: u32,
46    /// 0 is Sunday.
47    pub weekday: u32,
48    /// `getTimezoneOffset()`: minutes west of UTC.
49    pub offset_west: f64,
50}
51
52/// Days from 1970-01-01 to the civil date. `month` is 1 to 12.
53pub fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
54    let y = if m <= 2 { y - 1 } else { y };
55    let era = y.div_euclid(400);
56    let yoe = y.rem_euclid(400);
57    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
58    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
59    era * 146_097 + doe - 719_468
60}
61
62fn civil_from_days(z: i64) -> (i64, u32, u32) {
63    let z = z + 719_468;
64    let era = z.div_euclid(146_097);
65    let doe = z.rem_euclid(146_097);
66    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
67    let y = yoe + era * 400;
68    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
69    let mp = (5 * doy + 2) / 153;
70    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
71    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
72    (if m <= 2 { y + 1 } else { y }, m, d)
73}
74
75/// The tz database release bundled into Brrrty (`jiff-tzdb` 0.1.7): the
76/// one Node 26.2.0 ships.
77pub const TZDATA_VERSION: &str = "2026b";
78
79/// A zone from the bundled tz database.
80pub struct Zone {
81    /// The name as the tz database spells it.
82    pub name: &'static str,
83    rules: ::tz::TimeZone,
84}
85
86impl Zone {
87    /// The zone called `name` (any case), if the bundled data has it.
88    pub fn named(name: &str) -> Option<&'static Zone> {
89        use std::collections::HashMap;
90        use std::sync::Mutex;
91        static CACHE: OnceLock<Mutex<HashMap<&'static str, &'static Zone>>> = OnceLock::new();
92        let (canonical, bytes) = jiff_tzdb::get(name)?;
93        let mut cache = CACHE.get_or_init(Default::default).lock().ok()?;
94        if let Some(z) = cache.get(canonical) {
95            return Some(z);
96        }
97        let rules = ::tz::TimeZone::from_tz_data(bytes).ok()?;
98        let zone: &'static Zone = Box::leak(Box::new(Zone {
99            name: canonical,
100            rules,
101        }));
102        cache.insert(canonical, zone);
103        Some(zone)
104    }
105
106    /// The UTC offset at the instant `ms`, in seconds east.
107    pub fn offset_seconds(&self, ms: f64) -> i64 {
108        let secs = (ms / 1000.0).floor() as i64;
109        self.rules
110            .find_local_time_type(in_rule_range(secs))
111            .map_or(0, |t| i64::from(t.ut_offset()))
112    }
113}
114
115/// `secs` moved by whole 400-year cycles to within about 250,000 years of
116/// 1970, where the rules can be evaluated. The calendar repeats every 400
117/// years, and so do the zone's rules that far out (the last rule, or the
118/// local mean time before the first), so the offset is the same;
119/// JavaScript's range reaches 275,760.
120fn in_rule_range(secs: i64) -> i64 {
121    const CYCLE: i64 = 146_097 * 86_400;
122    const LIMIT: i64 = 7_800_000_000_000;
123    if secs.abs() <= LIMIT {
124        return secs;
125    }
126    let cycles = (secs.abs() - LIMIT) / CYCLE + 1;
127    secs - secs.signum() * cycles * CYCLE
128}
129
130/// The local zone as ICU names it (the key `%Z` and the long names are
131/// looked up by; `None` for an empty `TZ`), and its rules.
132struct Local {
133    key: Option<String>,
134    zone: &'static Zone,
135}
136
137/// The local zone, or why it can't be used. Read once per process.
138fn local() -> Result<&'static Local, &'static str> {
139    static LOCAL: OnceLock<Result<Local, String>> = OnceLock::new();
140    LOCAL
141        .get_or_init(|| {
142            resolve_local(
143                std::env::var("TZ").ok().as_deref(),
144                std::path::Path::new(LOCALTIME),
145                std::path::Path::new(ZONEINFO),
146            )
147        })
148        .as_ref()
149        .map_err(String::as_str)
150}
151
152fn local_zone() -> Result<&'static Zone, &'static str> {
153    local().map(|l| l.zone)
154}
155
156/// Whether local time can be used: `Err` says why not, naming `TZ` or
157/// `/etc/localtime`. Builds check this before they start, so a page is
158/// never written with a zone guessed.
159pub fn check_local() -> Result<(), String> {
160    local_zone().map(|_| ()).map_err(str::to_string)
161}
162
163/// The name of the local zone as Node's ICU finds it, or why it can't be
164/// told (for a probe or an error message).
165pub fn local_zone_name() -> Result<&'static str, &'static str> {
166    local_zone().map(|z| z.name)
167}
168
169/// ICU's `TZDEFAULT` and `TZZONEINFO` (`putil.cpp`, ICU 78.3), the same on
170/// Linux and macOS.
171const LOCALTIME: &str = "/etc/localtime";
172const ZONEINFO: &str = "/usr/share/zoneinfo";
173
174const SET_TZ: &str = "Set TZ to a zone name such as America/Chicago";
175
176/// ICU's `skipZoneIDPrefix`: `posix/` and `right/` copy the top level.
177fn skip_zone_id_prefix(id: &str) -> &str {
178    id.strip_prefix("posix/")
179        .or_else(|| id.strip_prefix("right/"))
180        .unwrap_or(id)
181}
182
183/// The zone `TZ` names or, when it is unset, the one `/etc/localtime` is,
184/// found as ICU 78.3's `uprv_tzname` finds it, with its rules from the
185/// bundled data:
186///
187/// - `TZ` set: its value without a leading `:` and a `posix/` or `right/`
188///   prefix. An empty `TZ` is UTC, as in Node. A name the bundled data
189///   lacks is refused (Node would fall back to UTC or the system zone).
190/// - `localtime` a symlink: the part of its real path after `/zoneinfo/`,
191///   or of the link's own target when the real path has none or is
192///   `posixrules` (macOS's real path is `/usr/share/zoneinfo.default/...`).
193/// - `localtime` a regular file (a copied zone file, common in Docker
194///   images): the first file under the zoneinfo folder with the same bytes,
195///   searched in directory order as ICU does, skipping `posixrules` and
196///   `localtime`.
197/// - `localtime` missing: UTC.
198fn resolve_local(
199    tz: Option<&str>,
200    localtime: &std::path::Path,
201    zoneinfo: &std::path::Path,
202) -> Result<Local, String> {
203    let utc = |key: Option<String>| {
204        Zone::named("UTC")
205            .map(|zone| Local { key, zone })
206            .ok_or_else(|| "the bundled tz data has no UTC".to_string())
207    };
208    if let Some(raw) = tz {
209        let name = raw.strip_prefix(':').unwrap_or(raw);
210        if name.is_empty() {
211            return utc(None);
212        }
213        let name = match name.strip_prefix('/') {
214            Some(_) => name.split_once("zoneinfo/").map_or("", |(_, z)| z),
215            None => name,
216        };
217        let name = skip_zone_id_prefix(name);
218        return Zone::named(name)
219            .map(|zone| Local {
220                key: Some(name.to_string()),
221                zone,
222            })
223            .ok_or_else(|| {
224                format!(
225                    "TZ is `{raw}`, which isn't a time zone in Brrrty's tz data ({TZDATA_VERSION}, Node 26's). \
226                     Node would quietly use UTC or the system zone instead. Set TZ to a zone name such as \
227                     America/Chicago, or unset it"
228                )
229            });
230    }
231    let named = |name: &str, how: String| {
232        Zone::named(name)
233            .map(|zone| Local {
234                key: Some(name.to_string()),
235                zone,
236            })
237            .ok_or_else(|| {
238                format!(
239                    "{how} `{name}`, which isn't a time zone in Brrrty's tz data ({TZDATA_VERSION}). {}",
240                    SET_TZ
241                )
242            })
243    };
244    let meta = match std::fs::symlink_metadata(localtime) {
245        Ok(m) => m,
246        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return utc(Some("UTC".into())),
247        Err(e) => {
248            return Err(format!(
249                "can't read {}: {e}. {}",
250                localtime.display(),
251                SET_TZ
252            ));
253        }
254    };
255    if meta.file_type().is_symlink() {
256        // ICU: `realpath`; if that fails (a broken link), the search below,
257        // which can't read the file either, so ICU guesses from the C
258        // library's abbreviation. Brrrty refuses.
259        let Ok(real) = std::fs::canonicalize(localtime) else {
260            return Err(format!(
261                "{} is a broken link, so Brrrty can't tell its time zone (Node would guess from \
262                 the C library's). {SET_TZ}",
263                localtime.display()
264            ));
265        };
266        let tail = |p: &str| p.split_once("/zoneinfo/").map(|(_, t)| t.to_string());
267        let name = tail(&real.to_string_lossy())
268            .filter(|t| t != "posixrules")
269            .or_else(|| {
270                std::fs::read_link(localtime)
271                    .ok()
272                    .and_then(|p| tail(&p.to_string_lossy()))
273            });
274        return match name {
275            Some(name) => named(
276                skip_zone_id_prefix(&name),
277                format!("{} links to", localtime.display()),
278            ),
279            None => Err(format!(
280                "{} is a link, but not into a zoneinfo folder, so Brrrty can't tell its time zone. {SET_TZ}",
281                localtime.display()
282            )),
283        };
284    }
285    let wanted = std::fs::read(localtime)
286        .map_err(|e| format!("can't read {}: {e}. {}", localtime.display(), SET_TZ))?;
287    let mut dir = zoneinfo.to_string_lossy().into_owned();
288    if !dir.ends_with('/') {
289        dir.push('/');
290    }
291    match search_for_tz_file(&dir, dir.len(), &wanted) {
292        Some(name) => named(&name, format!("{} is a copy of", localtime.display())),
293        None => Err(format!(
294            "{} is a file, and no zone in {} has the same bytes, so Brrrty can't tell its time zone \
295             (Node would guess from its abbreviation). {}",
296            localtime.display(),
297            zoneinfo.display(),
298            SET_TZ
299        )),
300    }
301}
302
303/// ICU's `searchForTZFile`: depth first in directory order, the first file
304/// with the same bytes as `wanted`, named from `root_len` on, with a
305/// `posix/` or `right/` prefix skipped. Paths are cut off at `PATH_MAX`,
306/// where `opendir` fails.
307fn search_for_tz_file(dir: &str, root_len: usize, wanted: &[u8]) -> Option<String> {
308    const PATH_MAX: usize = 4096;
309    let entries = std::fs::read_dir(dir).ok()?;
310    for entry in entries.flatten() {
311        let name = entry.file_name();
312        let name = name.to_string_lossy();
313        if name == "posixrules" || name == "localtime" {
314            continue;
315        }
316        let path = format!("{dir}{name}");
317        if path.len() + 1 >= PATH_MAX {
318            continue;
319        }
320        if std::fs::metadata(&path).is_ok_and(|m| m.is_dir()) {
321            if let Some(found) = search_for_tz_file(&format!("{path}/"), root_len, wanted) {
322                return Some(found);
323            }
324        } else if std::fs::metadata(&path).is_ok_and(|m| m.len() == wanted.len() as u64)
325            && std::fs::read(&path).is_ok_and(|b| b == wanted)
326        {
327            return Some(skip_zone_id_prefix(&path[root_len.min(path.len())..]).to_string());
328        }
329    }
330    None
331}
332
333/// The UTC offset of `tz` at the instant `ms`, in seconds east.
334fn offset_seconds(tz: Tz, ms: f64) -> i64 {
335    match tz {
336        Tz::Utc => 0,
337        Tz::Local => local_zone().map_or(0, |z| z.offset_seconds(ms)),
338    }
339}
340
341/// Broken-down time of the instant `ms` in `tz`.
342pub fn fields(tz: Tz, ms: f64) -> Option<Fields> {
343    if !ms.is_finite() || ms.abs() > MAX_TIME {
344        return None;
345    }
346    let offset = offset_seconds(tz, ms);
347    let local = ms as i64 + offset * 1000;
348    let days = local.div_euclid(86_400_000);
349    let in_day = local.rem_euclid(86_400_000);
350    let (year, month, day) = civil_from_days(days);
351    Some(Fields {
352        year,
353        month0: month - 1,
354        day,
355        hour: (in_day / 3_600_000) as u32,
356        minute: (in_day / 60_000 % 60) as u32,
357        second: (in_day / 1000 % 60) as u32,
358        millis: (in_day % 1000) as u32,
359        weekday: (days + 4).rem_euclid(7) as u32,
360        // V8 drops the seconds of a historical offset.
361        offset_west: (-(offset as f64) / 60.0).trunc() + 0.0,
362    })
363}
364
365/// The instant whose wall-clock time in `tz` is `local_ms` (read as if it
366/// were UTC). For a time the clocks skip, the offset from before the
367/// change is used, and for a time they repeat, the first one, as
368/// JavaScript does.
369pub fn local_to_utc(tz: Tz, local_ms: f64) -> f64 {
370    if tz == Tz::Utc || !local_ms.is_finite() {
371        return local_ms;
372    }
373    // The offsets either side of the day: a change of offset lies between
374    // them, so one of them is the right one, or two are for a time that
375    // repeats.
376    let before = offset_seconds(tz, local_ms - MS_PER_DAY);
377    let after = offset_seconds(tz, local_ms + MS_PER_DAY);
378    let valid = |off: i64| offset_seconds(tz, local_ms - off as f64 * 1000.0) == off;
379    let offset = match (valid(before), valid(after)) {
380        (true, true) => before.max(after),
381        (true, false) => before,
382        (false, true) => after,
383        // The clocks skip this time: the offset from before the change.
384        (false, false) => before,
385    };
386    local_ms - offset as f64 * 1000.0
387}
388
389/// `new Date(year, month, day, hours, minutes, seconds, ms)` with two to
390/// seven arguments, already numbers: a wall-clock time in `tz`, as
391/// milliseconds since 1970, or `NaN`. Missing arguments are day 1 and 0.
392/// Fields roll over as in JavaScript (month 12 is January of the next
393/// year, day 0 the last day of the month before), fractions are dropped,
394/// and a whole year from 0 to 99 means 1900 to 1999.
395pub fn make_date(tz: Tz, args: &[f64]) -> f64 {
396    let get = |i: usize, default: f64| args.get(i).copied().unwrap_or(default);
397    let mut year = get(0, f64::NAN);
398    if year.is_finite() {
399        let y = year.trunc();
400        if (0.0..=99.0).contains(&y) {
401            year = 1900.0 + y;
402        }
403    }
404    let day = make_day(year, get(1, 0.0), get(2, 1.0));
405    let time = make_time(get(3, 0.0), get(4, 0.0), get(5, 0.0), get(6, 0.0));
406    let local = day * MS_PER_DAY + time;
407    // V8 gives up on a local time well outside the range before looking
408    // up the zone.
409    if !local.is_finite() || local.abs() > MAX_TIME + 10.0 * MS_PER_DAY {
410        return f64::NAN;
411    }
412    time_clip(local_to_utc(tz, local))
413}
414
415/// The spec's `TimeClip`: `NaN` outside 8.64e15 ms, else whole ms.
416pub fn time_clip(t: f64) -> f64 {
417    if !t.is_finite() || t.abs() > MAX_TIME {
418        f64::NAN
419    } else {
420        t.trunc() + 0.0
421    }
422}
423
424/// The spec's `MakeDay`, with V8's limits on the year and month.
425fn make_day(year: f64, month: f64, date: f64) -> f64 {
426    if !year.is_finite() || !month.is_finite() || !date.is_finite() {
427        return f64::NAN;
428    }
429    let (y, m, dt) = (year.trunc(), month.trunc(), date.trunc());
430    if !(-1_000_000.0..=1_000_000.0).contains(&y) || !(-10_000_000.0..=10_000_000.0).contains(&m) {
431        return f64::NAN;
432    }
433    let ym = y as i64 + (m as i64).div_euclid(12);
434    let mn = (m as i64).rem_euclid(12);
435    days_from_civil(ym, mn + 1, 1) as f64 + dt - 1.0
436}
437
438/// The spec's `MakeTime`.
439fn make_time(h: f64, min: f64, s: f64, ms: f64) -> f64 {
440    if !h.is_finite() || !min.is_finite() || !s.is_finite() || !ms.is_finite() {
441        return f64::NAN;
442    }
443    h.trunc() * 3_600_000.0 + min.trunc() * 60_000.0 + s.trunc() * 1000.0 + ms.trunc()
444}
445
446/// `Date.prototype.toISOString()`, or `None` for an invalid date (where
447/// JavaScript throws a `RangeError`, "Invalid time value"). A year outside
448/// 0 to 9999 has a sign and six digits.
449pub fn iso_string(ms: f64) -> Option<String> {
450    let f = fields(Tz::Utc, ms)?;
451    let year = if (0..=9999).contains(&f.year) {
452        format!("{:04}", f.year)
453    } else {
454        format!(
455            "{}{:06}",
456            if f.year < 0 { '-' } else { '+' },
457            f.year.unsigned_abs()
458        )
459    };
460    Some(format!(
461        "{year}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",
462        f.month0 + 1,
463        f.day,
464        f.hour,
465        f.minute,
466        f.second,
467        f.millis
468    ))
469}
470
471/// The local zone's name as ICU found it, for the id and long names.
472fn local_zone_key() -> Option<&'static str> {
473    local().ok()?.key.as_deref()
474}
475
476/// Whether `name` is a zone in the tz database, ignoring case.
477pub fn is_known_zone(name: &str) -> bool {
478    ZONE_IDS
479        .iter()
480        .any(|(zone, _)| zone.eq_ignore_ascii_case(name))
481}
482
483/// The id Node reports for the local zone (`resolvedOptions().timeZone`),
484/// which is what `%Z` prints. `None` when the zone is not one it knows.
485pub fn zone_id(tz: Tz) -> Option<&'static str> {
486    match tz {
487        Tz::Utc => Some("UTC"),
488        Tz::Local => {
489            let key = local_zone_key()?;
490            ZONE_IDS
491                .binary_search_by_key(&key, |(zone, _)| *zone)
492                .ok()
493                .map(|i| ZONE_IDS[i].1)
494        }
495    }
496}
497
498/// The long name `Date.prototype.toString` prints in parentheses for a
499/// time at `offset_east` minutes east of UTC.
500///
501/// Node's names come from ICU. For the local zone this looks the zone's id
502/// up in a table generated from Node and finds the name for the offset,
503/// which tells standard time from daylight time. An offset the zone has
504/// used more than once under different names gets the most recent name
505/// (Moscow's +4 was "Moscow Summer Time" before 2011 and "Moscow Standard
506/// Time" after it). A zone or offset that is not in the table, such as a
507/// custom `TZ` like `CET-1CEST`, gets ICU's fallback form: `GMT+05:30`.
508pub fn long_name(tz: Tz, offset_east: i64) -> String {
509    let offset_min = (offset_east / 60) as i16;
510    let known = match tz {
511        Tz::Utc => Some("Coordinated Universal Time"),
512        Tz::Local => zone_id(tz).and_then(|id| {
513            let profile = PROFILES
514                .binary_search_by_key(&id, |(p, _)| *p)
515                .ok()
516                .map(|i| PROFILES[i].1)?;
517            profile
518                .iter()
519                .find(|(o, _)| *o == offset_min)
520                .map(|(_, name)| *name)
521        }),
522    };
523    match known {
524        Some(name) => name.to_string(),
525        None => gmt_offset(offset_east),
526    }
527}
528
529/// `GMT+05:30`.
530fn gmt_offset(offset_east: i64) -> String {
531    let sign = if offset_east < 0 { '-' } else { '+' };
532    let abs = offset_east.abs();
533    format!("GMT{sign}{:02}:{:02}", abs / 3600, abs / 60 % 60)
534}
535
536const DAYS: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
537const MONTHS: [&str; 12] = [
538    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
539];
540
541/// `Date.prototype.toString()` of the instant `ms`:
542/// `Fri Nov 15 2026 00:00:00 GMT+0000 (Coordinated Universal Time)`.
543pub fn date_to_string(tz: Tz, ms: f64) -> String {
544    let Some(f) = fields(tz, ms) else {
545        return "Invalid Date".into();
546    };
547    let offset_east = (-f.offset_west * 60.0) as i64;
548    let sign = if offset_east < 0 { '-' } else { '+' };
549    let abs = offset_east.abs();
550    let year = if f.year < 0 {
551        format!("-{:06}", -f.year)
552    } else {
553        format!("{:04}", f.year)
554    };
555    format!(
556        "{} {} {:02} {year} {:02}:{:02}:{:02} GMT{sign}{:02}{:02} ({})",
557        DAYS[f.weekday as usize],
558        MONTHS[f.month0 as usize],
559        f.day,
560        f.hour,
561        f.minute,
562        f.second,
563        abs / 3600,
564        abs / 60 % 60,
565        long_name(tz, offset_east),
566    )
567}
568
569#[cfg(test)]
570mod tests {
571    use super::*;
572
573    #[test]
574    fn utc_prints_like_node() {
575        // node: new Date(Date.UTC(2026, 10, 15)).toString() with TZ=UTC
576        let ms = 1_794_700_800_000.0;
577        assert_eq!(
578            date_to_string(Tz::Utc, ms),
579            "Sun Nov 15 2026 00:00:00 GMT+0000 (Coordinated Universal Time)"
580        );
581        // Years outside 0000 to 9999: node prints -000001 and 275760.
582        assert_eq!(
583            date_to_string(Tz::Utc, -62_198_755_200_000.0),
584            "Fri Jan 01 -000001 00:00:00 GMT+0000 (Coordinated Universal Time)"
585        );
586        assert_eq!(
587            date_to_string(Tz::Utc, 8.64e15),
588            "Sat Sep 13 275760 00:00:00 GMT+0000 (Coordinated Universal Time)"
589        );
590    }
591
592    #[test]
593    fn civil_dates_round_trip() {
594        for days in [-1_000_000, -719_468, -1, 0, 1, 19_000, 2_932_896] {
595            let (y, m, d) = civil_from_days(days);
596            assert_eq!(days_from_civil(y, i64::from(m), i64::from(d)), days);
597        }
598        assert_eq!(civil_from_days(0), (1970, 1, 1));
599        assert_eq!(civil_from_days(19_787), (2024, 3, 5));
600    }
601
602    #[test]
603    fn the_generated_tables_can_be_searched() {
604        assert!(
605            ZONE_IDS.windows(2).all(|w| w[0].0 < w[1].0),
606            "ZONE_IDS sorted"
607        );
608        assert!(
609            PROFILES.windows(2).all(|w| w[0].0 < w[1].0),
610            "PROFILES sorted"
611        );
612        for (zone, id) in ZONE_IDS {
613            assert!(
614                PROFILES.binary_search_by_key(id, |(p, _)| *p).is_ok(),
615                "{zone} has no profile for {id}"
616            );
617        }
618        let profile =
619            |id: &str| PROFILES[PROFILES.binary_search_by_key(&id, |(p, _)| *p).unwrap()].1;
620        // node: TZ=America/New_York new Date(2026, 0, 15).toString() and July.
621        assert!(profile("America/New_York").contains(&(-300, "Eastern Standard Time")));
622        assert!(profile("America/New_York").contains(&(-240, "Eastern Daylight Time")));
623        assert!(profile("Europe/London").contains(&(60, "British Summer Time")));
624        assert!(profile("Asia/Calcutta").contains(&(330, "India Standard Time")));
625        // Aliases resolve to the id Node reports.
626        let id =
627            |zone: &str| ZONE_IDS[ZONE_IDS.binary_search_by_key(&zone, |(z, _)| *z).unwrap()].1;
628        assert_eq!(id("US/Eastern"), "America/New_York");
629        assert_eq!(id("Asia/Kolkata"), "Asia/Calcutta");
630        assert_eq!(id("Etc/UTC"), "UTC");
631    }
632
633    #[test]
634    fn an_offset_missing_from_the_table_falls_back_to_gmt_form() {
635        assert_eq!(gmt_offset(19_800), "GMT+05:30");
636        assert_eq!(gmt_offset(-3_600), "GMT-01:00");
637        assert_eq!(gmt_offset(0), "GMT+00:00");
638    }
639
640    fn name(
641        tz: Option<&str>,
642        lt: &std::path::Path,
643        zi: &std::path::Path,
644    ) -> Result<String, String> {
645        resolve_local(tz, lt, zi).map(|l| format!("{} {:?}", l.zone.name, l.key))
646    }
647
648    /// ICU 78.3's `uprv_tzname`, case by case.
649    #[test]
650    fn the_local_zone_is_found_as_icu_finds_it() {
651        let dir = tempfile::tempdir().unwrap();
652        let zi = dir.path().join("zoneinfo");
653        std::fs::create_dir_all(zi.join("Europe")).unwrap();
654        std::fs::create_dir_all(zi.join("posix/Asia")).unwrap();
655        let berlin = jiff_tzdb::get("Europe/Berlin").unwrap().1;
656        let tokyo = jiff_tzdb::get("Asia/Tokyo").unwrap().1;
657        std::fs::write(zi.join("Europe/Berlin"), berlin).unwrap();
658        std::fs::write(zi.join("posix/Asia/Tokyo"), tokyo).unwrap();
659        // Skipped by name, as ICU skips them.
660        std::fs::write(zi.join("posixrules"), tokyo).unwrap();
661        std::fs::write(zi.join("localtime"), berlin).unwrap();
662
663        // Missing: UTC.
664        let missing = dir.path().join("missing");
665        assert_eq!(name(None, &missing, &zi).unwrap(), "UTC Some(\"UTC\")");
666        // A copy: found by its bytes; a `posix/` prefix is skipped.
667        let copy = dir.path().join("copy");
668        std::fs::write(&copy, berlin).unwrap();
669        assert_eq!(
670            name(None, &copy, &zi).unwrap(),
671            "Europe/Berlin Some(\"Europe/Berlin\")"
672        );
673        std::fs::write(&copy, tokyo).unwrap();
674        assert_eq!(
675            name(None, &copy, &zi).unwrap(),
676            "Asia/Tokyo Some(\"Asia/Tokyo\")"
677        );
678        // A copy of nothing in the folder, or with no folder: refused.
679        std::fs::write(&copy, b"TZif not a zone").unwrap();
680        assert!(name(None, &copy, &zi).unwrap_err().contains("same bytes"));
681        std::fs::write(&copy, berlin).unwrap();
682        assert!(
683            name(None, &copy, &dir.path().join("none"))
684                .unwrap_err()
685                .contains("Set TZ")
686        );
687        // A link: the part of its real path after /zoneinfo/, without posix/.
688        std::fs::create_dir_all(zi.join("posix/Europe")).unwrap();
689        std::fs::write(zi.join("posix/Europe/Paris"), b"x").unwrap();
690        let link = dir.path().join("link");
691        std::os::unix::fs::symlink(zi.join("posix/Europe/Paris"), &link).unwrap();
692        assert_eq!(
693            name(None, &link, &zi).unwrap(),
694            "Europe/Paris Some(\"Europe/Paris\")"
695        );
696        // A broken link: ICU can't read it either, and guesses; refused.
697        let broken = dir.path().join("broken");
698        std::os::unix::fs::symlink("/nowhere/zoneinfo/posix/Asia/Tokyo", &broken).unwrap();
699        assert!(
700            name(None, &broken, &zi)
701                .unwrap_err()
702                .contains("broken link")
703        );
704        let real = dir.path().join("real");
705        std::os::unix::fs::symlink(zi.join("Europe/Berlin"), &real).unwrap();
706        assert_eq!(
707            name(None, &real, &zi).unwrap(),
708            "Europe/Berlin Some(\"Europe/Berlin\")"
709        );
710        let odd = dir.path().join("odd");
711        std::os::unix::fs::symlink(&copy, &odd).unwrap();
712        assert!(
713            name(None, &odd, &zi)
714                .unwrap_err()
715                .contains("not into a zoneinfo folder")
716        );
717
718        // TZ wins, without its colon or a posix/ prefix; empty is UTC with no id.
719        assert_eq!(
720            name(Some(":Asia/Tokyo"), &link, &zi).unwrap(),
721            "Asia/Tokyo Some(\"Asia/Tokyo\")"
722        );
723        assert_eq!(
724            name(Some("posix/Asia/Tokyo"), &link, &zi).unwrap(),
725            "Asia/Tokyo Some(\"Asia/Tokyo\")"
726        );
727        assert_eq!(
728            name(Some("asia/tokyo"), &link, &zi).unwrap(),
729            "Asia/Tokyo Some(\"asia/tokyo\")"
730        );
731        assert_eq!(
732            name(Some("US/Pacific"), &link, &zi).unwrap(),
733            "US/Pacific Some(\"US/Pacific\")"
734        );
735        assert_eq!(name(Some(""), &link, &zi).unwrap(), "UTC None");
736        assert_eq!(
737            name(Some("/usr/share/zoneinfo/Europe/Paris"), &missing, &zi).unwrap(),
738            "Europe/Paris Some(\"Europe/Paris\")"
739        );
740        // Typos, stray spaces and POSIX rules: Node would quietly use UTC
741        // or the system zone, so Brrrty refuses, naming TZ.
742        for bad in [
743            "Foo/Bar",
744            "America/Chigaco",
745            "America/Chicago ",
746            "EST5EDT,M3.2.0,M11.1.0",
747            "CET-1CEST,M3.5.0,M10.5.0/3",
748            "<+0330>-3:30",
749            "JST-9",
750            "/etc/localtime",
751        ] {
752            let why = name(Some(bad), &missing, &zi).unwrap_err();
753            assert!(why.contains(&format!("TZ is `{bad}`")), "{why}");
754        }
755    }
756
757    #[test]
758    fn the_bundled_tz_data_is_the_release_named() {
759        assert_eq!(jiff_tzdb::VERSION, Some(TZDATA_VERSION));
760    }
761
762    #[test]
763    fn offsets_are_node_26_s_not_the_system_s() {
764        // tz 2026c makes Alberta UTC-6 all year from 2026-11-01; Node 26.2.0
765        // ships 2026b, where 2026-11-17 is still UTC-7.
766        let edmonton = Zone::named("America/Edmonton").unwrap();
767        assert_eq!(edmonton.offset_seconds(1_794_916_800_000.0), -7 * 3600);
768    }
769
770    #[test]
771    fn known_zones_ignore_case() {
772        assert!(is_known_zone("america/new_york"));
773        assert!(is_known_zone("Europe/Paris"));
774        assert!(!is_known_zone("Mars/Olympus"));
775    }
776}