jiff/tz/db/mod.rs
1use jcore::util::ArrayStr;
2
3use crate::{
4 error::{Error, tz::db::Error as E},
5 tz::TimeZone,
6 util::{sync::Arc, utf8},
7};
8
9mod bundled;
10mod concatenated;
11mod metadata;
12mod zoneinfo;
13
14/// Returns a copy of the global [`TimeZoneDatabase`].
15///
16/// This is the same database used for convenience routines like
17/// [`Timestamp::in_tz`](crate::Timestamp::in_tz) and parsing routines for
18/// [`ZonedDateTime`](crate::ZonedDateTime) that need to do IANA time zone
19/// identifier lookups. Basically, whenever an implicit time zone database is
20/// needed, it is *this* copy of the time zone database that is used.
21///
22/// In feature configurations where a time zone database cannot interact with
23/// the file system (like when `std` is not enabled), this returns a database
24/// where every lookup will fail.
25///
26/// # Example
27///
28/// ```
29/// use jiff::tz;
30///
31/// assert!(tz::db().get("Antarctica/Troll").is_ok());
32/// assert!(tz::db().get("does-not-exist").is_err());
33/// ```
34pub fn db() -> &'static TimeZoneDatabase {
35 // #[cfg(any(not(feature = "std"), miri))]
36 #[cfg(not(feature = "std"))]
37 {
38 // Without `std` there's no lazily initialized global state. But when
39 // the tzdb is bundled into the binary, we can still hand out a usable
40 // database: the bundled database needs no allocation, so it can be
41 // constructed in a `const`. (Without `std`, the zoneinfo and
42 // concatenated databases are both unavailable, so there's nothing to
43 // prefer over the bundle.)
44 //
45 // Ref: https://github.com/BurntSushi/jiff/issues/533
46 #[cfg(any(
47 feature = "tzdb-bundle-always",
48 all(
49 feature = "tzdb-bundle-platform",
50 any(windows, target_family = "wasm"),
51 ),
52 ))]
53 static DB: TimeZoneDatabase = TimeZoneDatabase {
54 inner: Repr::Bundled(bundled::Database::new()),
55 };
56 #[cfg(not(any(
57 feature = "tzdb-bundle-always",
58 all(
59 feature = "tzdb-bundle-platform",
60 any(windows, target_family = "wasm"),
61 ),
62 )))]
63 static DB: TimeZoneDatabase = TimeZoneDatabase::none();
64 &DB
65 }
66 // #[cfg(all(feature = "std", not(miri)))]
67 #[cfg(feature = "std")]
68 {
69 use std::sync::OnceLock;
70
71 static DB: OnceLock<TimeZoneDatabase> = OnceLock::new();
72 DB.get_or_init(|| {
73 let db = TimeZoneDatabase::from_env();
74 debug!("initialized global time zone database: {db:?}");
75 db
76 })
77 }
78}
79
80/// A handle to a [IANA Time Zone Database].
81///
82/// A `TimeZoneDatabase` provides a way to lookup [`TimeZone`]s by their
83/// human readable identifiers, such as `America/Los_Angeles` and
84/// `Europe/Warsaw`.
85///
86/// It is rare to need to create or use this type directly. Routines like zoned
87/// datetime parsing and time zone conversion provide convenience routines for
88/// using an implicit global time zone database by default. This global time
89/// zone database is available via [`jiff::tz::db`](crate::tz::db()`). But
90/// lower level parsing routines such as
91/// [`fmt::temporal::DateTimeParser::parse_zoned_datetime_with`](crate::fmt::temporal::DateTimeParser::parse_zoned_datetime_with)
92/// and
93/// [`civil::DateTime::to_zoned_datetime`](crate::civil::DateTime::to_zoned_datetime)
94/// provide a means to use a custom copy of a `TimeZoneDatabase`.
95///
96/// # Platform behavior
97///
98/// This behavior is subject to change.
99///
100/// On Unix systems, and when the `tzdb-zoneinfo` crate feature is enabled
101/// (which it is by default), Jiff will read the `/usr/share/zoneinfo`
102/// directory for time zone data.
103///
104/// On Windows systems and when the `tzdb-bundle-platform` crate feature is
105/// enabled (which it is by default), _or_ when the `tzdb-bundle-always` crate
106/// feature is enabled, then the `jiff-tzdb` crate will be used to embed the
107/// entire Time Zone Database into the compiled artifact.
108///
109/// On Android systems, and when the `tzdb-concatenated` crate feature is
110/// enabled (which it is by default), Jiff will attempt to read a concatenated
111/// zoneinfo database using the `ANDROID_DATA` or `ANDROID_ROOT` environment
112/// variables.
113///
114/// In general, using `/usr/share/zoneinfo` (or an equivalent) is heavily
115/// preferred in lieu of embedding the database into your compiled artifact.
116/// The reason is because your system copy of the Time Zone Database may be
117/// updated, perhaps a few times a year, and it is better to get seamless
118/// updates through your system rather than needing to wait on a Rust crate
119/// to update and then rebuild your software. The bundling approach should
120/// only be used when there is no plausible alternative. For example, Windows
121/// has no canonical location for a copy of the Time Zone Database. Indeed,
122/// this is why the Cargo configuration of Jiff specifically does not enabled
123/// bundling by default on Unix systems, but does enable it by default on
124/// Windows systems. Of course, if you really do need a copy of the database
125/// bundled, then you can enable the `tzdb-bundle-always` crate feature.
126///
127/// # Cloning
128///
129/// A `TimeZoneDatabase` can be cheaply cloned. It will share a thread safe
130/// cache with other copies of the same `TimeZoneDatabase`.
131///
132/// # Caching
133///
134/// Because looking up a time zone on disk, reading the file into memory
135/// and parsing the time zone transitions out of that file requires
136/// a fair amount of work, a `TimeZoneDatabase` does a fair bit of
137/// caching. This means that the vast majority of calls to, for example,
138/// [`Timestamp::in_tz`](crate::Timestamp::in_tz) don't actually need to hit
139/// disk. It will just find a cached copy of a [`TimeZone`] and return that.
140///
141/// Of course, with caching comes problems of cache invalidation. Invariably,
142/// there are parameters that Jiff uses to manage when the cache should be
143/// invalidated. Jiff tries to emit log messages about this when it happens. If
144/// you find the caching behavior of Jiff to be sub-optimal for your use case,
145/// please create an issue. (The plan is likely to expose some options for
146/// configuring the behavior of a `TimeZoneDatabase`, but I wanted to collect
147/// user feedback first.)
148///
149/// [IANA Time Zone Database]: https://en.wikipedia.org/wiki/Tz_database
150///
151/// # Example: list all available time zones
152///
153/// ```no_run
154/// use jiff::tz;
155///
156/// for tzid in tz::db().available() {
157/// println!("{tzid}");
158/// }
159/// ```
160///
161/// # Example: using multiple time zone databases
162///
163/// Jiff supports opening and using multiple time zone databases by default.
164/// All you need to do is point [`TimeZoneDatabase::from_dir`] to your own
165/// copy of the Time Zone Database, and it will handle the rest.
166///
167/// This example shows how to utilize multiple databases by parsing a datetime
168/// using an older copy of the IANA Time Zone Database. This example leverages
169/// the fact that the 2018 copy of the database preceded Brazil's announcement
170/// that daylight saving time would be abolished. This meant that datetimes
171/// in the future, when parsed with the older copy of the Time Zone Database,
172/// would still follow the old daylight saving time rules. But a mere update of
173/// the database would otherwise change the meaning of the datetime.
174///
175/// This scenario can come up if one stores datetimes in the future. This is
176/// also why the default offset conflict resolution strategy when parsing zoned
177/// datetimes is [`OffsetConflict::Reject`](crate::tz::OffsetConflict::Reject),
178/// which prevents one from silently re-interpreting datetimes to a different
179/// timestamp.
180///
181/// ```no_run
182/// use jiff::{fmt::temporal::DateTimeParser, tz::{self, TimeZoneDatabase}};
183///
184/// static PARSER: DateTimeParser = DateTimeParser::new();
185///
186/// // Open a version of tzdb from before Brazil announced its abolition
187/// // of daylight saving time.
188/// let tzdb2018 = TimeZoneDatabase::from_dir("path/to/tzdb-2018b")?;
189/// // Open the system tzdb.
190/// let tzdb = tz::db();
191///
192/// // Parse the same datetime string with the same parser, but using two
193/// // different versions of tzdb.
194/// let dt = "2020-01-15T12:00[America/Sao_Paulo]";
195/// let zdt2018 = PARSER.parse_zoned_datetime_with(&tzdb2018, dt)?;
196/// let zdt = PARSER.parse_zoned_datetime_with(tzdb, dt)?;
197///
198/// // Before DST was abolished, 2020-01-15 was in DST, which corresponded
199/// // to UTC offset -02. Since DST rules applied to datetimes in the
200/// // future, the 2018 version of tzdb would lead one to interpret
201/// // 2020-01-15 as being in DST.
202/// assert_eq!(zdt2018.offset(), tz::offset(-2));
203/// // But DST was abolished in 2019, which means that 2020-01-15 was no
204/// // no longer in DST. So after a tzdb update, the same datetime as above
205/// // now has a different offset.
206/// assert_eq!(zdt.offset(), tz::offset(-3));
207///
208/// // So if you try to parse a datetime serialized from an older copy of
209/// // tzdb, you'll get an error under the default configuration because
210/// // of `OffsetConflict::Reject`. This would succeed if you parsed it
211/// // using tzdb2018!
212/// assert!(
213/// PARSER.parse_zoned_datetime_with(tzdb, zdt2018.to_string()).is_err()
214/// );
215///
216/// # Ok::<(), Box<dyn std::error::Error>>(())
217/// ```
218#[derive(Clone)]
219pub struct TimeZoneDatabase {
220 inner: Repr,
221}
222
223/// The internal representation of a `TimeZoneDatabase`.
224///
225/// The bundled database is kept out of the `Arc` because it carries no data
226/// of its own (the tzdb is compiled into the binary and any parsed zones are
227/// cached in a global). This lets it be constructed in a `const`, which is
228/// what makes it possible for `db()` to return the bundled database even when
229/// `std` is unavailable (and so there is no lazily initialized global state).
230///
231/// Ref: https://github.com/BurntSushi/jiff/issues/533
232#[derive(Clone)]
233enum Repr {
234 /// A database for which all lookups fail.
235 Empty,
236 /// The bundled database. Needs no allocation, so no `Arc`.
237 Bundled(bundled::Database),
238 /// A database backed by an `Arc` so that clones share its cache.
239 Arc(Arc<Kind>),
240}
241
242#[derive(Debug)]
243// Needed for core-only "dumb" `Arc`.
244#[cfg_attr(not(feature = "alloc"), derive(Clone))]
245enum Kind {
246 ZoneInfo(zoneinfo::Database),
247 Concatenated(concatenated::Database),
248}
249
250impl TimeZoneDatabase {
251 /// Returns a database for which all time zone lookups fail.
252 ///
253 /// # Example
254 ///
255 /// ```
256 /// use jiff::tz::TimeZoneDatabase;
257 ///
258 /// let db = TimeZoneDatabase::none();
259 /// assert_eq!(db.available().count(), 0);
260 /// ```
261 pub const fn none() -> TimeZoneDatabase {
262 TimeZoneDatabase { inner: Repr::Empty }
263 }
264
265 /// Returns a time zone database initialized from the current environment.
266 ///
267 /// This routine never fails, but it may not be able to find a copy of
268 /// your Time Zone Database. When this happens, log messages (with some
269 /// at least at the `WARN` level) will be emitted. They can be viewed by
270 /// installing a [`log`] compatible logger such as [`env_logger`].
271 ///
272 /// Typically, one does not need to call this routine directly. Instead,
273 /// it's done for you as part of [`jiff::tz::db`](crate::tz::db()).
274 /// This does require Jiff's `std` feature to be enabled though. So for
275 /// example, you might use this constructor when the features `alloc`
276 /// and `tzdb-bundle-always` are enabled to get access to a bundled
277 /// copy of the IANA time zone database. (Accessing the system copy at
278 /// `/usr/share/zoneinfo` requires `std`.)
279 ///
280 /// Beware that calling this constructor will create a new _distinct_
281 /// handle from the one returned by `jiff::tz::db` with its own cache.
282 ///
283 /// [`log`]: https://docs.rs/log
284 /// [`env_logger`]: https://docs.rs/env_logger
285 ///
286 /// # Platform behavior
287 ///
288 /// When the `TZDIR` environment variable is set, this will attempt to
289 /// open the Time Zone Database at the directory specified. Otherwise,
290 /// this will search a list of predefined directories for a system
291 /// installation of the Time Zone Database. Typically, it's found at
292 /// `/usr/share/zoneinfo`.
293 ///
294 /// On Windows systems, under the default crate configuration, this will
295 /// return an embedded copy of the Time Zone Database since Windows does
296 /// not have a canonical installation of the Time Zone Database.
297 pub fn from_env() -> TimeZoneDatabase {
298 // On Android, try the concatenated database first, since that's
299 // typically what is used.
300 //
301 // Overall this logic might be sub-optimal. Like, does it really make
302 // sense to check for the zoneinfo or concatenated database on non-Unix
303 // platforms? Probably not to be honest. But these should only be
304 // executed ~once generally, so it doesn't seem like a big deal to try.
305 // And trying makes things a little more flexible I think.
306 #[cfg(not(miri))]
307 {
308 if cfg!(target_os = "android") {
309 let db = concatenated::Database::from_env();
310 if !db.is_definitively_empty() {
311 return TimeZoneDatabase::new(Kind::Concatenated(db));
312 }
313
314 let db = zoneinfo::Database::from_env();
315 if !db.is_definitively_empty() {
316 return TimeZoneDatabase::new(Kind::ZoneInfo(db));
317 }
318 } else {
319 let db = zoneinfo::Database::from_env();
320 if !db.is_definitively_empty() {
321 return TimeZoneDatabase::new(Kind::ZoneInfo(db));
322 }
323
324 let db = concatenated::Database::from_env();
325 if !db.is_definitively_empty() {
326 return TimeZoneDatabase::new(Kind::Concatenated(db));
327 }
328 }
329 }
330
331 let db = bundled::Database::new();
332 if !db.is_definitively_empty() {
333 return TimeZoneDatabase { inner: Repr::Bundled(db) };
334 }
335
336 warn!(
337 "could not find zoneinfo, concatenated tzdata or \
338 bundled time zone database",
339 );
340 TimeZoneDatabase::none()
341 }
342
343 /// Returns a time zone database initialized from the given directory.
344 ///
345 /// Unlike [`TimeZoneDatabase::from_env`], this always attempts to look for
346 /// a copy of the Time Zone Database at the directory given. And if it
347 /// fails to find one at that directory, then an error is returned.
348 ///
349 /// Basically, you should use this when you need to use a _specific_
350 /// copy of the Time Zone Database, and use `TimeZoneDatabase::from_env`
351 /// when you just want Jiff to try and "do the right thing for you."
352 ///
353 /// # Errors
354 ///
355 /// This returns an error if the given directory does not contain a valid
356 /// copy of the Time Zone Database. Generally, this means a directory with
357 /// at least one valid TZif file.
358 #[cfg(feature = "std")]
359 pub fn from_dir<P: AsRef<std::path::Path>>(
360 path: P,
361 ) -> Result<TimeZoneDatabase, Error> {
362 let path = path.as_ref();
363 let db = zoneinfo::Database::from_dir(path)?;
364 if db.is_definitively_empty() {
365 warn!(
366 "could not find zoneinfo data at directory {path}",
367 path = path.display(),
368 );
369 }
370 Ok(TimeZoneDatabase::new(Kind::ZoneInfo(db)))
371 }
372
373 /// Returns a time zone database initialized from a path pointing to a
374 /// concatenated `tzdata` file. This type of format is only known to be
375 /// found on Android environments. The specific format for this file isn't
376 /// defined formally anywhere, but Jiff parses the same format supported
377 /// by the [Android Platform].
378 ///
379 /// Unlike [`TimeZoneDatabase::from_env`], this always attempts to look for
380 /// a copy of the Time Zone Database at the path given. And if it
381 /// fails to find one at that path, then an error is returned.
382 ///
383 /// Basically, you should use this when you need to use a _specific_
384 /// copy of the Time Zone Database in its concatenated format, and use
385 /// `TimeZoneDatabase::from_env` when you just want Jiff to try and "do the
386 /// right thing for you." (`TimeZoneDatabase::from_env` will attempt to
387 /// automatically detect the presence of a system concatenated `tzdata`
388 /// file on Android.)
389 ///
390 /// # Errors
391 ///
392 /// This returns an error if the given path does not contain a valid
393 /// copy of the concatenated Time Zone Database.
394 ///
395 /// [Android Platform]: https://android.googlesource.com/platform/libcore/+/jb-mr2-release/luni/src/main/java/libcore/util/ZoneInfoDB.java
396 #[cfg(feature = "std")]
397 pub fn from_concatenated_path<P: AsRef<std::path::Path>>(
398 path: P,
399 ) -> Result<TimeZoneDatabase, Error> {
400 let path = path.as_ref();
401 let db = concatenated::Database::from_path(path)?;
402 if db.is_definitively_empty() {
403 warn!(
404 "could not find concatenated tzdata in file {path}",
405 path = path.display(),
406 );
407 }
408 Ok(TimeZoneDatabase::new(Kind::Concatenated(db)))
409 }
410
411 /// Returns a time zone database initialized from the bundled copy of
412 /// the [IANA Time Zone Database].
413 ///
414 /// While this API is always available, in order to get a non-empty
415 /// database back, this requires that one of the crate features
416 /// `tzdb-bundle-always` or `tzdb-bundle-platform` is enabled. In the
417 /// latter case, the bundled database is only available on platforms known
418 /// to lack a system copy of the IANA Time Zone Database (i.e., non-Unix
419 /// systems).
420 ///
421 /// This routine is infallible, but it may return a database
422 /// that is definitively empty if the bundled data is not
423 /// available. To query whether the data is empty or not, use
424 /// [`TimeZoneDatabase::is_definitively_empty`].
425 ///
426 /// # Data generation
427 ///
428 /// The data in this crate comes from the [IANA Time Zone Database] "data
429 /// only" distribution. [`jiff-cli`] is used to first compile the release
430 /// into binary TZif data using the `zic` compiler, and secondly, converts
431 /// the binary data into a flattened and de-duplicated representation that
432 /// is embedded into this crate's source code.
433 ///
434 /// The conversion into the TZif binary data uses the following settings:
435 ///
436 /// * The "rearguard" data is used (see below).
437 /// * The binary data itself is compiled using the "slim" format. Which
438 /// effectively means that the TZif data primarily only uses explicit
439 /// time zone transitions for historical data and POSIX time zones for
440 /// current time zone transition rules. This doesn't have any impact
441 /// on the actual results. The reason that there are "slim" and "fat"
442 /// formats is to support legacy applications that can't deal with
443 /// POSIX time zones. For example, `/usr/share/zoneinfo` on my modern
444 /// Archlinux installation (2025-02-27) is in the "fat" format.
445 ///
446 /// The reason that rearguard data is used is a bit more subtle and has
447 /// to do with a difference in how the IANA Time Zone Database treats its
448 /// internal "daylight saving time" flag and what people in the "real
449 /// world" consider "daylight saving time." For example, in the standard
450 /// distribution of the IANA Time Zone Database, `Europe/Dublin` has its
451 /// daylight saving time flag set to _true_ during Winter and set to
452 /// _false_ during Summer. The actual time shifts are the same as, e.g.,
453 /// `Europe/London`, but which one is actually labeled "daylight saving
454 /// time" is not.
455 ///
456 /// The IANA Time Zone Database does this for `Europe/Dublin`, presumably,
457 /// because _legally_, time during the Summer in Ireland is called `Irish
458 /// Standard Time`, and time during the Winter is called `Greenwich Mean
459 /// Time`. These legal names are reversed from what is typically the case,
460 /// where "standard" time is during the Winter and daylight saving time is
461 /// during the Summer. The IANA Time Zone Database implements this tweak in
462 /// legal language via a "negative daylight saving time offset." This is
463 /// somewhat odd, and some consumers of the IANA Time Zone Database cannot
464 /// handle it. Thus, the rearguard format was born for, seemingly, legacy
465 /// programs.
466 ///
467 /// Jiff can handle negative daylight saving time offsets just fine,
468 /// but we use the rearguard format anyway so that the underlying data
469 /// more accurately reflects on-the-ground reality for humans living in
470 /// `Europe/Dublin`. In particular, using the rearguard data enables
471 /// [localization of time zone names] to be done correctly.
472 ///
473 /// [IANA Time Zone Database]: https://en.wikipedia.org/wiki/Tz_database
474 /// [`jiff-cli`]: https://github.com/BurntSushi/jiff/tree/master/crates/jiff-cli
475 /// [localization of time zone names]: https://github.com/BurntSushi/jiff/issues/258
476 pub fn bundled() -> TimeZoneDatabase {
477 let db = bundled::Database::new();
478 if db.is_definitively_empty() {
479 warn!("could not find embedded/bundled zoneinfo");
480 }
481 TimeZoneDatabase { inner: Repr::Bundled(db) }
482 }
483
484 /// Creates a new DB from the internal kind.
485 fn new(kind: Kind) -> TimeZoneDatabase {
486 TimeZoneDatabase { inner: Repr::Arc(Arc::new(kind)) }
487 }
488
489 /// Returns a [`TimeZone`] corresponding to the IANA time zone identifier
490 /// given.
491 ///
492 /// The lookup is performed without regard to ASCII case.
493 ///
494 /// To see a list of all available time zone identifiers for this database,
495 /// use [`TimeZoneDatabase::available`].
496 ///
497 /// It is guaranteed that if the given time zone name is case insensitively
498 /// equivalent to `UTC`, then the time zone returned will be equivalent to
499 /// `TimeZone::UTC`. Similarly for `Etc/Unknown` and `TimeZone::unknown()`.
500 ///
501 /// # Example
502 ///
503 /// ```
504 /// use jiff::tz;
505 ///
506 /// let tz = tz::db().get("america/NEW_YORK")?;
507 /// assert_eq!(tz.iana_name(), Some("America/New_York"));
508 ///
509 /// # Ok::<(), Box<dyn std::error::Error>>(())
510 /// ```
511 pub fn get(&self, name: &str) -> Result<TimeZone, Error> {
512 let found = match self.inner {
513 Repr::Empty => {
514 return Err(Error::from(
515 E::failed_time_zone_no_database_configured(name),
516 ));
517 }
518 Repr::Bundled(ref db) => db.get(name),
519 Repr::Arc(ref kind) => match **kind {
520 Kind::ZoneInfo(ref db) => db.get(name),
521 Kind::Concatenated(ref db) => db.get(name),
522 },
523 };
524 if let Some(tz) = found {
525 trace!("found time zone `{name}` in {db:?}", db = self);
526 return Ok(tz);
527 }
528 Err(Error::from(E::failed_time_zone(name)))
529 }
530
531 /// Returns a list of all available time zone identifiers from this
532 /// database.
533 ///
534 /// Note that time zone identifiers are more of a machine readable
535 /// abstraction and not an end user level abstraction. Still, users
536 /// comfortable with configuring their system's default time zone through
537 /// IANA time zone identifiers are probably comfortable interacting with
538 /// the identifiers returned here.
539 ///
540 /// # Example
541 ///
542 /// ```no_run
543 /// use jiff::tz;
544 ///
545 /// for tzid in tz::db().available() {
546 /// println!("{tzid}");
547 /// }
548 /// ```
549 pub fn available<'d>(&'d self) -> TimeZoneNameIter<'d> {
550 match self.inner {
551 Repr::Empty => TimeZoneNameIter::empty(),
552 Repr::Bundled(ref db) => db.available(),
553 Repr::Arc(ref kind) => match **kind {
554 Kind::ZoneInfo(ref db) => db.available(),
555 Kind::Concatenated(ref db) => db.available(),
556 },
557 }
558 }
559
560 /// Resets the internal cache of this database.
561 ///
562 /// Subsequent interactions with this database will need to re-read time
563 /// zone data from disk.
564 ///
565 /// It might be useful to call this if you know the time zone database
566 /// has changed on disk and want to force Jiff to re-load it immediately
567 /// without spawning a new process or waiting for Jiff's internal cache
568 /// invalidation heuristics to kick in.
569 pub fn reset(&self) {
570 match self.inner {
571 Repr::Empty => {}
572 Repr::Bundled(ref db) => db.reset(),
573 Repr::Arc(ref kind) => match **kind {
574 Kind::ZoneInfo(ref db) => db.reset(),
575 Kind::Concatenated(ref db) => db.reset(),
576 },
577 }
578 }
579
580 /// Returns true if it is known that this time zone database is empty.
581 ///
582 /// When this returns true, it is guaranteed that all
583 /// [`TimeZoneDatabase::get`] calls will fail, and that
584 /// [`TimeZoneDatabase::available`] will always return an empty iterator.
585 ///
586 /// Note that if this returns false, it is still possible for this database
587 /// to be empty.
588 ///
589 /// # Example
590 ///
591 /// ```
592 /// use jiff::tz::TimeZoneDatabase;
593 ///
594 /// let db = TimeZoneDatabase::none();
595 /// assert!(db.is_definitively_empty());
596 /// ```
597 pub fn is_definitively_empty(&self) -> bool {
598 match self.inner {
599 Repr::Empty => true,
600 Repr::Bundled(ref db) => db.is_definitively_empty(),
601 Repr::Arc(ref kind) => match **kind {
602 Kind::ZoneInfo(ref db) => db.is_definitively_empty(),
603 Kind::Concatenated(ref db) => db.is_definitively_empty(),
604 },
605 }
606 }
607}
608
609impl core::fmt::Debug for TimeZoneDatabase {
610 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
611 f.write_str("TimeZoneDatabase(")?;
612 match self.inner {
613 Repr::Empty => return f.write_str("unavailable)"),
614 Repr::Bundled(ref db) => core::fmt::Debug::fmt(db, f)?,
615 Repr::Arc(ref kind) => match **kind {
616 Kind::ZoneInfo(ref db) => core::fmt::Debug::fmt(db, f)?,
617 Kind::Concatenated(ref db) => core::fmt::Debug::fmt(db, f)?,
618 },
619 }
620 f.write_str(")")
621 }
622}
623
624#[cfg(feature = "defmt")]
625impl defmt::Format for TimeZoneDatabase {
626 fn format(&self, f: defmt::Formatter) {
627 // `Kind` doesn't implement `defmt::Format`, so we only emit the type
628 // name. On embedded targets the database is usually bundled or unused,
629 // so the internal backend probably isn't meaningful to log either way.
630 defmt::write!(f, "TimeZoneDatabase(unavailable)");
631 }
632}
633
634/// An iterator over the time zone identifiers in a [`TimeZoneDatabase`].
635///
636/// This iterator is created by [`TimeZoneDatabase::available`].
637///
638/// There are no guarantees about the order in which this iterator yields
639/// time zone identifiers.
640///
641/// The lifetime parameter corresponds to the lifetime of the
642/// `TimeZoneDatabase` from which this iterator was created.
643#[derive(Clone, Debug)]
644#[cfg_attr(feature = "defmt", derive(defmt::Format))]
645pub struct TimeZoneNameIter<'d> {
646 #[cfg(feature = "alloc")]
647 it: alloc::vec::IntoIter<TimeZoneName<'d>>,
648 #[cfg(not(feature = "alloc"))]
649 it: core::iter::Empty<TimeZoneName<'d>>,
650}
651
652impl<'d> TimeZoneNameIter<'d> {
653 /// Creates a time zone name iterator that never yields any elements.
654 fn empty() -> TimeZoneNameIter<'d> {
655 #[cfg(feature = "alloc")]
656 {
657 TimeZoneNameIter { it: alloc::vec::Vec::new().into_iter() }
658 }
659 #[cfg(not(feature = "alloc"))]
660 {
661 TimeZoneNameIter { it: core::iter::empty() }
662 }
663 }
664
665 /// Creates a time zone name iterator that yields the elements from the
666 /// iterator given. (They are collected into a `Vec`.)
667 #[cfg(feature = "alloc")]
668 fn from_iter(
669 it: impl Iterator<Item = impl Into<alloc::string::String>>,
670 ) -> TimeZoneNameIter<'d> {
671 let names: alloc::vec::Vec<TimeZoneName<'d>> =
672 it.map(|name| TimeZoneName::new(name.into())).collect();
673 TimeZoneNameIter { it: names.into_iter() }
674 }
675}
676
677impl<'d> Iterator for TimeZoneNameIter<'d> {
678 type Item = TimeZoneName<'d>;
679
680 fn next(&mut self) -> Option<TimeZoneName<'d>> {
681 self.it.next()
682 }
683}
684
685/// A name for a time zone yield by the [`TimeZoneNameIter`] iterator.
686///
687/// The iterator is created by [`TimeZoneDatabase::available`].
688///
689/// The lifetime parameter corresponds to the lifetime of the
690/// `TimeZoneDatabase` from which this name was created.
691#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
692#[cfg_attr(feature = "defmt", derive(defmt::Format))]
693pub struct TimeZoneName<'d> {
694 /// The lifetime of the tzdb.
695 ///
696 /// We don't currently use this, but it could be quite useful if we ever
697 /// adopt a "compile time" tzdb like what `chrono-tz` has. Then we could
698 /// return strings directly from the embedded data. Or perhaps a "compile
699 /// time" TZif or some such.
700 lifetime: core::marker::PhantomData<&'d str>,
701 #[cfg(feature = "alloc")]
702 #[cfg_attr(feature = "defmt", defmt(Debug2Format))]
703 name: alloc::string::String,
704 #[cfg(not(feature = "alloc"))]
705 name: core::convert::Infallible,
706}
707
708impl<'d> TimeZoneName<'d> {
709 /// Returns a new time zone name from the string given.
710 ///
711 /// The lifetime returned is inferred according to the caller's context.
712 #[cfg(feature = "alloc")]
713 fn new(name: alloc::string::String) -> TimeZoneName<'d> {
714 TimeZoneName { lifetime: core::marker::PhantomData, name }
715 }
716
717 /// Returns this time zone name as a borrowed string.
718 ///
719 /// Note that the lifetime of the string returned is tied to `self`,
720 /// which may be shorter than the lifetime `'d` of the originating
721 /// `TimeZoneDatabase`.
722 #[inline]
723 pub fn as_str<'a>(&'a self) -> &'a str {
724 #[cfg(feature = "alloc")]
725 {
726 self.name.as_str()
727 }
728 #[cfg(not(feature = "alloc"))]
729 {
730 // Can never be reached because `TimeZoneName` cannot currently
731 // be constructed in core-only environments.
732 unreachable!()
733 }
734 }
735}
736
737impl<'d> core::fmt::Display for TimeZoneName<'d> {
738 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
739 f.write_str(self.as_str())
740 }
741}
742
743/// The geographical location corresponding to a primary time zone identifier.
744///
745/// This can be retrieved for a time zone via [`TimeZone::location`].
746///
747/// # Example
748///
749/// ```
750/// use jiff::tz::TimeZone;
751/// # if TimeZone::get("Asia/Calcutta").is_err() { return Ok(()) };
752///
753/// let tz = TimeZone::get("Europe/Copenhagen")?;
754/// let loc = tz.location().unwrap();
755/// assert_eq!(loc.country(), "DK");
756///
757/// let tz = TimeZone::get("EuRoPe/BeRlIn")?;
758/// let loc = tz.location().unwrap();
759/// assert_eq!(loc.country(), "DE");
760///
761/// let tz = TimeZone::get("asia/calcutta")?;
762/// let loc = tz.location().unwrap();
763/// assert_eq!(loc.country(), "IN");
764///
765/// # Ok::<(), Box<dyn std::error::Error>>(())
766/// ```
767#[derive(Clone, Copy, Debug)]
768pub struct TimeZoneLocation {
769 /// The ISO 3166 code corresponding to the country for the primary time
770 /// zone identifier.
771 country: ArrayStr<2>,
772 /// The latitude coordinate.
773 latitude: f64,
774 /// The longitude coordinate.
775 longitude: f64,
776}
777
778impl TimeZoneLocation {
779 /// Returns the ISO 3166 country code for the corresponding time zone.
780 ///
781 /// # Example
782 ///
783 /// ```
784 /// use jiff::tz::TimeZone;
785 /// # if TimeZone::get("Asia/Calcutta").is_err() { return Ok(()) };
786 ///
787 /// let tz = TimeZone::get("Asia/Calcutta")?;
788 /// let loc = tz.location().unwrap();
789 /// assert_eq!(loc.country(), "IN");
790 ///
791 /// # Ok::<(), Box<dyn std::error::Error>>(())
792 /// ```
793 pub const fn country(&self) -> &str {
794 self.country.as_str()
795 }
796
797 /// Returns the latitude coordinate for the corresponding time zone.
798 ///
799 /// # Example
800 ///
801 /// ```
802 /// use jiff::tz::TimeZone;
803 /// # if TimeZone::get("Asia/Calcutta").is_err() { return Ok(()) };
804 ///
805 /// let tz = TimeZone::get("Asia/Calcutta")?;
806 /// let loc = tz.location().unwrap();
807 /// assert_eq!(loc.latitude(), 22.533333333333335);
808 ///
809 /// # Ok::<(), Box<dyn std::error::Error>>(())
810 /// ```
811 pub const fn latitude(&self) -> f64 {
812 self.latitude
813 }
814
815 /// Returns the longitude coordinate for the corresponding time zone.
816 ///
817 /// # Example
818 ///
819 /// ```
820 /// use jiff::tz::TimeZone;
821 /// # if TimeZone::get("Asia/Calcutta").is_err() { return Ok(()) };
822 ///
823 /// let tz = TimeZone::get("Asia/Calcutta")?;
824 /// let loc = tz.location().unwrap();
825 /// assert_eq!(loc.longitude(), 88.36666666666666);
826 ///
827 /// # Ok::<(), Box<dyn std::error::Error>>(())
828 /// ```
829 pub const fn longitude(&self) -> f64 {
830 self.longitude
831 }
832}
833
834pub(crate) fn find_primary_iana_name(iana_name: &str) -> Option<&'static str> {
835 let index = metadata::TIME_ZONE_PRIMARY_IDENTIFIER
836 .binary_search_by(|&(key, _)| key.cmp(iana_name))
837 .ok()?;
838 let primary = metadata::TIME_ZONE_PRIMARY_IDENTIFIER[index].1;
839 Some(primary)
840}
841
842pub(crate) fn find_tz_location(iana_name: &str) -> Option<TimeZoneLocation> {
843 let index = metadata::TIME_ZONE_PRIMARY_IDENTIFIER
844 .binary_search_by(|&(key, _)| key.cmp(iana_name))
845 .ok()?;
846 let primary = metadata::TIME_ZONE_PRIMARY_IDENTIFIER[index].1;
847 let location = metadata::TIME_ZONE_METADATA
848 .binary_search_by(|&(key, _)| key.cmp(primary))
849 .ok()
850 .map(|index| metadata::TIME_ZONE_METADATA[index].1);
851 location
852}
853
854/// Checks if `name` is a "special" time zone and returns one if so.
855///
856/// This is limited to special constants that should have consistent values
857/// across time zone database implementations. For example, `UTC`.
858fn special_time_zone(name: &str) -> Option<TimeZone> {
859 if utf8::cmp_ignore_ascii_case("utc", name).is_eq() {
860 return Some(TimeZone::UTC);
861 }
862 if utf8::cmp_ignore_ascii_case("etc/unknown", name).is_eq() {
863 return Some(TimeZone::unknown());
864 }
865 None
866}
867
868#[cfg(test)]
869mod tests {
870 use super::*;
871
872 /// Tests that the global database returns the bundled tzdb when the bundle
873 /// is enabled but neither the zoneinfo nor concatenated databases are.
874 ///
875 /// This configuration doesn't have `std` (since both `tzdb-zoneinfo` and
876 /// `tzdb-concatenated` imply it), and so without special handling `db()`
877 /// used to return an empty database despite the tzdb being compiled in.
878 ///
879 /// Regression test for: https://github.com/BurntSushi/jiff/issues/533
880 #[cfg(all(
881 feature = "tzdb-bundle-always",
882 not(feature = "tzdb-zoneinfo"),
883 not(feature = "tzdb-concatenated"),
884 ))]
885 #[test]
886 fn bundled_db_when_only_bundle_enabled() {
887 let db = db();
888 assert!(!db.is_definitively_empty());
889 assert!(db.get("America/New_York").is_ok());
890 // The convenience APIs route through the global `db()`, so this is
891 // the symptom originally reported in #533.
892 assert!(
893 crate::civil::date(2024, 7, 4)
894 .at(12, 0, 0, 0)
895 .in_tz("America/New_York")
896 .is_ok()
897 );
898 }
899
900 /// This tests that the size of a time zone database is kept small.
901 ///
902 /// It's two words because the bundled database is stored outside the
903 /// `Arc` (so it can be constructed in a `const`, see `db()` and #533),
904 /// which means the representation needs a tag to distinguish it from the
905 /// empty and `Arc`-backed variants.
906 ///
907 /// I think it would probably be okay to make this bigger if we had a
908 /// good reason to, but it seems sensible to put a road-block to avoid
909 /// accidentally increasing its size.
910 #[test]
911 fn time_zone_database_size() {
912 #[cfg(feature = "alloc")]
913 {
914 let word = core::mem::size_of::<usize>();
915 assert_eq!(2 * word, core::mem::size_of::<TimeZoneDatabase>());
916 }
917 // A `TimeZoneDatabase` in core-only is vapid.
918 #[cfg(not(feature = "alloc"))]
919 {
920 assert_eq!(1, core::mem::size_of::<TimeZoneDatabase>());
921 }
922 }
923
924 /// Time zone databases should always return `TimeZone::UTC` if the time
925 /// zone is known to be UTC.
926 ///
927 /// Regression test for: https://github.com/BurntSushi/jiff/issues/346
928 #[test]
929 fn bundled_returns_utc_constant() {
930 let db = TimeZoneDatabase::bundled();
931 if db.is_definitively_empty() {
932 return;
933 }
934 assert_eq!(db.get("UTC").unwrap(), TimeZone::UTC);
935 assert_eq!(db.get("utc").unwrap(), TimeZone::UTC);
936 assert_eq!(db.get("uTc").unwrap(), TimeZone::UTC);
937 assert_eq!(db.get("UtC").unwrap(), TimeZone::UTC);
938
939 // Also, similarly, for `Etc/Unknown`.
940 assert_eq!(db.get("Etc/Unknown").unwrap(), TimeZone::unknown());
941 assert_eq!(db.get("etc/UNKNOWN").unwrap(), TimeZone::unknown());
942 }
943
944 /// Time zone databases should always return `TimeZone::UTC` if the time
945 /// zone is known to be UTC.
946 ///
947 /// Regression test for: https://github.com/BurntSushi/jiff/issues/346
948 #[cfg(all(feature = "std", not(miri)))]
949 #[test]
950 fn zoneinfo_returns_utc_constant() {
951 let Ok(db) = TimeZoneDatabase::from_dir("/usr/share/zoneinfo") else {
952 return;
953 };
954 if db.is_definitively_empty() {
955 return;
956 }
957 assert_eq!(db.get("UTC").unwrap(), TimeZone::UTC);
958 assert_eq!(db.get("utc").unwrap(), TimeZone::UTC);
959 assert_eq!(db.get("uTc").unwrap(), TimeZone::UTC);
960 assert_eq!(db.get("UtC").unwrap(), TimeZone::UTC);
961
962 // Also, similarly, for `Etc/Unknown`.
963 assert_eq!(db.get("Etc/Unknown").unwrap(), TimeZone::unknown());
964 assert_eq!(db.get("etc/UNKNOWN").unwrap(), TimeZone::unknown());
965 }
966
967 /// This checks that our zoneinfo database never returns a time zone
968 /// identifier that isn't presumed to correspond to a real and valid
969 /// TZif file in the tzdb.
970 ///
971 /// This test was added when I optimized the initialized of Jiff's zoneinfo
972 /// database. Originally, it did a directory traversal along with a 4-byte
973 /// read of every file in the directory to check if the file was TZif or
974 /// something else. This turned out to be quite slow on slow file systems.
975 /// I rejiggered it so that the reads of every file were removed. But this
976 /// meant we could have loaded a name from a file that wasn't TZif into
977 /// our in-memory cache.
978 ///
979 /// For doing a single time zone lookup, this isn't a problem, since we
980 /// have to read the TZif data anyway. If it's invalid, then we just
981 /// return `None` and log a warning. No big deal.
982 ///
983 /// But for the `TimeZoneDatabase::available()` API, we were previously
984 /// just returning a list of names under the presumption that every such
985 /// name corresponds to a valid TZif file. This test checks that we don't
986 /// emit junk. (Which was in practice accomplished to moving the 4-byte
987 /// read to when we call `TimeZoneDatabase::available()`.)
988 ///
989 /// Ref: https://github.com/BurntSushi/jiff/issues/366
990 #[cfg(all(feature = "std", not(miri)))]
991 #[test]
992 fn zoneinfo_available_returns_only_tzif() {
993 use alloc::{
994 collections::BTreeSet,
995 string::{String, ToString},
996 };
997
998 let Ok(db) = TimeZoneDatabase::from_dir("/usr/share/zoneinfo") else {
999 return;
1000 };
1001 if db.is_definitively_empty() {
1002 return;
1003 }
1004 let names: BTreeSet<String> =
1005 db.available().map(|n| n.as_str().to_string()).collect();
1006 // Not all zoneinfo directories are created equal. Some have more or
1007 // less junk than others. So just try a few things.
1008 let should_be_absent = [
1009 "leapseconds",
1010 "tzdata.zi",
1011 "leap-seconds.list",
1012 "SECURITY",
1013 "zone1970.tab",
1014 "iso3166.tab",
1015 "zonenow.tab",
1016 "zone.tab",
1017 ];
1018 for name in should_be_absent {
1019 assert!(
1020 !names.contains(name),
1021 "found `{name}` in time zone list, but it shouldn't be there",
1022 );
1023 }
1024 }
1025}