diff --git a/Cargo.lock b/Cargo.lock index 749ca1477..ac6b9ff98 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -869,6 +869,7 @@ dependencies = [ "log", "num-traits", "resb", + "temporal_utils", "timezone_provider", "tinystr", "web-time", @@ -898,6 +899,10 @@ dependencies = [ "temporal", ] +[[package]] +name = "temporal_utils" +version = "0.2.6" + [[package]] name = "timezone_provider" version = "0.2.6" @@ -908,6 +913,7 @@ dependencies = [ "jiff-tzdb", "serde", "serde_json", + "temporal_utils", "tinystr", "tzif", "yoke", @@ -1358,6 +1364,7 @@ dependencies = [ "indexmap", "serde", "serde_json", + "temporal_utils", "tzif", "zoneinfo_rs", ] diff --git a/Cargo.toml b/Cargo.toml index c78d84c4f..e1eca49a5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,7 @@ exclude = [ temporal = { version = "0.2.6", path = "./crates/temporal", default-features = false } timezone_provider = { version = "0.2.6", path = "./crates/provider", default-features = false } zoneinfo_rs = { version = "0.1.0", path = "./crates/zoneinfo", default-features = false } +temporal_utils = { version = "0.2.6", path = "./crates/temporal_utils" } # Dependencies rustc-hash = "2.1.0" diff --git a/crates/provider/Cargo.toml b/crates/provider/Cargo.toml index 86434d4d9..20f7a7967 100644 --- a/crates/provider/Cargo.toml +++ b/crates/provider/Cargo.toml @@ -52,6 +52,7 @@ zoneinfo64 = ["dep:zoneinfo64"] [dependencies] # Provider dependency +temporal_utils = { workspace = true } zerotrie.workspace = true zerovec = { workspace = true, features = ["derive", "alloc"] } tinystr = { workspace = true, features = ["zerovec"] } diff --git a/crates/provider/src/common.rs b/crates/provider/src/common.rs index dad2d4e2d..1c5649aaf 100644 --- a/crates/provider/src/common.rs +++ b/crates/provider/src/common.rs @@ -1,9 +1,7 @@ //! Common logic shared across TZif providers -use crate::{ - provider::{GapEntryOffsets, UtcOffsetSeconds}, - utils, -}; +use crate::provider::{GapEntryOffsets, UtcOffsetSeconds}; +use temporal_utils as utils; use core::ops::Range; diff --git a/crates/provider/src/epoch_nanoseconds.rs b/crates/provider/src/epoch_nanoseconds.rs index 302958e5d..d8eea7fcf 100644 --- a/crates/provider/src/epoch_nanoseconds.rs +++ b/crates/provider/src/epoch_nanoseconds.rs @@ -1,13 +1,13 @@ use crate::TimeZoneProviderError; +pub(crate) use temporal_utils::MS_PER_DAY; + /// Number of nanoseconds in a day #[doc(hidden)] pub const NS_PER_DAY: u64 = MS_PER_DAY as u64 * 1_000_000; pub(crate) const NS_IN_S: i128 = 1_000_000_000; -/// Milliseconds per day constant: 8.64e+7 -pub(crate) const MS_PER_DAY: u32 = 24 * 60 * 60 * 1000; /// Max Instant nanosecond constant #[doc(hidden)] pub(crate) const NS_MAX_INSTANT: i128 = NS_PER_DAY as i128 * 100_000_000i128; diff --git a/crates/provider/src/experimental_tzif/posix.rs b/crates/provider/src/experimental_tzif/posix.rs index deca061c5..0b8ffb0f4 100644 --- a/crates/provider/src/experimental_tzif/posix.rs +++ b/crates/provider/src/experimental_tzif/posix.rs @@ -5,8 +5,9 @@ use crate::{ }, epoch_nanoseconds::EpochNanoseconds, provider::{GapEntryOffsets, TimeZoneProviderResult, UtcOffsetSeconds}, - utils, TimeZoneProviderError, + TimeZoneProviderError, }; +use temporal_utils as utils; use tinystr::TinyAsciiStr; #[cfg(feature = "datagen")] diff --git a/crates/provider/src/experimental_tzif/provider.rs b/crates/provider/src/experimental_tzif/provider.rs index 32b0fceab..0cdf9e9a9 100644 --- a/crates/provider/src/experimental_tzif/provider.rs +++ b/crates/provider/src/experimental_tzif/provider.rs @@ -14,8 +14,9 @@ use crate::{ CandidateEpochNanoseconds, EpochNanosecondsAndOffset, GapEntryOffsets, ResolvedId, TimeZoneProviderResult, TimeZoneResolver, TransitionDirection, UtcOffsetSeconds, }, - utils, TimeZoneProviderError, + TimeZoneProviderError, }; +use temporal_utils as utils; use zerofrom::ZeroFrom; #[derive(Debug, Default)] diff --git a/crates/provider/src/lib.rs b/crates/provider/src/lib.rs index 469627a6e..fa2ec4f73 100644 --- a/crates/provider/src/lib.rs +++ b/crates/provider/src/lib.rs @@ -90,9 +90,6 @@ pub mod epoch_nanoseconds; #[cfg(any(feature = "tzif", feature = "experimental_tzif"))] pub(crate) mod common; -#[doc(hidden)] -pub mod utils; - mod error; pub mod provider; pub use error::TimeZoneProviderError; diff --git a/crates/provider/src/provider.rs b/crates/provider/src/provider.rs index 217c7316f..386b67aff 100644 --- a/crates/provider/src/provider.rs +++ b/crates/provider/src/provider.rs @@ -5,10 +5,10 @@ use core::str::FromStr; -use crate::utils; use crate::CompiledNormalizer; use crate::{epoch_nanoseconds::EpochNanoseconds, TimeZoneProviderError}; use alloc::borrow::Cow; +use temporal_utils as utils; pub(crate) type TimeZoneProviderResult = Result; diff --git a/crates/provider/src/tzif.rs b/crates/provider/src/tzif.rs index 421c1c5ae..a4cfd4d55 100644 --- a/crates/provider/src/tzif.rs +++ b/crates/provider/src/tzif.rs @@ -58,7 +58,7 @@ use tzif::{ }, }; -use crate::utils; +use temporal_utils as utils; use crate::provider::{ CandidateEpochNanoseconds, GapEntryOffsets, IsoDateTime, NormalizerAndResolver, ResolvedId, diff --git a/crates/provider/src/utils.rs b/crates/provider/src/utils.rs deleted file mode 100644 index ce254788a..000000000 --- a/crates/provider/src/utils.rs +++ /dev/null @@ -1,132 +0,0 @@ -//! Utility date and time equations for Temporal - -use crate::epoch_nanoseconds::MS_PER_DAY; - -pub mod neri_schneider; - -pub use neri_schneider::epoch_days_from_gregorian_date; - -// NOTE: Potentially add more of tests. - -// ==== Begin Date Equations ==== - -pub(crate) const MS_PER_HOUR: i64 = 3_600_000; -pub(crate) const MS_PER_MINUTE: i64 = 60_000; - -/// `EpochDaysToEpochMS` -/// -/// Functionally the same as Date's abstract operation `MakeDate` -pub fn epoch_days_to_epoch_ms(day: i64, time: i64) -> i64 { - (day * MS_PER_DAY as i64) + time -} - -/// `EpochTimeToDayNumber` -/// -/// This equation is the equivalent to `ECMAScript`'s `Date(t)` -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] -pub(crate) fn epoch_time_to_day_number(t: i64) -> i32 { - t.div_euclid(MS_PER_DAY as i64) as i32 -} - -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] -pub(crate) fn epoch_ms_to_ms_in_day(t: i64) -> u32 { - (t.rem_euclid(i64::from(MS_PER_DAY))) as u32 -} - -// https://tc39.es/proposal-temporal/#eqn-mathematicalinleapyear -pub(crate) fn is_leap(y: i32) -> bool { - if y % 4 != 0 { - false - } else if y % 4 == 0 && y % 100 != 0 { - true - } else if y % 100 == 0 && y % 400 != 0 { - false - } else { - // Assert that y is divisble by 400 to ensure we are returning the correct result. - assert_eq!(y % 400, 0); - true - } -} - -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] -pub(crate) fn epoch_time_to_iso_year(t: i64) -> i32 { - let epoch_days = epoch_ms_to_epoch_days(t); - let (rata_die, shift_constant) = neri_schneider::rata_die_for_epoch_days(epoch_days); - neri_schneider::year(rata_die, shift_constant) -} - -/// Returns the epoch day number for a given year. -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] -pub(crate) fn epoch_days_for_year(y: i32) -> i32 { - 365 * (y - 1970) + (y - 1969).div_euclid(4) - (y - 1901).div_euclid(100) - + (y - 1601).div_euclid(400) -} - -pub(crate) const fn epoch_ms_to_epoch_days(ms: i64) -> i32 { - (ms.div_euclid(MS_PER_DAY as i64)) as i32 -} - -pub fn ymd_from_epoch_milliseconds(epoch_milliseconds: i64) -> (i32, u8, u8) { - let epoch_days = epoch_ms_to_epoch_days(epoch_milliseconds); - neri_schneider::ymd_from_epoch_days(epoch_days) -} - -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] -pub(crate) fn month_to_day(m: u8, is_leap: bool) -> u16 { - let leap_day = u16::from(is_leap); - match m { - 0 => 0, - 1 => 31, - 2 => 59 + leap_day, - 3 => 90 + leap_day, - 4 => 120 + leap_day, - 5 => 151 + leap_day, - 6 => 181 + leap_day, - 7 => 212 + leap_day, - 8 => 243 + leap_day, - 9 => 273 + leap_day, - 10 => 304 + leap_day, - 11 => 334 + leap_day, - _ => unreachable!(), - } -} - -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] -pub(crate) fn epoch_time_to_day_in_year(t: i64) -> i32 { - epoch_time_to_day_number(t) - (epoch_days_for_year(epoch_time_to_iso_year(t))) -} - -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] -pub(crate) fn epoch_seconds_to_day_of_week(t: i64) -> u8 { - ((t / 86_400) + 4).rem_euclid(7) as u8 -} - -// Trait implementations - -// EpochTimeTOWeekDay -> REMOVED - -// ==== End Date Equations ==== - -// ==== Begin Calendar Equations ==== - -// NOTE: below was the iso methods in temporal::calendar -> Need to be reassessed. - -/// 12.2.31 `ISODaysInMonth ( year, month )` -/// -/// NOTE: month is 1 based -pub fn iso_days_in_month(year: i32, month: u8) -> u8 { - match month { - 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, - 4 | 6 | 9 | 11 => 30, - 2 => 28 + is_leap(year) as u8, - _ => unreachable!("ISODaysInMonth panicking is an implementation error."), - } -} - -// The below calendar abstract equations/utilities were removed for being unused. -// 12.2.32 `ToISOWeekOfYear ( year, month, day )` -// 12.2.33 `ISOMonthCode ( month )` -// 12.2.39 `ToISODayOfYear ( year, month, day )` -// 12.2.40 `ToISODayOfWeek ( year, month, day )` - -// ==== End Calendar Equations ==== diff --git a/crates/temporal/Cargo.toml b/crates/temporal/Cargo.toml index dde03aa05..5313517d7 100644 --- a/crates/temporal/Cargo.toml +++ b/crates/temporal/Cargo.toml @@ -14,6 +14,7 @@ exclude.workspace = true [dependencies] +temporal_utils = { workspace = true } core_maths = "0.1.1" icu_calendar = { workspace = true, features = ["compiled_data"] } icu_locale_core.workspace = true diff --git a/crates/temporal/src/utils.rs b/crates/temporal/src/utils.rs index bb85c67cc..56d5d095b 100644 --- a/crates/temporal/src/utils.rs +++ b/crates/temporal/src/utils.rs @@ -1,16 +1,6 @@ //! Utility date and time equations for Temporal -pub(crate) use timezone_provider::utils::epoch_days_from_gregorian_date; - -// NOTE: Potentially add more of tests. - -// ==== Begin Date Equations ==== - -pub(crate) const MS_PER_HOUR: i64 = 3_600_000; -pub(crate) const MS_PER_MINUTE: i64 = 60_000; - -pub(crate) use timezone_provider::utils::{ - epoch_days_to_epoch_ms, iso_days_in_month, ymd_from_epoch_milliseconds, +pub(crate) use temporal_utils::{ + epoch_days_from_gregorian_date, epoch_days_to_epoch_ms, iso_days_in_month, + ymd_from_epoch_milliseconds, MS_PER_HOUR, MS_PER_MINUTE, }; - -// ==== End Calendar Equations ==== diff --git a/crates/temporal_utils/Cargo.toml b/crates/temporal_utils/Cargo.toml new file mode 100644 index 000000000..5caf14647 --- /dev/null +++ b/crates/temporal_utils/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "temporal_utils" +description = "Gregorian and ISO-calendar date equations" +edition.workspace = true +version.workspace = true +rust-version.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +readme.workspace = true +exclude.workspace = true +include = [ + "src/**/*.rs", + "Cargo.toml", + "LICENSE-Apache", + "LICENSE-MIT", + "README.md", +] + +[package.metadata.docs.rs] +all-features = true diff --git a/crates/temporal_utils/LICENSE-Apache b/crates/temporal_utils/LICENSE-Apache new file mode 100644 index 000000000..551045b58 --- /dev/null +++ b/crates/temporal_utils/LICENSE-Apache @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Boa + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/crates/temporal_utils/LICENSE-MIT b/crates/temporal_utils/LICENSE-MIT new file mode 100644 index 000000000..d5624ad0c --- /dev/null +++ b/crates/temporal_utils/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Boa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/temporal_utils/README.md b/crates/temporal_utils/README.md new file mode 100644 index 000000000..0d248371e --- /dev/null +++ b/crates/temporal_utils/README.md @@ -0,0 +1,19 @@ +# temporal_utils + +Gregorian and ISO-calendar date equations shared across the `temporal` +workspace (`temporal`, `timezone_provider`, `zoneinfo_rs`). + +This crate has no dependencies and performs no I/O; it converts between +epoch days/milliseconds and Gregorian year/month/day, and computes leap +years, weekdays, and ISO month lengths. The Gregorian conversion is based +on Cassio Neri and Lorenz Schneider's paper, [Euclidean affine functions +and their application to calendar +algorithms](https://onlinelibrary.wiley.com/doi/full/10.1002/spe.3172). + +## Why a separate crate? + +This logic was previously duplicated between `timezone_provider` (as a +`#[doc(hidden)]` module) and `zoneinfo_rs` (with slightly different +signatures). Consolidating it here removes the duplication and lets pure +calendar math be consumed without pulling in the heavier tzdb/TZif-parsing +dependencies of `timezone_provider`. diff --git a/crates/temporal_utils/src/lib.rs b/crates/temporal_utils/src/lib.rs new file mode 100644 index 000000000..5edfdab8d --- /dev/null +++ b/crates/temporal_utils/src/lib.rs @@ -0,0 +1,180 @@ +//! Gregorian and ISO-calendar date equations: epoch days/milliseconds, +//! year/month/day, leap years, and weekdays. No dependencies, no I/O. + +#![no_std] +#![forbid(unsafe_code)] + +pub mod neri_schneider; + +pub use neri_schneider::epoch_days_from_gregorian_date; + +// ==== Begin Time Constants ==== + +/// Milliseconds per day constant: 8.64e+7 +pub const MS_PER_DAY: u32 = 24 * 60 * 60 * 1000; +/// Seconds per day +pub const SECONDS_PER_DAY: i64 = 24 * 60 * 60; +/// Milliseconds per hour +pub const MS_PER_HOUR: i64 = 3_600_000; +/// Milliseconds per minute +pub const MS_PER_MINUTE: i64 = 60_000; + +// The weekday number for 1970-1-1 (Thursday) +const EPOCH_DAY_OF_WEEK_CONSTANT: i32 = 4; + +// ==== End Time Constants ==== + +// ==== Begin Date Equations ==== + +/// `EpochDaysToEpochMS` +/// +/// Functionally the same as Date's abstract operation `MakeDate` +pub fn epoch_days_to_epoch_ms(day: i64, time: i64) -> i64 { + (day * MS_PER_DAY as i64) + time +} + +/// `EpochTimeToDayNumber` +/// +/// This equation is the equivalent to `ECMAScript`'s `Date(t)` +pub fn epoch_time_to_day_number(t: i64) -> i32 { + t.div_euclid(MS_PER_DAY as i64) as i32 +} + +pub fn epoch_ms_to_ms_in_day(t: i64) -> u32 { + (t.rem_euclid(i64::from(MS_PER_DAY))) as u32 +} + +// https://tc39.es/proposal-temporal/#eqn-mathematicalinleapyear +pub fn is_leap(y: i32) -> bool { + if y % 4 != 0 { + false + } else if y % 4 == 0 && y % 100 != 0 { + true + } else if y % 100 == 0 && y % 400 != 0 { + false + } else { + // Assert that y is divisble by 400 to ensure we are returning the correct result. + assert_eq!(y % 400, 0); + true + } +} + +pub fn epoch_time_to_iso_year(t: i64) -> i32 { + let epoch_days = epoch_ms_to_epoch_days(t); + let (rata_die, shift_constant) = neri_schneider::rata_die_for_epoch_days(epoch_days); + neri_schneider::year(rata_die, shift_constant) +} + +/// Returns the Gregorian year containing the given epoch second. +pub fn epoch_seconds_to_iso_year(epoch_seconds: i64) -> i32 { + let epoch_days = epoch_seconds.div_euclid(SECONDS_PER_DAY) as i32; + let (rata_die, shift_constant) = neri_schneider::rata_die_for_epoch_days(epoch_days); + neri_schneider::year(rata_die, shift_constant) +} + +/// Returns the epoch day number for a given year. +pub fn epoch_days_for_year(y: i32) -> i32 { + 365 * (y - 1970) + (y - 1969).div_euclid(4) - (y - 1901).div_euclid(100) + + (y - 1601).div_euclid(400) +} + +pub const fn epoch_ms_to_epoch_days(ms: i64) -> i32 { + (ms.div_euclid(MS_PER_DAY as i64)) as i32 +} + +pub fn ymd_from_epoch_milliseconds(epoch_milliseconds: i64) -> (i32, u8, u8) { + let epoch_days = epoch_ms_to_epoch_days(epoch_milliseconds); + neri_schneider::ymd_from_epoch_days(epoch_days) +} + +/// Returns the (zero-indexed) day-of-year for the start of the given (zero-indexed) month. +/// +/// `m` of `12` returns the day-of-year for the end of the year (i.e. `365`/`366`), which is +/// useful for computing a month's length as `month_to_day(m + 1, leap) - month_to_day(m, leap)`. +pub fn month_to_day(m: u8, is_leap: bool) -> u16 { + let leap_day = u16::from(is_leap); + match m { + 0 => 0, + 1 => 31, + 2 => 59 + leap_day, + 3 => 90 + leap_day, + 4 => 120 + leap_day, + 5 => 151 + leap_day, + 6 => 181 + leap_day, + 7 => 212 + leap_day, + 8 => 243 + leap_day, + 9 => 273 + leap_day, + 10 => 304 + leap_day, + 11 => 334 + leap_day, + 12 => 365 + leap_day, + _ => unreachable!(), + } +} + +pub fn epoch_time_to_day_in_year(t: i64) -> i32 { + epoch_time_to_day_number(t) - (epoch_days_for_year(epoch_time_to_iso_year(t))) +} + +/// The day of the week (0 = Sunday .. 6 = Saturday) for a given epoch day number. +pub const fn epoch_days_to_week_day(epoch_days: i32) -> u8 { + (epoch_days + EPOCH_DAY_OF_WEEK_CONSTANT).rem_euclid(7) as u8 +} + +/// The day of the week (0 = Sunday .. 6 = Saturday) for a given epoch second. `epoch_seconds` +/// MUST be an exact multiple of [`SECONDS_PER_DAY`] (i.e. midnight UTC on some day). +pub fn epoch_seconds_to_day_of_week(epoch_seconds: i64) -> u8 { + epoch_days_to_week_day(epoch_seconds.div_euclid(SECONDS_PER_DAY) as i32) +} + +/// Converts an epoch day number to the epoch seconds at midnight UTC of that day. +pub const fn epoch_days_to_epoch_seconds(epoch_days: i32) -> i64 { + epoch_days as i64 * SECONDS_PER_DAY +} + +// ==== End Date Equations ==== + +// ==== Begin Calendar Equations ==== + +// NOTE: below was the iso methods in temporal::calendar -> Need to be reassessed. + +/// 12.2.31 `ISODaysInMonth ( year, month )` +/// +/// NOTE: month is 1 based +pub fn iso_days_in_month(year: i32, month: u8) -> u8 { + match month { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 => 28 + is_leap(year) as u8, + _ => unreachable!("ISODaysInMonth panicking is an implementation error."), + } +} + +// The below calendar abstract equations/utilities were removed for being unused. +// 12.2.32 `ToISOWeekOfYear ( year, month, day )` +// 12.2.33 `ISOMonthCode ( month )` +// 12.2.39 `ToISODayOfYear ( year, month, day )` +// 12.2.40 `ToISODayOfWeek ( year, month, day )` + +// ==== End Calendar Equations ==== + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn month_to_day_end_of_year_matches_next_month_start() { + assert_eq!(month_to_day(12, false), 365); + assert_eq!(month_to_day(12, true), 366); + } + + #[test] + fn epoch_days_to_week_day_matches_epoch_seconds_to_day_of_week() { + for epoch_days in [-100_000_001, -1, 0, 1, 100_000_001] { + let seconds = epoch_days_to_epoch_seconds(epoch_days); + assert_eq!( + epoch_days_to_week_day(epoch_days), + epoch_seconds_to_day_of_week(seconds) + ); + } + } +} diff --git a/crates/provider/src/utils/neri_schneider.rs b/crates/temporal_utils/src/neri_schneider.rs similarity index 93% rename from crates/provider/src/utils/neri_schneider.rs rename to crates/temporal_utils/src/neri_schneider.rs index 620c1784d..61ab8469d 100644 --- a/crates/provider/src/utils/neri_schneider.rs +++ b/crates/temporal_utils/src/neri_schneider.rs @@ -41,7 +41,6 @@ pub const EPOCH_COMPUTATIONAL_RATA_DIE: i32 = 719_468; pub const DAYS_IN_A_400Y_CYCLE: u32 = 146_097; -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] const TWO_POWER_THIRTY_NINE: u64 = 549_755_813_888; // 2^39 constant const TWO_POWER_THIRTY_TWO: u64 = 4_294_967_296; // 2^32 constant const TWO_POWER_SIXTEEN: u32 = 65_536; // 2^16 constant @@ -79,7 +78,6 @@ const fn rata_die_first_equations(year: i32, month: u8, day: u8) -> (u64, i64, i // Computational days to gregorian YMD // Determine j -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] const fn j(rata_die: u32) -> u32 { (computational_day_of_year(rata_die) >= 306) as u32 } @@ -88,7 +86,6 @@ const fn n_one(rata_die: u32) -> u32 { 4 * rata_die + 3 } -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] const fn n_two(rata_die: u32) -> u32 { century_rem(rata_die) | 3 } @@ -101,12 +98,10 @@ const fn first_equations(rata_die: u32) -> (u32, u32) { (century_num, century_rem) } -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] const fn century_rem(rata_die: u32) -> u32 { n_one(rata_die).rem_euclid(DAYS_IN_A_400Y_CYCLE) } -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] pub const fn century_number(rata_die: u32) -> u32 { n_one(rata_die).div_euclid(DAYS_IN_A_400Y_CYCLE) } @@ -135,24 +130,20 @@ const fn third_equations(rata_die: u32) -> (u32, u32, u32, u32) { } // Z -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] pub const fn computational_year_of_century(rata_die: u32) -> u64 { (376_287_347 * n_two(rata_die) as u64).div_euclid(TWO_POWER_THIRTY_NINE) } // N_y -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] pub const fn computational_day_of_year(rata_die: u32) -> u32 { (n_two(rata_die) - 1461 * computational_year_of_century(rata_die) as u32).div_euclid(4) } // Y -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] pub const fn computational_year(rata_die: u32) -> u32 { 100 * century_number(rata_die) + computational_year_of_century(rata_die) as u32 } -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] pub const fn year(computational_rata_die: u32, shift_constant: i32) -> i32 { (computational_year(computational_rata_die) + j(computational_rata_die)) as i32 - shift_constant } @@ -186,7 +177,6 @@ pub const fn ymd_from_epoch_days(epoch_days: i32) -> (i32, u8, u8) { } #[cfg(test)] -#[cfg(any(feature = "tzif", feature = "experimental_tzif"))] mod tests { use super::*; diff --git a/crates/zoneinfo/Cargo.toml b/crates/zoneinfo/Cargo.toml index 54392e4f4..4fe93d868 100644 --- a/crates/zoneinfo/Cargo.toml +++ b/crates/zoneinfo/Cargo.toml @@ -21,6 +21,7 @@ std = [] unstable = [] [dependencies] +temporal_utils = { workspace = true } hashbrown = "0.16.0" indexmap = "2.11.4" diff --git a/crates/zoneinfo/src/lib.rs b/crates/zoneinfo/src/lib.rs index a873c02c6..ed02fd069 100644 --- a/crates/zoneinfo/src/lib.rs +++ b/crates/zoneinfo/src/lib.rs @@ -47,8 +47,6 @@ extern crate std; #[cfg(feature = "std")] use std::{io, path::Path}; -pub(crate) mod utils; - pub mod compiler; pub mod parser; pub mod posix; diff --git a/crates/zoneinfo/src/posix.rs b/crates/zoneinfo/src/posix.rs index 66efe948a..64db63bbf 100644 --- a/crates/zoneinfo/src/posix.rs +++ b/crates/zoneinfo/src/posix.rs @@ -10,7 +10,6 @@ use crate::{ rule::{DayOfMonth, WeekDay}, Month, QualifiedTime, Sign, Time, }, - utils::month_to_day, zone::ZoneEntry, }; use alloc::string::String; @@ -148,11 +147,15 @@ impl PosixDate { pub(crate) fn from_rule(rule: &Rule) -> (Self, i64) { match rule.on_date { DayOfMonth::Day(day) if rule.in_month == Month::Jan || rule.in_month == Month::Feb => ( - PosixDate::JulianNoLeap(month_to_day(rule.in_month as u8, 1) as u16 + day as u16), + PosixDate::JulianNoLeap( + temporal_utils::month_to_day((rule.in_month as u8) - 1, true) + day as u16, + ), 0, ), DayOfMonth::Day(day) => ( - PosixDate::JulianLeap(month_to_day(rule.in_month as u8, 1) as u16 + day as u16), + PosixDate::JulianLeap( + temporal_utils::month_to_day((rule.in_month as u8) - 1, true) + day as u16, + ), 0, ), DayOfMonth::Last(wd) => ( diff --git a/crates/zoneinfo/src/rule.rs b/crates/zoneinfo/src/rule.rs index abdef4387..38d9994bf 100644 --- a/crates/zoneinfo/src/rule.rs +++ b/crates/zoneinfo/src/rule.rs @@ -12,7 +12,6 @@ use crate::{ rule::{DayOfMonth, ToYear}, Month, QualifiedTime, Time, }, - utils::{self, epoch_seconds_for_epoch_days}, }; #[derive(Debug)] @@ -120,7 +119,7 @@ impl Rules { } pub(crate) fn search_last_active_rule(&self, transition_point: i64) -> Option<&Rule> { - let transition_year = utils::year_from_epoch_seconds(transition_point); + let transition_year = temporal_utils::epoch_seconds_to_iso_year(transition_point); let mut best: (i64, Option<&Rule>) = (i64::MIN, None); for rule in &self.rules { @@ -143,7 +142,7 @@ impl Rules { // In practice this loop runs 1-2 iterations. for year in (from_year..=to_year).rev() { let epoch_days = epoch_days_for_rule_date(year, rule.in_month, rule.on_date); - let rule_secs = epoch_seconds_for_epoch_days(epoch_days); + let rule_secs = temporal_utils::epoch_days_to_epoch_seconds(epoch_days); if rule_secs < transition_point { if best.0 < rule_secs { best = (rule_secs, Some(rule)); @@ -224,7 +223,7 @@ impl Rule { saving: &Time, ) -> i64 { let epoch_days = epoch_days_for_rule_date(year, self.in_month, self.on_date); - let epoch_seconds = epoch_seconds_for_epoch_days(epoch_days); + let epoch_seconds = temporal_utils::epoch_days_to_epoch_seconds(epoch_days); epoch_seconds + self .at @@ -242,14 +241,14 @@ impl Rule { /// epoch_days_for_rule_date calculates the epoch days given values provided for a specific `Rule` pub(crate) fn epoch_days_for_rule_date(year: i32, month: Month, day_of_month: DayOfMonth) -> i32 { let day_of_year_for_month = month.month_start_to_day_of_year(year); - let epoch_days_for_year = utils::epoch_days_for_year(year); + let epoch_days_for_year = temporal_utils::epoch_days_for_year(year); let epoch_days = epoch_days_for_year + day_of_year_for_month; let day_of_month = match day_of_month { DayOfMonth::Last(weekday) => { let mut day_of_month = month.month_end_to_day_of_year(year) - day_of_year_for_month; loop { let target_days = epoch_days + day_of_month; - let target_week_day = utils::epoch_days_to_week_day(target_days); + let target_week_day = temporal_utils::epoch_days_to_week_day(target_days); if target_week_day == weekday as u8 { break; } @@ -261,7 +260,7 @@ pub(crate) fn epoch_days_for_rule_date(year: i32, month: Month, day_of_month: Da let mut day_of_month = d as i32 - 1; loop { let target_days = epoch_days + day_of_month; - let target_week_day = utils::epoch_days_to_week_day(target_days); + let target_week_day = temporal_utils::epoch_days_to_week_day(target_days); if week_day as u8 == target_week_day { break day_of_month; } @@ -272,7 +271,7 @@ pub(crate) fn epoch_days_for_rule_date(year: i32, month: Month, day_of_month: Da let mut day_of_month = d as i32 - 1; loop { let target_days = epoch_days + day_of_month; - let target_week_day = utils::epoch_days_to_week_day(target_days); + let target_week_day = temporal_utils::epoch_days_to_week_day(target_days); if week_day as u8 == target_week_day { break day_of_month; } diff --git a/crates/zoneinfo/src/types.rs b/crates/zoneinfo/src/types.rs index 4225ea18e..f11bdcea6 100644 --- a/crates/zoneinfo/src/types.rs +++ b/crates/zoneinfo/src/types.rs @@ -9,10 +9,7 @@ use alloc::borrow::ToOwned; -use crate::{ - parser::{ContextParse, LineParseContext, TryFromStr, ZoneInfoParseError}, - utils, -}; +use crate::parser::{ContextParse, LineParseContext, TryFromStr, ZoneInfoParseError}; pub mod rule; pub mod zone; @@ -45,12 +42,12 @@ pub enum Month { impl Month { /// Calculates the day of year for the start of the month pub(crate) fn month_start_to_day_of_year(self, year: i32) -> i32 { - utils::month_to_day(self as u8, utils::num_leap_days(year)) + temporal_utils::month_to_day((self as u8) - 1, temporal_utils::is_leap(year)) as i32 } /// Calculates the day of year for the end of the month pub(crate) fn month_end_to_day_of_year(self, year: i32) -> i32 { - utils::month_to_day(self as u8 + 1, utils::num_leap_days(year)) - 1 + temporal_utils::month_to_day(self as u8, temporal_utils::is_leap(year)) as i32 - 1 } } diff --git a/crates/zoneinfo/src/types/zone.rs b/crates/zoneinfo/src/types/zone.rs index f3bbd696b..cf01c94b1 100644 --- a/crates/zoneinfo/src/types/zone.rs +++ b/crates/zoneinfo/src/types/zone.rs @@ -8,7 +8,6 @@ use crate::{ parser::{next_split, ContextParse, LineParseContext, TryFromStr, ZoneInfoParseError}, rule::epoch_days_for_rule_date, types::{rule::DayOfMonth, Month, QualifiedTime, Time}, - utils, }; /// The value in the `NAME` column of a zone table that identifies the @@ -184,6 +183,6 @@ pub struct Date { impl Date { pub fn as_secs(&self) -> i64 { let epoch_days = epoch_days_for_rule_date(self.year, self.month, self.day); - utils::epoch_seconds_for_epoch_days(epoch_days) + temporal_utils::epoch_days_to_epoch_seconds(epoch_days) } } diff --git a/crates/zoneinfo/src/utils.rs b/crates/zoneinfo/src/utils.rs deleted file mode 100644 index 492b9295c..000000000 --- a/crates/zoneinfo/src/utils.rs +++ /dev/null @@ -1,84 +0,0 @@ -//! Utiltiy functions - -// TODO: potentially make time utils reusable - -pub const SECONDS_PER_DAY: i64 = 24 * 60 * 60; - -pub(crate) fn mathematical_days_in_year(y: i32) -> i32 { - if y % 4 != 0 { - 365 - } else if y % 4 == 0 && y % 100 != 0 { - 366 - } else if y % 100 == 0 && y % 400 != 0 { - 365 - } else { - // Assert that y is divisble by 400 to ensure we are returning the correct result. - assert_eq!(y % 400, 0); - 366 - } -} - -pub(crate) fn num_leap_days(year: i32) -> i32 { - mathematical_days_in_year(year) - 365 -} - -pub(crate) fn month_to_day(m: u8, leap_day: i32) -> i32 { - match m { - 1 => 0, - 2 => 31, - 3 => 59 + leap_day, - 4 => 90 + leap_day, - 5 => 120 + leap_day, - 6 => 151 + leap_day, - 7 => 181 + leap_day, - 8 => 212 + leap_day, - 9 => 243 + leap_day, - 10 => 273 + leap_day, - 11 => 304 + leap_day, - 12 => 334 + leap_day, - // Sort of hack to return end of month days - 13 => 365 + leap_day, - _ => unreachable!(), - } -} - -pub(crate) fn epoch_days_for_year(y: i32) -> i32 { - 365 * (y - 1970) + (y - 1969).div_euclid(4) - (y - 1901).div_euclid(100) - + (y - 1601).div_euclid(400) -} - -pub(crate) fn epoch_seconds_for_epoch_days(epoch_days: i32) -> i64 { - epoch_days as i64 * SECONDS_PER_DAY -} - -// The weekday number for 1970-1-1 -const EPOCH_DAY_OF_WEEK_CONSTANT: i32 = 4; - -pub(crate) fn epoch_days_to_week_day(epoch_days: i32) -> u8 { - // Wrapping here will be off by 1. (Sunday = 7; Mon = 1) - (epoch_days + EPOCH_DAY_OF_WEEK_CONSTANT).rem_euclid(7) as u8 -} - -/// Returns the calendar year containing the given epoch seconds. -/// Mirrors `timezone_provider::utils::epoch_time_to_iso_year` (Neri-Schneider algorithm), -/// adapted for seconds rather than milliseconds. -pub(crate) fn year_from_epoch_seconds(secs: i64) -> i32 { - const EPOCH_COMPUTATIONAL_RATA_DIE: i32 = 719_468; - const DAYS_IN_A_400Y_CYCLE: u32 = 146_097; - const SHIFT_CONSTANT: i32 = 3_670; - const TWO_POWER_THIRTY_NINE: u64 = 549_755_813_888; - - let epoch_days = secs.div_euclid(SECONDS_PER_DAY) as i32; - let rata_die = (epoch_days - + EPOCH_COMPUTATIONAL_RATA_DIE - + DAYS_IN_A_400Y_CYCLE as i32 * SHIFT_CONSTANT) as u32; - let shift_constant = 400 * SHIFT_CONSTANT; - let n1 = 4 * rata_die + 3; - let century = n1.div_euclid(DAYS_IN_A_400Y_CYCLE); - let n2 = n1.rem_euclid(DAYS_IN_A_400Y_CYCLE) | 3; - let century_year = (376_287_347_u64 * n2 as u64).div_euclid(TWO_POWER_THIRTY_NINE) as u32; - let comp_year = 100 * century + century_year; - let day_of_year = (n2 - 1461 * century_year).div_euclid(4); - let j = (day_of_year >= 306) as u32; - (comp_year + j) as i32 - shift_constant -} diff --git a/tools/depcheck/src/main.rs b/tools/depcheck/src/main.rs index 77a419b7c..7e0577919 100644 --- a/tools/depcheck/src/main.rs +++ b/tools/depcheck/src/main.rs @@ -156,6 +156,7 @@ pub const BASIC_RUNTIME_DEPS: &[&str] = &[ // temporal crates "temporal", "timezone_provider", + "temporal_utils", // ICU4X components and utils "calendrical_calculations", "core_maths",