Skip to main content

time_zone/
iana.rs

1//! Optional IANA zone name tables.
2//!
3//! The tables map IANA identifiers such as `Europe/Paris` to the POSIX TZ
4//! string of the zone. They are generated from the IANA time zone database; the
5//! version of the database is in [`TZDATA_VERSION`]. One table per region is
6//! compiled with its Cargo feature, and the features combine:
7//!
8//! | Feature | Names |
9//! | --- | --- |
10//! | none (default) | no names: [`zone_count`] is 0 and every lookup fails |
11//! | `iana-africa`, `iana-america`, `iana-antarctica`, `iana-arctic`, `iana-asia`, `iana-atlantic`, `iana-australia`, `iana-europe`, `iana-indian`, `iana-pacific` | the names with that prefix, for example `Europe/Paris` |
12//! | `iana-etc` | the fixed offset zones `Etc/...` and `GMT` |
13//! | `iana-all` | every region |
14//!
15//! A region holds the names with its prefix only: `Atlantic/Madeira` is in
16//! `iana-atlantic`, not in `iana-europe`. The four canonical names without a
17//! prefix, `CST6CDT`, `EST5EDT`, `MST7MDT` and `PST8PDT`, are in
18//! `iana-america`. `Factory` is in no table.
19//!
20//! By default, the tables hold the canonical names and the listed aliases:
21//! the `backward` links that tzdata `zone.tab` lists for a country, such as
22//! `Europe/Amsterdam`, `Europe/Oslo` or `Atlantic/Reykjavik` (zones that
23//! tzdata merged into another one), so that every country keeps its names.
24//! With `iana-legacy-aliases`, each enabled region also holds the other
25//! `backward` links, for example `US/Eastern`, `Japan` or `Asia/Calcutta`. An
26//! alias is in the region of its prefix, or, without a region prefix, in the
27//! region of the zone that it names (`US/Eastern` is in `iana-america`). An
28//! alias row is its name and the index of the TZ string of the zone that it
29//! names, shared with that zone.
30//!
31//! [`zone_name`] lists the enabled region tables in alphabetical order of
32//! feature name (`iana-africa` through `iana-pacific`, with `iana-etc` between
33//! `iana-australia` and `iana-europe`), with the names of each table sorted,
34//! aliases included. Zones of a region that share a TZ string share it in one
35//! string blob.
36//!
37//! ```
38//! # #[cfg(feature = "iana-europe")]
39//! # {
40//! use time_zone::{iana, TimeZone};
41//!
42//! let paris = TimeZone::from_iana_name("Europe/Paris").unwrap();
43//! assert_eq!(paris.standard_abbreviation(), "CET");
44//! assert_eq!(
45//!     iana::time_zone_string("Europe/Dublin"),
46//!     Some("IST-1GMT0,M10.5.0,M3.5.0/1")
47//! );
48//! assert!(TimeZone::from_iana_name("Not/AZone").is_none());
49//! # }
50//! ```
51
52use crate::TimeZone;
53use crate::generated;
54use core::cmp::Ordering;
55
56/// The version of the IANA time zone database that the tables were generated
57/// from, for example `2026f`.
58pub const TZDATA_VERSION: &str = generated::TZDATA_VERSION;
59
60/// One generated table: a sorted name blob and a TZ string blob, both of
61/// `\0` terminated strings.
62pub(crate) struct Table {
63    /// The names, sorted, each ended by `\0`.
64    pub(crate) names: &'static str,
65    /// The start of each name in `names`, plus the end of the blob.
66    pub(crate) name_offsets: &'static [u16],
67    /// The index in `string_offsets` of the TZ string of each name.
68    pub(crate) zone_string: &'static [u8],
69    /// The TZ strings, each ended by `\0`.
70    pub(crate) strings: &'static str,
71    /// The start of each TZ string in `strings`, plus the end of the blob.
72    pub(crate) string_offsets: &'static [u16],
73}
74
75impl Table {
76    fn count(&self) -> usize {
77        self.name_offsets.len() - 1
78    }
79
80    fn name(&self, index: usize) -> Option<&'static str> {
81        let start = usize::from(*self.name_offsets.get(index)?);
82        let end = usize::from(*self.name_offsets.get(index + 1)?);
83        self.names.get(start..end - 1)
84    }
85
86    fn time_zone_string(&self, index: usize) -> Option<&'static str> {
87        let string = usize::from(*self.zone_string.get(index)?);
88        let start = usize::from(*self.string_offsets.get(string)?);
89        let end = usize::from(*self.string_offsets.get(string + 1)?);
90        self.strings.get(start..end - 1)
91    }
92
93    /// Binary search for a name. The lookup compares bytes in a loop so that
94    /// it needs no `memcmp` call; some freestanding targets do not provide one.
95    fn lookup(&self, name: &str) -> Option<usize> {
96        let mut low = 0;
97        let mut high = self.count();
98        while low < high {
99            let middle = (low + high) / 2;
100            match compare(self.name(middle)?.as_bytes(), name.as_bytes()) {
101                Ordering::Less => low = middle + 1,
102                Ordering::Greater => high = middle,
103                Ordering::Equal => return Some(middle),
104            }
105        }
106        None
107    }
108}
109
110/// The tables of the enabled features, in the order of [`zone_name`].
111const TABLES: &[&Table] = &[
112    #[cfg(all(feature = "iana-africa", not(feature = "iana-legacy-aliases")))]
113    &generated::africa::TABLE,
114    #[cfg(all(feature = "iana-africa", feature = "iana-legacy-aliases"))]
115    &generated::africa::TABLE_WITH_LEGACY_ALIASES,
116    #[cfg(all(feature = "iana-america", not(feature = "iana-legacy-aliases")))]
117    &generated::america::TABLE,
118    #[cfg(all(feature = "iana-america", feature = "iana-legacy-aliases"))]
119    &generated::america::TABLE_WITH_LEGACY_ALIASES,
120    #[cfg(all(feature = "iana-antarctica", not(feature = "iana-legacy-aliases")))]
121    &generated::antarctica::TABLE,
122    #[cfg(all(feature = "iana-antarctica", feature = "iana-legacy-aliases"))]
123    &generated::antarctica::TABLE_WITH_LEGACY_ALIASES,
124    #[cfg(all(feature = "iana-arctic", not(feature = "iana-legacy-aliases")))]
125    &generated::arctic::TABLE,
126    #[cfg(all(feature = "iana-arctic", feature = "iana-legacy-aliases"))]
127    &generated::arctic::TABLE_WITH_LEGACY_ALIASES,
128    #[cfg(all(feature = "iana-asia", not(feature = "iana-legacy-aliases")))]
129    &generated::asia::TABLE,
130    #[cfg(all(feature = "iana-asia", feature = "iana-legacy-aliases"))]
131    &generated::asia::TABLE_WITH_LEGACY_ALIASES,
132    #[cfg(all(feature = "iana-atlantic", not(feature = "iana-legacy-aliases")))]
133    &generated::atlantic::TABLE,
134    #[cfg(all(feature = "iana-atlantic", feature = "iana-legacy-aliases"))]
135    &generated::atlantic::TABLE_WITH_LEGACY_ALIASES,
136    #[cfg(all(feature = "iana-australia", not(feature = "iana-legacy-aliases")))]
137    &generated::australia::TABLE,
138    #[cfg(all(feature = "iana-australia", feature = "iana-legacy-aliases"))]
139    &generated::australia::TABLE_WITH_LEGACY_ALIASES,
140    #[cfg(all(feature = "iana-etc", not(feature = "iana-legacy-aliases")))]
141    &generated::etc::TABLE,
142    #[cfg(all(feature = "iana-etc", feature = "iana-legacy-aliases"))]
143    &generated::etc::TABLE_WITH_LEGACY_ALIASES,
144    #[cfg(all(feature = "iana-europe", not(feature = "iana-legacy-aliases")))]
145    &generated::europe::TABLE,
146    #[cfg(all(feature = "iana-europe", feature = "iana-legacy-aliases"))]
147    &generated::europe::TABLE_WITH_LEGACY_ALIASES,
148    #[cfg(all(feature = "iana-indian", not(feature = "iana-legacy-aliases")))]
149    &generated::indian::TABLE,
150    #[cfg(all(feature = "iana-indian", feature = "iana-legacy-aliases"))]
151    &generated::indian::TABLE_WITH_LEGACY_ALIASES,
152    #[cfg(all(feature = "iana-pacific", not(feature = "iana-legacy-aliases")))]
153    &generated::pacific::TABLE,
154    #[cfg(all(feature = "iana-pacific", feature = "iana-legacy-aliases"))]
155    &generated::pacific::TABLE_WITH_LEGACY_ALIASES,
156];
157
158/// The number of zone names in the enabled tables.
159pub fn zone_count() -> usize {
160    TABLES.iter().map(|table| table.count()).sum()
161}
162
163/// The zone name at an index, for 0 to [`zone_count`].
164pub fn zone_name(index: usize) -> Option<&'static str> {
165    let mut index = index;
166    for table in TABLES {
167        if index < table.count() {
168            return table.name(index);
169        }
170        index -= table.count();
171    }
172    None
173}
174
175/// Whether the enabled tables have a zone name.
176pub fn contains(name: &str) -> bool {
177    time_zone_string(name).is_some()
178}
179
180/// The POSIX TZ string of an IANA zone name, if the enabled tables have the
181/// name.
182pub fn time_zone_string(name: &str) -> Option<&'static str> {
183    TABLES.iter().find_map(|table| {
184        let index = table.lookup(name)?;
185        table.time_zone_string(index)
186    })
187}
188
189/// Compare two byte slices without a `memcmp` call.
190fn compare(left: &[u8], right: &[u8]) -> Ordering {
191    let shared = left.len().min(right.len());
192    for index in 0..shared {
193        match left[index].cmp(&right[index]) {
194            Ordering::Equal => {}
195            other => return other,
196        }
197    }
198    left.len().cmp(&right.len())
199}
200
201impl TimeZone {
202    /// Parse the POSIX TZ string of an IANA zone name, for example
203    /// `Europe/Paris`. Returns None when the table does not have the name.
204    ///
205    /// Every string in the generated table parses, so the parse error path is
206    /// not reachable here; it is still handled to keep the function total.
207    pub fn from_iana_name(name: &str) -> Option<TimeZone> {
208        TimeZone::parse(time_zone_string(name)?).ok()
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    #[test]
215    fn lookups_follow_the_enabled_regions() {
216        let europe = cfg!(feature = "iana-europe");
217        assert_eq!(super::contains("Europe/Paris"), europe);
218        assert_eq!(super::time_zone_string("Europe/Paris").is_some(), europe);
219        if super::TABLES.is_empty() {
220            assert_eq!(super::zone_count(), 0);
221            assert_eq!(super::zone_name(0), None);
222        }
223    }
224
225    #[test]
226    fn each_table_is_strictly_sorted() {
227        for table in super::TABLES {
228            let mut previous: Option<&str> = None;
229            for index in 0..table.count() {
230                let name = table.name(index).unwrap();
231                if let Some(previous) = previous {
232                    assert!(previous < name, "{previous} !< {name}");
233                }
234                previous = Some(name);
235            }
236        }
237    }
238
239    #[test]
240    fn utc_const_matches_parse() {
241        assert_eq!(
242            crate::TimeZone::utc(),
243            crate::TimeZone::parse("UTC0").unwrap()
244        );
245    }
246}