This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-11482-1b42833a2105efdbb757108c7d15233aa35e9bf5 in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit 1f1f8595c29a7fc284e2101a008d0f730f392836 Author: Andy Grove <[email protected]> AuthorDate: Fri Nov 20 19:39:09 2026 +0000 feat: add `jiff` feature to resolve named timezones (#11482) # Which issue does this PR close? - Part of #9183. - Motivated by apache/datafusion-comet#6816. # Rationale for this change chrono-tz precomputes each zone's transitions up to 2099 and keeps the last offset for every later instant. jiff applies the zone's POSIX TZ rule to any instant, as `java.time` and libc do. So local `2300-07-01 12:00:00` in `America/Los_Angeles` is PDT (UTC-7) in Spark and jiff but PST (UTC-8) through `arrow_array::timezone::Tz` today, and `Australia/Sydney` stays on daylight time all year from 2100. As suggested on #9183, this adds jiff alongside chrono-tz as an opt-in feature, so downstream projects can try it before chrono-tz is dropped. Only the engine behind `Tz` changes. `Tz` still implements chrono's `TimeZone`, is still `Copy`, and accepts the same names with the same `Display`, `Debug` and error output. # What changes are included in this PR? - `arrow-array` gets a `jiff` feature, forwarded by `arrow`, using `jiff` 1.0 and `jiff-tzdb` 1.0. If both `chrono-tz` and `jiff` are enabled, `jiff` is used. Because Cargo unifies features, enabling `jiff` anywhere in a build changes named timezones for every crate in it. - Zones come only from the database compiled into `jiff-tzdb`, never the host's zoneinfo, so results are deterministic as with chrono-tz. Names must match exactly, as with chrono-tz, and `Factory` is rejected, so both features accept the same set. - `Tz` holds a `'static` reference into a table with one lazily resolved slot per bundled name. Memory is bounded by the database and lookups take no lock. - Gaps, folds, `offset_from_local_date` and `GapInfo` behave as with chrono-tz. Instants outside jiff's years -9999 to 9999 take the nearest covered offset, because chrono's `offset_from_utc_datetime` cannot fail. - New `timezone::tzdb_version()` reports the bundled IANA release. chrono-tz 0.10.4 bundles 2025b and jiff-tzdb 1.0.0 bundles 2026f, so the engines also differ before 2100 wherever the database changed. - CI tests `arrow`, `arrow-cast`, `arrow-csv` and `arrow-json` with `jiff`, checks `arrow-array` with only `jiff`, builds wasm32 with `jiff`, and tests and lints `arrow-array` with `chrono-tz` alone, since `--all-features` now selects jiff. # Are these changes tested? - New unit tests cover DST transitions from UTC and from local time, gaps and folds, every bundled name, rejected names, daylight saving in 2100, 2300 and 9999 in both hemispheres, gaps, folds and `GapInfo` after 2099, and clamping at both ends of jiff's range. - Existing tests gated on `chrono-tz`, including the `arrow` integration tests and the `GapInfo` tests, now also run with `jiff`. - With both features enabled, tests compare the engines directly: names, UTC and local offsets, and gaps, weekly from 1900 to 2099 and on each side of every transition. Zones that differ only because of the tzdb releases are listed, and a failure prints both releases. ## Benchmarks `arrow/benches/named_timezone.rs` is new. It covers parsing, offset lookups from UTC and local time, `date_part(Hour)` and a cast to string, over three ranges. Before 2038 both engines read a transition table. From 2038 to 2100 jiff evaluates the POSIX rule while chrono-tz still reads its table, with the same results. After 2100 the results differ. Results on an AMD Ryzen 9 7950X3D, pinned to one core, comparing `--features chrono-tz,jiff` against `--features chrono-tz`: | | Before 2038, LA and London | Before 2038, UTC and Tokyo | After 2038, LA and London | |---|---|---|---| | offset lookups | 7% to 17% faster | 8% to 55% faster | 1.9x to 2.4x slower | | `date_part(Hour)` | within 1% | 9% to 15% faster | 55% to 66% slower | | cast to string | 9% to 10% slower | 2% to 4% faster | 21% to 26% slower | Parsing a name takes 7 to 8 ns, down from 12 to 14 ns. Zones without daylight saving are unaffected by the range. The cast is slower before 2038 even though its lookup is faster. Shrinking `Tz` to 8 bytes did not help, and neither did aligning every function to 64 bytes. A profile puts the extra time in chrono's `write_rfc3339`, which runs the same code with either engine, and the cause is not yet known. <details> <summary>Full results (median time per iteration)</summary> | benchmark | chrono-tz | jiff | change | |---|---|---|---| | cast_timestamp_to_utf8/128K/1970_to_2038/America/Los_Angeles | 11.77 ms | 12.89 ms | +9% | | cast_timestamp_to_utf8/128K/1970_to_2038/Asia/Tokyo | 11.02 ms | 10.60 ms | -4% | | cast_timestamp_to_utf8/128K/1970_to_2038/Europe/London | 11.36 ms | 12.55 ms | +10% | | cast_timestamp_to_utf8/128K/1970_to_2038/UTC | 10.15 ms | 9.91 ms | -2% | | cast_timestamp_to_utf8/128K/2038_to_2100/America/Los_Angeles | 11.89 ms | 14.52 ms | +22% | | cast_timestamp_to_utf8/128K/2038_to_2100/Asia/Tokyo | 11.09 ms | 10.61 ms | -4% | | cast_timestamp_to_utf8/128K/2038_to_2100/Europe/London | 11.45 ms | 14.33 ms | +25% | | cast_timestamp_to_utf8/128K/2038_to_2100/UTC | 10.22 ms | 9.86 ms | -4% | | cast_timestamp_to_utf8/128K/2100_to_2300/America/Los_Angeles | 12.03 ms | 14.56 ms | +21% | | cast_timestamp_to_utf8/128K/2100_to_2300/Asia/Tokyo | 11.11 ms | 10.60 ms | -5% | | cast_timestamp_to_utf8/128K/2100_to_2300/Europe/London | 11.29 ms | 14.29 ms | +26% | | cast_timestamp_to_utf8/128K/2100_to_2300/UTC | 10.06 ms | 9.88 ms | -2% | | date_part_hour/1M/1970_to_2038/America/Los_Angeles | 29.61 ms | 29.77 ms | +1% | | date_part_hour/1M/1970_to_2038/Asia/Tokyo | 24.81 ms | 22.69 ms | -9% | | date_part_hour/1M/1970_to_2038/Europe/London | 29.66 ms | 29.61 ms | -0% | | date_part_hour/1M/1970_to_2038/UTC | 22.81 ms | 19.50 ms | -15% | | date_part_hour/1M/2038_to_2100/America/Los_Angeles | 30.34 ms | 49.85 ms | +64% | | date_part_hour/1M/2038_to_2100/Asia/Tokyo | 24.89 ms | 22.64 ms | -9% | | date_part_hour/1M/2038_to_2100/Europe/London | 30.31 ms | 50.34 ms | +66% | | date_part_hour/1M/2038_to_2100/UTC | 22.75 ms | 19.47 ms | -14% | | date_part_hour/1M/2100_to_2300/America/Los_Angeles | 32.24 ms | 49.84 ms | +55% | | date_part_hour/1M/2100_to_2300/Asia/Tokyo | 24.75 ms | 22.65 ms | -8% | | date_part_hour/1M/2100_to_2300/Europe/London | 31.80 ms | 50.64 ms | +59% | | date_part_hour/1M/2100_to_2300/UTC | 22.81 ms | 19.50 ms | -15% | | tz_offset_from_local_datetime/1970_to_2038/America/Los_Angeles | 154.25 µs | 142.72 µs | -7% | | tz_offset_from_local_datetime/1970_to_2038/Asia/Tokyo | 130.27 µs | 120.38 µs | -8% | | tz_offset_from_local_datetime/1970_to_2038/Europe/London | 156.78 µs | 143.35 µs | -9% | | tz_offset_from_local_datetime/1970_to_2038/UTC | 136.35 µs | 64.63 µs | -53% | | tz_offset_from_local_datetime/2038_to_2100/America/Los_Angeles | 157.89 µs | 383.09 µs | +143% | | tz_offset_from_local_datetime/2038_to_2100/Asia/Tokyo | 130.43 µs | 119.94 µs | -8% | | tz_offset_from_local_datetime/2038_to_2100/Europe/London | 160.83 µs | 382.98 µs | +138% | | tz_offset_from_local_datetime/2038_to_2100/UTC | 136.29 µs | 64.63 µs | -53% | | tz_offset_from_local_datetime/2100_to_2300/America/Los_Angeles | 168.53 µs | 386.77 µs | +129% | | tz_offset_from_local_datetime/2100_to_2300/Asia/Tokyo | 130.32 µs | 120.73 µs | -7% | | tz_offset_from_local_datetime/2100_to_2300/Europe/London | 167.62 µs | 385.93 µs | +130% | | tz_offset_from_local_datetime/2100_to_2300/UTC | 136.34 µs | 64.63 µs | -53% | | tz_offset_from_utc_datetime/1970_to_2038/America/Los_Angeles | 106.60 µs | 89.01 µs | -17% | | tz_offset_from_utc_datetime/1970_to_2038/Asia/Tokyo | 78.06 µs | 53.25 µs | -32% | | tz_offset_from_utc_datetime/1970_to_2038/Europe/London | 108.35 µs | 89.52 µs | -17% | | tz_offset_from_utc_datetime/1970_to_2038/UTC | 67.53 µs | 30.25 µs | -55% | | tz_offset_from_utc_datetime/2038_to_2100/America/Los_Angeles | 110.76 µs | 238.38 µs | +115% | | tz_offset_from_utc_datetime/2038_to_2100/Asia/Tokyo | 78.11 µs | 53.08 µs | -32% | | tz_offset_from_utc_datetime/2038_to_2100/Europe/London | 113.60 µs | 244.64 µs | +115% | | tz_offset_from_utc_datetime/2038_to_2100/UTC | 67.47 µs | 30.23 µs | -55% | | tz_offset_from_utc_datetime/2100_to_2300/America/Los_Angeles | 124.92 µs | 240.12 µs | +92% | | tz_offset_from_utc_datetime/2100_to_2300/Asia/Tokyo | 78.06 µs | 53.15 µs | -32% | | tz_offset_from_utc_datetime/2100_to_2300/Europe/London | 125.06 µs | 245.87 µs | +97% | | tz_offset_from_utc_datetime/2100_to_2300/UTC | 67.47 µs | 30.19 µs | -55% | | tz_parse/America/Los_Angeles | 14.00 ns | 8.10 ns | -42% | | tz_parse/Asia/Tokyo | 12.35 ns | 7.38 ns | -40% | | tz_parse/Europe/London | 12.83 ns | 7.41 ns | -42% | | tz_parse/UTC | 11.93 ns | 7.52 ns | -37% | Offset lookup rows are for 8192 instants per iteration. </details> # Are there any significant user-facing changes? No. The feature is opt-in, and `timezone::tzdb_version()` is the only new public item. Follow-ups, before jiff could become the default in a major release: - Remove the post-2038 cost in DST zones, for example with a per-zone transition table built in arrow up to a later horizon, as prototyped in review. - Find the cause of the slower cast before 2038. # AI usage disclosure The code, tests, benchmarks and this description were written with an AI assistant (Claude Code). --- .github/workflows/arrow.yml | 18 +- Cargo.lock | 53 +- arrow-array/Cargo.toml | 6 + arrow-array/src/array/primitive_array.rs | 6 +- arrow-array/src/timezone.rs | 913 +++++++++++++++++++++++++++---- arrow-array/src/types.rs | 4 +- arrow-cast/src/parse.rs | 2 +- arrow-schema/src/datatype.rs | 5 +- arrow/Cargo.toml | 7 + arrow/README.md | 1 + arrow/benches/named_timezone.rs | 118 ++++ 11 files changed, 1026 insertions(+), 107 deletions(-) diff --git a/.github/workflows/arrow.yml b/.github/workflows/arrow.yml index f239689f1e..52526fb9d5 100644 --- a/.github/workflows/arrow.yml +++ b/.github/workflows/arrow.yml @@ -37,6 +37,8 @@ jobs: cargo test -p arrow-array --all-features # Disable feature `force_validate` cargo test -p arrow-array --features=ffi + # `jiff` takes precedence over `chrono-tz`, so test `chrono-tz` on its own + cargo test -p arrow-array --features=chrono-tz - name: Test arrow-cmp run: cargo test -p arrow-cmp --all-features - name: Test arrow-select @@ -49,6 +51,11 @@ jobs: run: cargo test -p arrow-csv --all-features - name: Test arrow-json run: cargo test -p arrow-json --all-features + - name: Test arrow-cast, arrow-csv and arrow-json with jiff + run: | + cargo test -p arrow-cast --all-features --features arrow-array/jiff + cargo test -p arrow-csv --all-features --features arrow-array/jiff + cargo test -p arrow-json --all-features --features arrow-array/jiff - name: Test arrow-avro run: cargo test -p arrow-avro --all-features - name: Test arrow-string @@ -65,6 +72,8 @@ jobs: run: cargo test -p arrow - name: Test arrow except pyarrow run: cargo test -p arrow --features=force_validate,prettyprint,ipc_compression,ffi,chrono-tz + - name: Test arrow with jiff + run: cargo test -p arrow --features=force_validate,prettyprint,ipc_compression,ffi,chrono-tz,jiff - name: Run examples run: | # Test arrow examples @@ -150,6 +159,8 @@ jobs: run: cargo check -p arrow --no-default-features --all-targets --features ffi - name: Check compilation --no-default-features --all-targets --features chrono-tz run: cargo check -p arrow --no-default-features --all-targets --features chrono-tz + - name: Check compilation --no-default-features --all-targets --features jiff + run: cargo check -p arrow --no-default-features --all-targets --features jiff # test the arrow crate builds against wasm32 in nightly rust @@ -170,7 +181,7 @@ jobs: rustup target add wasm32-unknown-unknown rustup target add wasm32-wasip1 - name: Build wasm32-unknown-unknown - run: cargo build -p arrow --no-default-features --features=json,csv,ipc,ffi --target wasm32-unknown-unknown + run: cargo build -p arrow --no-default-features --features=json,csv,ipc,ffi,jiff --target wasm32-unknown-unknown - name: Build wasm32-wasip1 run: cargo build -p arrow --no-default-features --features=json,csv,ipc,ffi --target wasm32-wasip1 @@ -194,7 +205,10 @@ jobs: - name: Clippy arrow-schema run: cargo clippy -p arrow-schema --all-targets --all-features -- -D warnings - name: Clippy arrow-array - run: cargo clippy -p arrow-array --all-targets --all-features -- -D warnings + run: | + cargo clippy -p arrow-array --all-targets --all-features -- -D warnings + # `jiff` takes precedence over `chrono-tz`, so lint `chrono-tz` on its own + cargo clippy -p arrow-array --all-targets --features chrono-tz -- -D warnings - name: Clippy arrow-cmp run: cargo clippy -p arrow-cmp --all-targets --all-features -- -D warnings - name: Clippy arrow-select diff --git a/Cargo.lock b/Cargo.lock index c9404ebb36..6bad500e7a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -229,6 +229,8 @@ dependencies = [ "futures", "half", "hashbrown 0.17.1", + "jiff 1.0.0", + "jiff-tzdb 1.0.0", "libc", "num-complex", "num-integer", @@ -1931,8 +1933,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "668b7183bd07af9a4885f5c35b0cc5c83c4607a913c16b7e17291832910d2dcc" dependencies = [ "defmt", - "jiff-core", - "jiff-static", + "jiff-core 0.1.0", + "jiff-static 0.2.35", "jiff-tzdb-platform", "js-sys", "log", @@ -1943,6 +1945,20 @@ dependencies = [ "windows-link", ] +[[package]] +name = "jiff" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cc767b5763de45e810109520123bb2829a653f3a7ed9be40b2bc4f81158f595" +dependencies = [ + "jiff-core 1.0.0", + "jiff-static 1.0.0", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + [[package]] name = "jiff-core" version = "0.1.0" @@ -1952,31 +1968,58 @@ dependencies = [ "defmt", ] +[[package]] +name = "jiff-core" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "894f7ac42105f584100691b3bf6e6b92dd12fcfa225f6c397f95c8a94b47b68f" +dependencies = [ + "log", +] + [[package]] name = "jiff-static" version = "0.2.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a69dcb3a21cfb32ce1cd056169337ca284af0766dd766e7878819b251a49204" dependencies = [ - "jiff-core", + "jiff-core 0.1.0", "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "jiff-static" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "955491488dc99b572ea6d67b172dcd98787d00744b1fb44a5689b4e6413695a6" +dependencies = [ + "jiff-core 1.0.0", + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "jiff-tzdb" version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e" +[[package]] +name = "jiff-tzdb" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc" + [[package]] name = "jiff-tzdb-platform" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" dependencies = [ - "jiff-tzdb", + "jiff-tzdb 0.1.8", ] [[package]] @@ -2489,7 +2532,7 @@ dependencies = [ "bytes", "futures", "http", - "jiff", + "jiff 0.2.35", "log", "md-5", "percent-encoding", diff --git a/arrow-array/Cargo.toml b/arrow-array/Cargo.toml index 5a05329443..fe673f6e04 100644 --- a/arrow-array/Cargo.toml +++ b/arrow-array/Cargo.toml @@ -42,6 +42,9 @@ arrow-schema = { workspace = true } arrow-data = { workspace = true } chrono = { workspace = true } chrono-tz = { version = "0.10.3", optional = true } +# Timezones are built from jiff-tzdb, so jiff's own tzdb features are not needed +jiff = { version = "1.0", default-features = false, features = ["std", "tz-fat", "perf-inline"], optional = true } +jiff-tzdb = { version = "1.0", optional = true } futures = { version = "0.3", optional = true } num-complex = { version = "0.4.6", default-features = false, features = ["std"] } num-integer = { version = "0.1.46", default-features = false, features = ["std"] } @@ -56,6 +59,9 @@ all-features = true async = ["dep:futures"] ffi = ["arrow-schema/ffi", "arrow-data/ffi", "dep:libc"] force_validate = ["arrow-data/force_validate"] +# Use jiff for date and time support. It currently resolves named timezones, taking precedence +# over `chrono-tz` for every crate in the build (see the `timezone` module documentation). +jiff = ["dep:jiff", "dep:jiff-tzdb"] # Enable memory tracking support pool = ["arrow-buffer/pool", "arrow-data/pool"] diff --git a/arrow-array/src/array/primitive_array.rs b/arrow-array/src/array/primitive_array.rs index f9cd7a2084..b68e1de4cf 100644 --- a/arrow-array/src/array/primitive_array.rs +++ b/arrow-array/src/array/primitive_array.rs @@ -2277,7 +2277,7 @@ mod tests { } #[test] - #[cfg(feature = "chrono-tz")] + #[cfg(any(feature = "chrono-tz", feature = "jiff"))] fn test_timestamp_with_named_tz_fmt_debug() { let arr: PrimitiveArray<TimestampMillisecondType> = TimestampMillisecondArray::from(vec![1546214400000, 1546214400000, -1546214400000]) @@ -2289,7 +2289,7 @@ mod tests { } #[test] - #[cfg(not(feature = "chrono-tz"))] + #[cfg(not(any(feature = "chrono-tz", feature = "jiff")))] fn test_timestamp_with_named_tz_fmt_debug() { let arr: PrimitiveArray<TimestampMillisecondType> = TimestampMillisecondArray::from(vec![1546214400000, 1546214400000, -1546214400000]) @@ -2326,7 +2326,7 @@ mod tests { } #[test] - #[cfg(feature = "chrono-tz")] + #[cfg(any(feature = "chrono-tz", feature = "jiff"))] fn test_timestamp_with_tz_with_daylight_saving_fmt_debug() { let arr: PrimitiveArray<TimestampMillisecondType> = TimestampMillisecondArray::from(vec![ 1647161999000, diff --git a/arrow-array/src/timezone.rs b/arrow-array/src/timezone.rs index 1668b9487a..da7f27d0ea 100644 --- a/arrow-array/src/timezone.rs +++ b/arrow-array/src/timezone.rs @@ -3,11 +3,53 @@ // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements //! Timezone for timestamp arrays +//! +//! Without additional features, [`Tz`] only supports fixed offsets such as `+09:00`. The +//! `chrono-tz` and `jiff` features add named timezones from the [IANA time zone database], such +//! as `America/Los_Angeles`: +//! +//! * `chrono-tz` resolves names with [chrono-tz], which precomputes each zone's transitions up to +//! 2099 and keeps the last offset for any later instant, so daylight saving no longer changes it. +//! * `jiff` resolves names with [jiff], which applies each zone's daylight saving rules to any +//! instant, as `java.time` and libc do. +//! +//! When both are enabled, `jiff` is used. Cargo unifies features across a build, so enabling +//! `jiff` for any crate changes how named timezones are resolved for every crate in the build. +//! +//! Each feature bundles its own copy of the database, which may be a different release, so the two +//! can also disagree wherever the database changed between releases. [`tzdb_version`] returns the +//! release in use. +//! +//! [IANA time zone database]: https://www.iana.org/time-zones +//! [chrono-tz]: https://docs.rs/chrono-tz +//! [jiff]: https://docs.rs/jiff use arrow_schema::ArrowError; use chrono::{DateTime, FixedOffset, NaiveDateTime}; pub use private::{Tz, TzOffset}; +/// Returns the release of the [IANA time zone database] that resolves named timezones, such as +/// `"2026c"`. +/// +/// Returns `None` when neither the `chrono-tz` nor the `jiff` feature is enabled, as only fixed +/// offsets are then supported. +/// +/// [IANA time zone database]: https://www.iana.org/time-zones +pub fn tzdb_version() -> Option<&'static str> { + #[cfg(feature = "jiff")] + { + Some(jiff_tzdb::VERSION) + } + #[cfg(all(feature = "chrono-tz", not(feature = "jiff")))] + { + Some(chrono_tz::IANA_TZDB_VERSION) + } + #[cfg(not(any(feature = "chrono-tz", feature = "jiff")))] + { + None + } +} + /// Parses a fixed offset of the form "+09:00", "-09" or "+0930" fn parse_fixed_offset(tz: &str) -> Option<FixedOffset> { let bytes = tz.as_bytes(); @@ -35,7 +77,686 @@ fn parse_fixed_offset(tz: &str) -> Option<FixedOffset> { } } -#[cfg(feature = "chrono-tz")] +#[cfg(feature = "jiff")] +mod private { + use super::*; + use chrono::offset::TimeZone; + use chrono::{Datelike, LocalResult, NaiveDate, NaiveDateTime, NaiveTime, Offset, Timelike}; + use jiff::Timestamp; + use jiff::civil::DateTime as JiffDateTime; + use jiff::tz::{AmbiguousOffset, TimeZone as JiffTimeZone}; + use std::collections::HashMap; + use std::fmt::Display; + use std::str::FromStr; + use std::sync::OnceLock; + + /// An [`Offset`] for [`Tz`] + #[derive(Debug, Copy, Clone)] + pub struct TzOffset { + tz: Tz, + offset: FixedOffset, + } + + impl std::fmt::Display for TzOffset { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.offset.fmt(f) + } + } + + impl Offset for TzOffset { + fn fix(&self) -> FixedOffset { + self.offset + } + } + + /// A named timezone resolved by jiff, together with its name. + struct NamedTz { + name: &'static str, + tz: JiffTimeZone, + } + + /// Prints only the name, so that `Debug` output matches the `chrono-tz` feature. + impl std::fmt::Debug for NamedTz { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.name) + } + } + + /// Builds a timezone from jiff-tzdb. `jiff::tz::db()` would read the host's zoneinfo files + /// instead if any crate in the build enabled jiff's `tzdb-zoneinfo` feature. + fn bundled_tz(name: &str) -> Option<JiffTimeZone> { + // As jiff's own bundled database does, so that UTC is not backed by TZif data + if name == "UTC" { + return Some(JiffTimeZone::UTC); + } + let (canonical_name, tzif) = jiff_tzdb::get(name)?; + JiffTimeZone::tzif(canonical_name, tzif).ok() + } + + /// Resolves a name in the bundled database. As with chrono-tz, and unlike jiff, names are case + /// sensitive. + /// + /// [`Tz`] is `Copy` but [`JiffTimeZone`] is reference counted, so `Tz` holds a `'static` + /// reference into a table with one slot per bundled name, each resolved on first use. + fn named_tz(name: &str) -> Result<&'static NamedTz, ArrowError> { + type Slots = HashMap<&'static str, OnceLock<Option<NamedTz>>, ahash::RandomState>; + static SLOTS: OnceLock<Slots> = OnceLock::new(); + let slots = SLOTS.get_or_init(|| { + jiff_tzdb::available() + // A placeholder for an unknown local timezone, which chrono-tz does not accept + .filter(|name| *name != "Factory") + .map(|name| (name, OnceLock::new())) + .collect() + }); + slots + .get_key_value(name) + .and_then(|(name, slot)| { + slot.get_or_init(|| { + let tz = bundled_tz(name)?; + Some(NamedTz { name, tz }) + }) + .as_ref() + }) + // The same message as with chrono-tz + .ok_or_else(|| { + ArrowError::ParseError(format!( + "Invalid timezone \"{name}\": failed to parse timezone" + )) + }) + } + + /// An Arrow [`TimeZone`] + #[derive(Debug, Copy, Clone)] + pub struct Tz(TzInner); + + #[derive(Debug, Copy, Clone)] + enum TzInner { + Timezone(&'static NamedTz), + Offset(FixedOffset), + } + + // These are copied per value by chrono, so catch any accidental growth + #[cfg(target_pointer_width = "64")] + const _: () = { + assert!(std::mem::size_of::<Tz>() == 16); + assert!(std::mem::size_of::<TzOffset>() == 24); + }; + + impl FromStr for Tz { + type Err = ArrowError; + + fn from_str(tz: &str) -> Result<Self, Self::Err> { + match parse_fixed_offset(tz) { + Some(offset) => Ok(Self(TzInner::Offset(offset))), + None => Ok(Self(TzInner::Timezone(named_tz(tz)?))), + } + } + } + + impl Display for Tz { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.0 { + TzInner::Timezone(tz) => f.write_str(tz.name), + TzInner::Offset(offset) => offset.fmt(f), + } + } + } + + fn fixed_offset(offset: jiff::tz::Offset) -> FixedOffset { + // The bundled database never holds an offset of a day or more, so this cannot fail + FixedOffset::east_opt(offset.seconds()).expect("timezone offset within a day") + } + + /// The instant jiff should consult for a UTC datetime. jiff covers years -9999 to 9999; + /// anything outside that range takes the offset in force at the nearest covered instant. + fn jiff_timestamp(utc: &NaiveDateTime) -> Timestamp { + let seconds = utc.and_utc().timestamp(); + Timestamp::from_second(seconds).unwrap_or(if seconds < 0 { + Timestamp::MIN + } else { + Timestamp::MAX + }) + } + + /// The civil datetime jiff should resolve for a local datetime, or `None` when the year is + /// outside jiff's range. Sub-second precision is irrelevant to the offset in force. + fn jiff_civil(local: &NaiveDateTime) -> Option<JiffDateTime> { + JiffDateTime::new( + i16::try_from(local.year()).ok()?, + local.month() as i8, + local.day() as i8, + local.hour() as i8, + local.minute() as i8, + local.second() as i8, + 0, + ) + .ok() + } + + impl Tz { + fn offset(&self, offset: FixedOffset) -> TzOffset { + TzOffset { tz: *self, offset } + } + } + + impl TimeZone for Tz { + type Offset = TzOffset; + + fn from_offset(offset: &Self::Offset) -> Self { + offset.tz + } + + fn offset_from_local_date(&self, local: &NaiveDate) -> LocalResult<Self::Offset> { + match self.0 { + TzInner::Offset(tz) => tz + .offset_from_local_date(local) + .map(|x| self.offset(x.fix())), + TzInner::Timezone(_) => { + // As chrono-tz does, take an offset in force at the start or end of the day, + // so that a day with a transition still resolves + let earliest = self.offset_from_local_datetime(&local.and_time(NaiveTime::MIN)); + let latest = + self.offset_from_local_datetime(&local.and_hms_opt(23, 59, 59).unwrap()); + match (earliest, latest) { + (result @ LocalResult::Single(_), _) => result, + (_, result @ LocalResult::Single(_)) => result, + (LocalResult::Ambiguous(offset, _), _) => LocalResult::Single(offset), + (_, LocalResult::Ambiguous(offset, _)) => LocalResult::Single(offset), + (LocalResult::None, LocalResult::None) => LocalResult::None, + } + } + } + } + + fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<Self::Offset> { + match self.0 { + TzInner::Offset(tz) => tz + .offset_from_local_datetime(local) + .map(|x| self.offset(x.fix())), + TzInner::Timezone(tz) => match jiff_civil(local) { + // Outside jiff's range, treat the local datetime as if it were UTC. Either + // way it takes the offset in force at the nearest covered instant. + None => LocalResult::Single(self.offset_from_utc_datetime(local)), + Some(dt) => match tz.tz.to_ambiguous_timestamp(dt).offset() { + AmbiguousOffset::Unambiguous { offset } => { + LocalResult::Single(self.offset(fixed_offset(offset))) + } + AmbiguousOffset::Gap { .. } => LocalResult::None, + AmbiguousOffset::Fold { before, after } => LocalResult::Ambiguous( + self.offset(fixed_offset(before)), + self.offset(fixed_offset(after)), + ), + }, + }, + } + } + + fn offset_from_utc_date(&self, utc: &NaiveDate) -> Self::Offset { + self.offset_from_utc_datetime(&utc.and_time(NaiveTime::MIN)) + } + + fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> Self::Offset { + match self.0 { + TzInner::Offset(tz) => self.offset(tz.offset_from_utc_datetime(utc).fix()), + TzInner::Timezone(tz) => { + self.offset(fixed_offset(tz.tz.to_offset(jiff_timestamp(utc)))) + } + } + } + } + + pub(super) fn new_gap_info(local: &NaiveDateTime, tz: &Tz) -> Option<GapInfo> { + let TzInner::Timezone(named) = tz.0 else { + return None; + }; + // A local datetime outside jiff's range resolves to a single offset, so it is not in a gap + let civil = jiff_civil(local)?; + let AmbiguousOffset::Gap { before, after } = + named.tz.to_ambiguous_timestamp(civil).offset() + else { + return None; + }; + // Reading a local datetime in the gap with the later offset gives an instant before the + // transition, so the next transition is the one that opened the gap + let from = after.to_timestamp(civil).ok()?; + let transition = named.tz.following(from).next()?; + let end = DateTime::from_timestamp(transition.timestamp().as_second(), 0)?; + let begin = end.naive_utc() + chrono::TimeDelta::seconds(before.seconds().into()); + Some(GapInfo { + begin: Some((begin, tz.offset(fixed_offset(before)))), + end: Some(end.with_timezone(tz)), + }) + } + + #[cfg(test)] + mod tests { + use super::*; + use chrono::{Timelike, Utc}; + + #[test] + fn test_with_timezone() { + let vals = [ + Utc.timestamp_millis_opt(37800000).unwrap(), + Utc.timestamp_millis_opt(86339000).unwrap(), + ]; + + assert_eq!(10, vals[0].hour()); + assert_eq!(23, vals[1].hour()); + + let tz: Tz = "America/Los_Angeles".parse().unwrap(); + + assert_eq!(2, vals[0].with_timezone(&tz).hour()); + assert_eq!(15, vals[1].with_timezone(&tz).hour()); + } + + #[test] + fn test_dst_transitions_from_utc() { + let tz: Tz = "Australia/Sydney".parse().unwrap(); + let standard = FixedOffset::east_opt(10 * 60 * 60).unwrap(); + let daylight = FixedOffset::east_opt(11 * 60 * 60).unwrap(); + let at = |y, m, d, h, min| { + NaiveDate::from_ymd_opt(y, m, d) + .unwrap() + .and_hms_opt(h, min, 0) + .unwrap() + }; + // Daylight time ended 2021-04-04T03:00+11:00, which is 2021-04-03T16:00Z + assert_eq!( + tz.offset_from_utc_datetime(&at(2021, 4, 3, 15, 30)).fix(), + daylight + ); + assert_eq!( + tz.offset_from_utc_datetime(&at(2021, 4, 3, 16, 30)).fix(), + standard + ); + // Daylight time started 2021-10-03T02:00+10:00, which is 2021-10-02T16:00Z + assert_eq!( + tz.offset_from_utc_datetime(&at(2021, 10, 2, 15, 30)).fix(), + standard + ); + assert_eq!( + tz.offset_from_utc_datetime(&at(2021, 10, 2, 16, 30)).fix(), + daylight + ); + } + + #[test] + fn test_dst_transitions_from_local() { + let tz: Tz = "America/New_York".parse().unwrap(); + let eastern_standard = FixedOffset::west_opt(5 * 60 * 60).unwrap(); + let eastern_daylight = FixedOffset::west_opt(4 * 60 * 60).unwrap(); + let at = |m, d, h, min| { + NaiveDate::from_ymd_opt(2024, m, d) + .unwrap() + .and_hms_opt(h, min, 0) + .unwrap() + }; + match tz.offset_from_local_datetime(&at(1, 15, 12, 0)) { + LocalResult::Single(offset) => assert_eq!(offset.fix(), eastern_standard), + other => panic!("expected a single offset, got {other:?}"), + } + // 02:30 on 2024-03-10 was skipped when clocks went forward + assert!(matches!( + tz.offset_from_local_datetime(&at(3, 10, 2, 30)), + LocalResult::None + )); + // 01:30 on 2024-11-03 happened twice; the daylight reading comes first + match tz.offset_from_local_datetime(&at(11, 3, 1, 30)) { + LocalResult::Ambiguous(first, second) => { + assert_eq!(first.fix(), eastern_daylight); + assert_eq!(second.fix(), eastern_standard); + } + other => panic!("expected an ambiguous offset, got {other:?}"), + } + // A date on a transition day still resolves to an offset in force that day + assert!(matches!( + tz.offset_from_local_date(&NaiveDate::from_ymd_opt(2024, 3, 10).unwrap()), + LocalResult::Single(_) + )); + } + + /// chrono-tz keeps its last offset after 2099, while jiff keeps applying daylight saving + #[test] + fn test_dst_applies_after_2099() { + let hours = |h| FixedOffset::east_opt(h * 60 * 60).unwrap(); + // Each zone's offsets in January and July + let zones = [ + ("America/Los_Angeles", hours(-8), hours(-7)), + ("Australia/Sydney", hours(11), hours(10)), + ]; + for (zone, january, july) in zones { + let tz: Tz = zone.parse().unwrap(); + for year in [2024, 2100, 2300, 9999] { + for (month, expected) in [(1, january), (7, july)] { + let at = NaiveDate::from_ymd_opt(year, month, 1) + .unwrap() + .and_hms_opt(12, 0, 0) + .unwrap(); + assert_eq!( + tz.offset_from_utc_datetime(&at).fix(), + expected, + "{zone} {at}" + ); + match tz.offset_from_local_datetime(&at) { + LocalResult::Single(offset) => { + assert_eq!(offset.fix(), expected, "local {zone} {at}") + } + other => panic!("expected a single offset for {at}, got {other:?}"), + } + } + } + } + } + + /// chrono-tz has no transitions after 2099, so the comparison with it cannot check gaps + /// and folds there + #[test] + fn test_gaps_and_folds_after_2099() { + let tz: Tz = "America/Los_Angeles".parse().unwrap(); + let pacific_standard = FixedOffset::west_opt(8 * 60 * 60).unwrap(); + let pacific_daylight = FixedOffset::west_opt(7 * 60 * 60).unwrap(); + let at = |y, m, d, h, min| { + NaiveDate::from_ymd_opt(y, m, d) + .unwrap() + .and_hms_opt(h, min, 0) + .unwrap() + }; + // The second Sunday in March and the first Sunday in November of each year + for (year, spring, fall) in [(2100, 14, 7), (2300, 11, 4), (9998, 8, 1)] { + let skipped = at(year, 3, spring, 2, 30); + assert!(matches!( + tz.offset_from_local_datetime(&skipped), + LocalResult::None + )); + let gap = GapInfo::new(&skipped, &tz).unwrap(); + let (begin, begin_offset) = gap.begin.unwrap(); + assert_eq!(begin, at(year, 3, spring, 2, 0)); + assert_eq!(begin_offset.fix(), pacific_standard); + let end = gap.end.unwrap(); + assert_eq!(end.naive_local(), at(year, 3, spring, 3, 0)); + assert_eq!(end.offset().fix(), pacific_daylight); + + match tz.offset_from_local_datetime(&at(year, 11, fall, 1, 30)) { + LocalResult::Ambiguous(first, second) => { + assert_eq!(first.fix(), pacific_daylight); + assert_eq!(second.fix(), pacific_standard); + } + other => panic!("expected an ambiguous offset in {year}, got {other:?}"), + } + } + } + + #[test] + fn test_beyond_jiff_range() { + let tz: Tz = "America/Los_Angeles".parse().unwrap(); + let at = |year| { + NaiveDate::from_ymd_opt(year, 7, 1) + .unwrap() + .and_hms_opt(12, 0, 0) + .unwrap() + }; + // jiff covers years -9999 to 9999. Beyond that, rather than failing, the offset in + // force at the nearest covered instant applies: standard time at the end of 9999, + // and local mean time before the first transition. + let pacific_standard = FixedOffset::west_opt(8 * 60 * 60).unwrap(); + let local_mean_time = FixedOffset::west_opt(7 * 60 * 60 + 52 * 60 + 58).unwrap(); + for (year, expected) in [(20_000, pacific_standard), (-20_000, local_mean_time)] { + assert_eq!( + tz.offset_from_utc_datetime(&at(year)).fix(), + expected, + "{year}" + ); + match tz.offset_from_local_datetime(&at(year)) { + LocalResult::Single(offset) => { + assert_eq!(offset.fix(), expected, "local {year}") + } + other => panic!("expected a single offset for {year}, got {other:?}"), + } + } + } + + #[test] + fn test_timezone_display() { + let test_cases = ["UTC", "America/Los_Angeles", "-08:00", "+05:30"]; + for &case in &test_cases { + let tz: Tz = case.parse().unwrap(); + assert_eq!(tz.to_string(), case); + } + } + + #[test] + fn test_bundled_names() { + for name in jiff_tzdb::available() { + if name != "Factory" { + let tz: Tz = name.parse().unwrap(); + assert_eq!(tz.to_string(), name); + } + } + } + + #[test] + fn test_invalid_timezone() { + // jiff ignores case and knows some names that chrono-tz does not, but both features + // accept the same names + let names = [ + "Not/AZone", + "america/los_angeles", + "utc", + "Etc/Unknown", + "Factory", + ]; + for name in names { + let err = name.parse::<Tz>().unwrap_err().to_string(); + let expected = format!("Invalid timezone \"{name}\""); + assert!(err.contains(&expected), "{err}"); + } + } + + #[test] + fn test_debug_matches_chrono_tz() { + let tz: Tz = "America/Los_Angeles".parse().unwrap(); + assert_eq!(format!("{tz:?}"), "Tz(Timezone(America/Los_Angeles))"); + let offset = tz.offset_from_utc_datetime( + &NaiveDate::from_ymd_opt(2024, 1, 1) + .unwrap() + .and_hms_opt(0, 0, 0) + .unwrap(), + ); + assert_eq!( + format!("{offset:?}"), + "TzOffset { tz: Tz(Timezone(America/Los_Angeles)), offset: -08:00 }" + ); + } + + /// With `--features chrono-tz,jiff` both engines are compiled, so these compare them + /// directly. They are expected to fail when either crate moves to a new release of the + /// IANA database, which is how such a change gets noticed. + #[cfg(feature = "chrono-tz")] + mod compare_with_chrono_tz { + use super::*; + use std::collections::BTreeSet; + + /// Zones whose offsets differ only because the two engines bundle different releases. + /// When this test fails after a dependency update, review the differences and update + /// this list. + const KNOWN_DIFFERENCES: &[&str] = &[ + "Africa/Casablanca", + "Africa/El_Aaiun", + "America/Araguaina", + "America/Bahia", + "America/Belem", + "America/Boa_Vista", + "America/Bogota", + "America/Campo_Grande", + "America/Cuiaba", + "America/Edmonton", + "America/Eirunepe", + "America/Ensenada", + "America/Fortaleza", + "America/Havana", + "America/Inuvik", + "America/Maceio", + "America/Manaus", + "America/Noronha", + "America/Porto_Acre", + "America/Porto_Velho", + "America/Rainy_River", + "America/Recife", + "America/Rio_Branco", + "America/Santa_Isabel", + "America/Santarem", + "America/Sao_Paulo", + "America/Tijuana", + "America/Vancouver", + "America/Winnipeg", + "America/Yellowknife", + "Asia/Tehran", + "Brazil/Acre", + "Brazil/DeNoronha", + "Brazil/East", + "Brazil/West", + "CST6CDT", + "Canada/Central", + "Canada/Mountain", + "Canada/Pacific", + "Cuba", + "EST5EDT", + "Eire", + "Europe/Chisinau", + "Europe/Dublin", + "Europe/Tiraspol", + "Iran", + "MST7MDT", + "Mexico/BajaNorte", + "PST8PDT", + ]; + + fn releases() -> String { + format!( + "chrono-tz has tzdb {}, jiff-tzdb has tzdb {}", + chrono_tz::IANA_TZDB_VERSION, + jiff_tzdb::VERSION + ) + } + + fn at(seconds: i64) -> NaiveDateTime { + DateTime::from_timestamp(seconds, 0).unwrap().naive_utc() + } + + /// The parts of a gap that both engines report: where it begins and ends + type Gap = (Option<(NaiveDateTime, FixedOffset)>, Option<NaiveDateTime>); + + fn chrono_tz_gap(tz: &chrono_tz::Tz, local: &NaiveDateTime) -> Option<Gap> { + chrono_tz::GapInfo::new(local, tz).map(|gap| { + ( + gap.begin.map(|(begin, offset)| (begin, offset.fix())), + gap.end.map(|end| end.naive_utc()), + ) + }) + } + + fn jiff_gap(tz: &Tz, local: &NaiveDateTime) -> Option<Gap> { + GapInfo::new(local, tz).map(|gap| { + ( + gap.begin.map(|(begin, offset)| (begin, offset.fix())), + gap.end.map(|end| end.naive_utc()), + ) + }) + } + + /// Whether the engines agree when `datetime` is read as UTC and as local time + fn agree(chrono_tz: chrono_tz::Tz, jiff: Tz, datetime: &NaiveDateTime) -> bool { + chrono_tz_gap(&chrono_tz, datetime) == jiff_gap(&jiff, datetime) + && chrono_tz.offset_from_utc_datetime(datetime).fix() + == jiff.offset_from_utc_datetime(datetime).fix() + && chrono_tz + .offset_from_local_datetime(datetime) + .map(|o| o.fix()) + == jiff.offset_from_local_datetime(datetime).map(|o| o.fix()) + } + + #[test] + fn test_same_names() { + let chrono: BTreeSet<_> = + chrono_tz::TZ_VARIANTS.iter().map(|tz| tz.name()).collect(); + let jiff: BTreeSet<_> = jiff_tzdb::available() + .filter(|name| *name != "Factory") + .collect(); + assert_eq!(chrono, jiff, "{}", releases()); + } + + #[test] + fn test_same_offsets() { + // 1900-01-01 to 2099-01-01, before chrono-tz stops applying daylight saving + const START: i64 = -2_208_988_800; + const END: i64 = 4_070_908_800; + const WEEK: usize = 7 * 24 * 60 * 60; + + let mut different = BTreeSet::new(); + for variant in chrono_tz::TZ_VARIANTS { + let name = variant.name(); + let jiff: Tz = name.parse().unwrap(); + let TzInner::Timezone(named) = jiff.0 else { + unreachable!("{name} is not an offset"); + }; + + // Weekly samples find transitions that only one engine knows about + let mut samples: Vec<_> = (START..END).step_by(WEEK).map(at).collect(); + + // Probing each side of every transition covers gaps and folds + let start = Timestamp::from_second(START).unwrap(); + let transitions = named.tz.following(start); + for t in transitions.take_while(|t| t.timestamp().as_second() < END) { + let instant = t.timestamp().as_second(); + let after = i64::from(t.offset().seconds()); + let before = i64::from( + named + .tz + .to_offset(Timestamp::from_second(instant - 1).unwrap()) + .seconds(), + ); + samples.extend( + [ + instant - 1, + instant, + instant + before - 1, + instant + before, + instant + after - 1, + instant + after, + ] + .map(at), + ); + } + + // Years in which the two releases give different UTC offsets + let changed: BTreeSet<_> = samples + .iter() + .filter(|dt| { + variant.offset_from_utc_datetime(dt).fix() + != jiff.offset_from_utc_datetime(dt).fix() + }) + .map(|dt| dt.year()) + .collect(); + if !changed.is_empty() { + different.insert(name); + } + + // Every other year must also agree on local times and gaps. Neighbouring + // years are skipped too, as a local reading can fall in them. + for dt in &samples { + if !(dt.year() - 1..=dt.year() + 1).any(|y| changed.contains(&y)) { + assert!(agree(variant, jiff, dt), "{name} at {dt}, {}", releases()); + } + } + } + let known = KNOWN_DIFFERENCES.iter().copied().collect(); + assert_eq!(different, known, "{}", releases()); + } + } + } +} + +#[cfg(all(feature = "chrono-tz", not(feature = "jiff")))] mod private { use super::*; use chrono::offset::TimeZone; @@ -245,95 +966,6 @@ mod private { ); } - fn naive(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> NaiveDateTime { - NaiveDate::from_ymd_opt(y, mo, d) - .unwrap() - .and_hms_opt(h, mi, 0) - .unwrap() - } - - fn utc(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> chrono::DateTime<Utc> { - Utc.with_ymd_and_hms(y, mo, d, h, mi, 0).unwrap() - } - - #[test] - fn test_gap_info_not_in_gap() { - let tz: Tz = "America/New_York".parse().unwrap(); - // Just before and at the end of the 2021 spring forward gap - assert!(GapInfo::new(&naive(2021, 3, 14, 1, 59), &tz).is_none()); - assert!(GapInfo::new(&naive(2021, 3, 14, 3, 0), &tz).is_none()); - // Ambiguous time during the 2021 fall back overlap is not a gap - assert!(GapInfo::new(&naive(2021, 11, 7, 1, 30), &tz).is_none()); - } - - #[test] - fn test_gap_info_america_new_york() { - // Clocks went forward from 2021-03-14T02:00:00-05:00 to 2021-03-14T03:00:00-04:00 - let tz: Tz = "America/New_York".parse().unwrap(); - for local in [ - naive(2021, 3, 14, 2, 0), - naive(2021, 3, 14, 2, 30), - naive(2021, 3, 14, 2, 59), - ] { - assert!(tz.from_local_datetime(&local).single().is_none()); - - let gap = GapInfo::new(&local, &tz).unwrap(); - let (begin, begin_offset) = gap.begin.unwrap(); - assert_eq!(begin, naive(2021, 3, 14, 2, 0)); - assert_eq!( - begin_offset.fix(), - FixedOffset::west_opt(5 * 60 * 60).unwrap() - ); - - let end = gap.end.unwrap(); - assert_eq!(end.naive_local(), naive(2021, 3, 14, 3, 0)); - assert_eq!( - end.offset().fix(), - FixedOffset::west_opt(4 * 60 * 60).unwrap() - ); - assert_eq!(end, utc(2021, 3, 14, 7, 0)); - assert_eq!(end.timezone().to_string(), "America/New_York"); - } - } - - #[test] - fn test_gap_info_europe_london() { - // Clocks went forward from 2021-03-28T01:00:00+00:00 to 2021-03-28T02:00:00+01:00 - let tz: Tz = "Europe/London".parse().unwrap(); - let gap = GapInfo::new(&naive(2021, 3, 28, 1, 30), &tz).unwrap(); - - let (begin, begin_offset) = gap.begin.unwrap(); - assert_eq!(begin, naive(2021, 3, 28, 1, 0)); - assert_eq!(begin_offset.fix(), FixedOffset::east_opt(0).unwrap()); - - let end = gap.end.unwrap(); - assert_eq!(end.naive_local(), naive(2021, 3, 28, 2, 0)); - assert_eq!(end.offset().fix(), FixedOffset::east_opt(60 * 60).unwrap()); - assert_eq!(end, utc(2021, 3, 28, 1, 0)); - } - - #[test] - fn test_gap_info_australia_sydney() { - // Clocks went forward from 2021-10-03T02:00:00+10:00 to 2021-10-03T03:00:00+11:00 - let tz: Tz = "Australia/Sydney".parse().unwrap(); - let gap = GapInfo::new(&naive(2021, 10, 3, 2, 30), &tz).unwrap(); - - let (begin, begin_offset) = gap.begin.unwrap(); - assert_eq!(begin, naive(2021, 10, 3, 2, 0)); - assert_eq!( - begin_offset.fix(), - FixedOffset::east_opt(10 * 60 * 60).unwrap() - ); - - let end = gap.end.unwrap(); - assert_eq!(end.naive_local(), naive(2021, 10, 3, 3, 0)); - assert_eq!( - end.offset().fix(), - FixedOffset::east_opt(11 * 60 * 60).unwrap() - ); - assert_eq!(end, utc(2021, 10, 2, 16, 0)); - } - #[test] fn test_timezone_display() { let test_cases = ["UTC", "America/Los_Angeles", "-08:00", "+05:30"]; @@ -345,7 +977,7 @@ mod private { } } -#[cfg(not(feature = "chrono-tz"))] +#[cfg(not(any(feature = "chrono-tz", feature = "jiff")))] mod private { use super::*; use chrono::offset::TimeZone; @@ -378,7 +1010,7 @@ mod private { fn from_str(tz: &str) -> Result<Self, Self::Err> { let offset = parse_fixed_offset(tz).ok_or_else(|| { ArrowError::ParseError(format!( - "Invalid timezone \"{tz}\": only offset based timezones supported without chrono-tz feature" + "Invalid timezone \"{tz}\": only offset based timezones supported without chrono-tz or jiff feature" )) })?; Ok(Self(offset)) @@ -429,7 +1061,7 @@ mod private { /// does not. /// /// ``` -/// # #[cfg(feature = "chrono-tz")] +/// # #[cfg(any(feature = "chrono-tz", feature = "jiff"))] /// # { /// use arrow_array::timezone::{GapInfo, Tz}; /// use chrono::{DateTime, FixedOffset, LocalResult, NaiveDateTime, Offset, TimeZone}; @@ -557,4 +1189,99 @@ mod tests { } } } + + #[cfg(any(feature = "chrono-tz", feature = "jiff"))] + mod gap_info { + use super::*; + use chrono::Utc; + + fn naive(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> NaiveDateTime { + NaiveDate::from_ymd_opt(y, mo, d) + .unwrap() + .and_hms_opt(h, mi, 0) + .unwrap() + } + + fn utc(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> chrono::DateTime<Utc> { + Utc.with_ymd_and_hms(y, mo, d, h, mi, 0).unwrap() + } + + #[test] + fn test_gap_info_not_in_gap() { + let tz: Tz = "America/New_York".parse().unwrap(); + // Just before and at the end of the 2021 spring forward gap + assert!(GapInfo::new(&naive(2021, 3, 14, 1, 59), &tz).is_none()); + assert!(GapInfo::new(&naive(2021, 3, 14, 3, 0), &tz).is_none()); + // Ambiguous time during the 2021 fall back overlap is not a gap + assert!(GapInfo::new(&naive(2021, 11, 7, 1, 30), &tz).is_none()); + } + + #[test] + fn test_gap_info_america_new_york() { + // Clocks went forward from 2021-03-14T02:00:00-05:00 to 2021-03-14T03:00:00-04:00 + let tz: Tz = "America/New_York".parse().unwrap(); + for local in [ + naive(2021, 3, 14, 2, 0), + naive(2021, 3, 14, 2, 30), + naive(2021, 3, 14, 2, 59), + ] { + assert!(tz.from_local_datetime(&local).single().is_none()); + + let gap = GapInfo::new(&local, &tz).unwrap(); + let (begin, begin_offset) = gap.begin.unwrap(); + assert_eq!(begin, naive(2021, 3, 14, 2, 0)); + assert_eq!( + begin_offset.fix(), + FixedOffset::west_opt(5 * 60 * 60).unwrap() + ); + + let end = gap.end.unwrap(); + assert_eq!(end.naive_local(), naive(2021, 3, 14, 3, 0)); + assert_eq!( + end.offset().fix(), + FixedOffset::west_opt(4 * 60 * 60).unwrap() + ); + assert_eq!(end, utc(2021, 3, 14, 7, 0)); + assert_eq!(end.timezone().to_string(), "America/New_York"); + } + } + + #[test] + fn test_gap_info_europe_london() { + // Clocks went forward from 2021-03-28T01:00:00+00:00 to 2021-03-28T02:00:00+01:00 + let tz: Tz = "Europe/London".parse().unwrap(); + let gap = GapInfo::new(&naive(2021, 3, 28, 1, 30), &tz).unwrap(); + + let (begin, begin_offset) = gap.begin.unwrap(); + assert_eq!(begin, naive(2021, 3, 28, 1, 0)); + assert_eq!(begin_offset.fix(), FixedOffset::east_opt(0).unwrap()); + + let end = gap.end.unwrap(); + assert_eq!(end.naive_local(), naive(2021, 3, 28, 2, 0)); + assert_eq!(end.offset().fix(), FixedOffset::east_opt(60 * 60).unwrap()); + assert_eq!(end, utc(2021, 3, 28, 1, 0)); + } + + #[test] + fn test_gap_info_australia_sydney() { + // Clocks went forward from 2021-10-03T02:00:00+10:00 to 2021-10-03T03:00:00+11:00 + let tz: Tz = "Australia/Sydney".parse().unwrap(); + let gap = GapInfo::new(&naive(2021, 10, 3, 2, 30), &tz).unwrap(); + + let (begin, begin_offset) = gap.begin.unwrap(); + assert_eq!(begin, naive(2021, 10, 3, 2, 0)); + assert_eq!( + begin_offset.fix(), + FixedOffset::east_opt(10 * 60 * 60).unwrap() + ); + + let end = gap.end.unwrap(); + assert_eq!(end.naive_local(), naive(2021, 10, 3, 3, 0)); + assert_eq!( + end.offset().fix(), + FixedOffset::east_opt(11 * 60 * 60).unwrap() + ); + assert_eq!(end, utc(2021, 10, 2, 16, 0)); + } + } } diff --git a/arrow-array/src/types.rs b/arrow-array/src/types.rs index 131327cef7..9f88ecbcf8 100644 --- a/arrow-array/src/types.rs +++ b/arrow-array/src/types.rs @@ -2048,7 +2048,7 @@ mod tests { } #[test] - #[cfg(feature = "chrono-tz")] + #[cfg(any(feature = "chrono-tz", feature = "jiff"))] fn timestamp_from_naive_datetime_ambiguous() { use chrono::{NaiveDate, NaiveTime}; @@ -2066,7 +2066,7 @@ mod tests { } #[test] - #[cfg(feature = "chrono-tz")] + #[cfg(any(feature = "chrono-tz", feature = "jiff"))] fn timestamp_from_naive_datetime_none() { use chrono::{NaiveDate, NaiveTime}; diff --git a/arrow-cast/src/parse.rs b/arrow-cast/src/parse.rs index 65a33eea27..77aa7f92cf 100644 --- a/arrow-cast/src/parse.rs +++ b/arrow-cast/src/parse.rs @@ -158,7 +158,7 @@ impl TimestampParser { /// * `1997-01-31 092656+04:00` # close to RCF3339, no fractional seconds or time separator /// * `1997-01-31` # close to RCF3339, only date no time /// -/// [IANA timezones] are only supported if the `arrow-array/chrono-tz` feature is enabled +/// [IANA timezones] are only supported if the `arrow-array/chrono-tz` or `arrow-array/jiff` feature is enabled /// /// * `2023-01-01 040506 America/Los_Angeles` /// diff --git a/arrow-schema/src/datatype.rs b/arrow-schema/src/datatype.rs index 84a3c037dd..5b984d18ab 100644 --- a/arrow-schema/src/datatype.rs +++ b/arrow-schema/src/datatype.rs @@ -196,11 +196,14 @@ pub enum DataType { /// /// Timezone string parsing /// ----------------------- - /// When feature `chrono-tz` is not enabled, allowed timezone strings are fixed offsets of the form "+09:00", "-09" or "+0930". + /// When neither feature `chrono-tz` nor `jiff` is enabled, allowed timezone strings are fixed offsets of the form "+09:00", "-09" or "+0930". /// /// When feature `chrono-tz` is enabled, additional strings supported by [chrono_tz](https://docs.rs/chrono-tz/latest/chrono_tz/) /// are also allowed, which include [IANA database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) /// timezones. + /// + /// When feature `jiff` is enabled, the same strings are allowed, and named timezones are resolved + /// with [jiff](https://docs.rs/jiff/latest/jiff/) instead. `jiff` takes precedence over `chrono-tz`. Timestamp(TimeUnit, Option<Arc<str>>), /// A signed 32-bit date representing the elapsed time since UNIX epoch (1970-01-01) /// in days. diff --git a/arrow/Cargo.toml b/arrow/Cargo.toml index 92a9d9e10c..9da0c65d7d 100644 --- a/arrow/Cargo.toml +++ b/arrow/Cargo.toml @@ -70,6 +70,7 @@ force_validate = ["arrow-array/force_validate", "arrow-data/force_validate"] # Enable ffi support ffi = ["arrow-schema/ffi", "arrow-data/ffi", "arrow-array/ffi"] chrono-tz = ["arrow-array/chrono-tz"] +jiff = ["arrow-array/jiff"] canonical_extension_types = ["arrow-schema/canonical_extension_types"] # Enable memory tracking support pool = ["arrow-array/pool"] @@ -316,6 +317,12 @@ name = "nullif_kernel" harness = false required-features = ["test_utils"] +[[bench]] +name = "named_timezone" +harness = false +# Cargo cannot require one of several features. To measure jiff, run with `chrono-tz,jiff`. +required-features = ["chrono-tz"] + [[test]] name = "csv" required-features = ["csv", "chrono-tz"] diff --git a/arrow/README.md b/arrow/README.md index 3496de59ce..9a99849201 100644 --- a/arrow/README.md +++ b/arrow/README.md @@ -49,6 +49,7 @@ The `arrow` crate provides the following features which may be enabled in your ` - `prettyprint` - support for formatting record batches as textual columns implementations of some [compute](https://github.com/apache/arrow-rs/tree/main/arrow/src/compute/kernels) - `chrono-tz` - support of parsing timezone using [chrono-tz](https://docs.rs/chrono-tz/0.6.0/chrono_tz/) +- `jiff` - use [jiff](https://docs.rs/jiff/latest/jiff/) for date and time support. It currently covers named timezones, and takes precedence over `chrono-tz` - `ffi` - bindings for the Arrow C [C Data Interface](https://arrow.apache.org/docs/format/CDataInterface.html) - `pyarrow` - bindings for pyo3 to call arrow-rs from python - `pyarrow-experimental-inspect` - record the pyarrow type of each conversion in PyO3's introspection data, so that stub generators emit e.g. `pyarrow.Array` rather than `_typeshed.Incomplete` (also enables `pyarrow`) diff --git a/arrow/benches/named_timezone.rs b/arrow/benches/named_timezone.rs new file mode 100644 index 0000000000..9fc406608f --- /dev/null +++ b/arrow/benches/named_timezone.rs @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Benchmarks for named (IANA) timezones, which the `chrono-tz` and `jiff` features resolve. +//! +//! Run with `--features chrono-tz` and again with `--features chrono-tz,jiff` to compare the two +//! implementations behind [`Tz`]. + +use arrow::array::timezone::Tz; +use arrow::array::{TimestampMicrosecondArray, TimestampMillisecondArray}; +use arrow::compute::{DatePart, cast, date_part}; +use arrow::datatypes::DataType; +use chrono::{DateTime, NaiveDateTime, TimeZone}; +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +const ZONES: [&str; 4] = ["UTC", "America/Los_Angeles", "Europe/London", "Asia/Tokyo"]; + +/// Microseconds since the epoch at the start of 2038, 2100 and 2300 +const Y2038: i64 = 2_145_916_800_000_000; +const Y2100: i64 = 4_102_444_800_000_000; +const Y2300: i64 = 10_413_792_000_000_000; + +/// Instant ranges in microseconds. jiff's transition tables end in 2038, after which it evaluates +/// each zone's rule, and chrono-tz's end in 2099. +const RANGES: [(&str, i64, i64); 3] = [ + ("1970_to_2038", 0, Y2038), + ("2038_to_2100", Y2038, Y2100), + ("2100_to_2300", Y2100, Y2300), +]; + +/// Microsecond instants spread evenly over the range +fn instants(len: usize, start: i64, end: i64) -> Vec<i64> { + (0..len) + .map(|i| start + (end - start) / len as i64 * i as i64) + .collect() +} + +fn bench_parse(c: &mut Criterion) { + let mut group = c.benchmark_group("tz_parse"); + for zone in ZONES { + group.bench_function(zone, |b| { + b.iter(|| black_box(black_box(zone).parse::<Tz>().unwrap())) + }); + } + group.finish(); +} + +fn bench_offset_lookup(c: &mut Criterion) { + for (range, start, end) in RANGES { + let utc: Vec<NaiveDateTime> = instants(8192, start, end) + .into_iter() + .map(|micros| DateTime::from_timestamp_micros(micros).unwrap().naive_utc()) + .collect(); + + let mut group = c.benchmark_group(format!("tz_offset_from_utc_datetime/{range}")); + group.throughput(criterion::Throughput::Elements(utc.len() as u64)); + for zone in ZONES { + let tz: Tz = zone.parse().unwrap(); + group.bench_function(zone, |b| { + b.iter(|| { + for dt in &utc { + black_box(tz.offset_from_utc_datetime(black_box(dt))); + } + }) + }); + } + group.finish(); + + let mut group = c.benchmark_group(format!("tz_offset_from_local_datetime/{range}")); + group.throughput(criterion::Throughput::Elements(utc.len() as u64)); + for zone in ZONES { + let tz: Tz = zone.parse().unwrap(); + group.bench_function(zone, |b| { + b.iter(|| { + for dt in &utc { + black_box(tz.offset_from_local_datetime(black_box(dt))); + } + }) + }); + } + group.finish(); + } +} + +fn bench_kernels(c: &mut Criterion) { + for (range, start, end) in RANGES { + let micros = TimestampMicrosecondArray::from(instants(1 << 20, start, end)); + let millis = TimestampMillisecondArray::from( + instants(1 << 17, start, end) + .into_iter() + .map(|v| v / 1000) + .collect::<Vec<_>>(), + ); + + let mut group = c.benchmark_group(format!("date_part_hour/1M/{range}")); + for zone in ZONES { + let array = micros.clone().with_timezone(zone); + group.bench_function(zone, |b| { + b.iter(|| black_box(date_part(black_box(&array), DatePart::Hour).unwrap())) + }); + } + group.finish(); + + let mut group = c.benchmark_group(format!("cast_timestamp_to_utf8/128K/{range}")); + for zone in ZONES { + let array = millis.clone().with_timezone(zone); + group.bench_function(zone, |b| { + b.iter(|| black_box(cast(black_box(&array), &DataType::Utf8).unwrap())) + }); + } + group.finish(); + } +} + +criterion_group!(benches, bench_parse, bench_offset_lookup, bench_kernels); +criterion_main!(benches);
