Skip to main content

nodejs/
tznames.rs

1//! ICU's en SPECIFIC zone names — `Eastern Standard Time` / `EST`, the `zzzz`
2//! and `z` pattern fields and the parenthetical of `Date.prototype.toString`.
3//!
4//! ICU names a zone through its METAZONE at an instant: `America/New_York`
5//! belongs to `America_Eastern`, whose en names are `Eastern Standard Time`,
6//! `Eastern Daylight Time`, `EST` and `EDT`. A zone may change metazone over
7//! time (`Africa/Algiers` moved between `Europe_Western` and `Europe_Central`
8//! four times), a metazone may lack a name of some width (`Europe_Central` has
9//! no short names in en, so Paris is `GMT+1` under `timeZoneName: 'short'`),
10//! and a zone may carry names of its own ahead of any metazone (`Etc/UTC`). A
11//! missing name falls back to the localized GMT format, which the callers
12//! render.
13//!
14//! The tables in `tznames_data.rs` transcribe ICU 79.1 / CLDR 49, the data node
15//! v26.12.1 ships. Keying by the zone rather than by the abbreviation
16//! `localtime` reports is what tells `Europe/London` (metazone `British`, no
17//! standard-time name: `GMT+0`) from `Atlantic/Reykjavik` (metazone `GMT`:
18//! `GMT`), which share the abbreviation `GMT`.
19
20#[path = "tznames_data.rs"]
21mod data;
22
23/// ICU's canonical id for `id` (`Asia/Kolkata` → `Asia/Calcutta`,
24/// `US/Eastern` → `America/New_York`): the key the metazone table uses.
25fn canonical(id: &str) -> &str {
26    match data::ALIASES.binary_search_by(|(alias, _)| alias.cmp(&id)) {
27        Ok(i) => data::ALIASES[i].1,
28        Err(_) => id,
29    }
30}
31
32/// The metazone `id` belongs to at `secs` (UTC epoch seconds); a mapping
33/// covers `[from, to)`.
34fn metazone_at(id: &str, secs: i64) -> Option<&'static str> {
35    let i = data::ZONE_METAZONES
36        .binary_search_by(|(zone, _)| zone.cmp(&id))
37        .ok()?;
38    data::ZONE_METAZONES[i]
39        .1
40        .iter()
41        .find(|(_, from, to)| *from <= secs && secs < *to)
42        .map(|(mz, _, _)| *mz)
43}
44
45/// Pick one of a `[ls, ld, ss, sd]` row.
46fn pick(row: &[Option<&'static str>; 4], dst: bool, long: bool) -> Option<&'static str> {
47    row[usize::from(!long) * 2 + usize::from(dst)]
48}
49
50/// The en specific name of zone `id` at `secs` — long (`zzzz`) or short
51/// (`z`), daylight or standard — or `None` where ICU falls back to the GMT
52/// format.
53pub fn specific_name(id: &str, secs: i64, dst: bool, long: bool) -> Option<&'static str> {
54    let id = canonical(id);
55    if let Ok(i) = data::ZONE_NAMES.binary_search_by(|(zone, _)| zone.cmp(&id)) {
56        if let Some(name) = pick(&data::ZONE_NAMES[i].1, dst, long) {
57            return Some(name);
58        }
59    }
60    let mz = metazone_at(id, secs)?;
61    let i = data::METAZONE_NAMES
62        .binary_search_by(|(m, _)| m.cmp(&mz))
63        .ok()?;
64    pick(&data::METAZONE_NAMES[i].1, dst, long)
65}
66
67/// The IANA id of the process's local zone: `TZ` (a leading `:` dropped, a
68/// path reduced to what follows `zoneinfo/`, empty meaning UTC), else the
69/// target of `/etc/localtime`. Read on every call, as `localtime_r` re-reads
70/// `TZ`. `None` when neither names a zone the system has (a POSIX rule string
71/// such as `EST5EDT,M3.2.0,M11.1.0`).
72pub fn local_zone_id() -> Option<String> {
73    let from_path = |p: &str| p.rsplit_once("zoneinfo/").map(|(_, id)| id.to_string());
74    let id = match std::env::var("TZ") {
75        Ok(tz) => {
76            let tz = tz.strip_prefix(':').unwrap_or(&tz);
77            if tz.is_empty() {
78                "UTC".to_string()
79            } else if tz.starts_with('/') {
80                from_path(tz)?
81            } else {
82                tz.to_string()
83            }
84        }
85        Err(_) => from_path(&std::fs::read_link("/etc/localtime").ok()?.to_string_lossy())?,
86    };
87    crate::tzif::load(&id).map(|_| id)
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    #[test]
95    fn names_come_from_the_metazone_at_the_instant() {
96        assert_eq!(
97            specific_name("America/New_York", 0, false, true),
98            Some("Eastern Standard Time")
99        );
100        assert_eq!(specific_name("US/Eastern", 0, true, false), Some("EDT"));
101        assert_eq!(
102            specific_name("Asia/Kolkata", 0, false, true),
103            Some("India Standard Time")
104        );
105        assert_eq!(specific_name("Europe/Paris", 0, false, false), None);
106        assert_eq!(
107            specific_name("Europe/London", 1_700_000_000, false, true),
108            None
109        );
110        assert_eq!(
111            specific_name("Europe/London", 1_700_000_000, true, true),
112            Some("British Summer Time")
113        );
114        assert_eq!(specific_name("UTC", 0, false, false), Some("UTC"));
115    }
116}