Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs

This commit is contained in:
2026-09-15 10:41:00 -06:00
parent 6dc77e8eb0
commit a2b65bb47f
16427 changed files with 6972976 additions and 3 deletions
+253
View File
@@ -0,0 +1,253 @@
// This is a part of Chrono.
// See README.md and LICENSE.txt for details.
//! The time zone which has a fixed offset from UTC.
use core::fmt;
use core::str::FromStr;
#[cfg(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))]
use rkyv::{Archive, Deserialize, Serialize};
use super::{MappedLocalTime, Offset, TimeZone};
use crate::format::{OUT_OF_RANGE, ParseError, scan};
use crate::naive::{NaiveDate, NaiveDateTime};
/// The time zone with fixed offset, from UTC-23:59:59 to UTC+23:59:59.
///
/// Using the [`TimeZone`](./trait.TimeZone.html) methods
/// on a `FixedOffset` struct is the preferred way to construct
/// `DateTime<FixedOffset>` instances. See the [`east_opt`](#method.east_opt) and
/// [`west_opt`](#method.west_opt) methods for examples.
#[derive(PartialEq, Eq, Hash, Copy, Clone)]
#[cfg_attr(
any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"),
derive(Archive, Deserialize, Serialize),
archive(compare(PartialEq)),
archive_attr(derive(Clone, Copy, PartialEq, Eq, Hash, Debug))
)]
#[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
pub struct FixedOffset {
local_minus_utc: i32,
}
impl FixedOffset {
/// Makes a new `FixedOffset` for the Eastern Hemisphere with given timezone difference.
/// The negative `secs` means the Western Hemisphere.
///
/// Panics on the out-of-bound `secs`.
#[deprecated(since = "0.4.23", note = "use `east_opt()` instead")]
#[must_use]
pub fn east(secs: i32) -> FixedOffset {
FixedOffset::east_opt(secs).expect("FixedOffset::east out of bounds")
}
/// Makes a new `FixedOffset` for the Eastern Hemisphere with given timezone difference.
/// The negative `secs` means the Western Hemisphere.
///
/// Returns `None` on the out-of-bound `secs`.
///
/// # Example
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// use chrono::{FixedOffset, TimeZone};
/// let hour = 3600;
/// let datetime =
/// FixedOffset::east_opt(5 * hour).unwrap().with_ymd_and_hms(2016, 11, 08, 0, 0, 0).unwrap();
/// assert_eq!(&datetime.to_rfc3339(), "2016-11-08T00:00:00+05:00")
/// # }
/// ```
#[must_use]
pub const fn east_opt(secs: i32) -> Option<FixedOffset> {
if -86_400 < secs && secs < 86_400 {
Some(FixedOffset { local_minus_utc: secs })
} else {
None
}
}
/// Makes a new `FixedOffset` for the Western Hemisphere with given timezone difference.
/// The negative `secs` means the Eastern Hemisphere.
///
/// Panics on the out-of-bound `secs`.
#[deprecated(since = "0.4.23", note = "use `west_opt()` instead")]
#[must_use]
pub fn west(secs: i32) -> FixedOffset {
FixedOffset::west_opt(secs).expect("FixedOffset::west out of bounds")
}
/// Makes a new `FixedOffset` for the Western Hemisphere with given timezone difference.
/// The negative `secs` means the Eastern Hemisphere.
///
/// Returns `None` on the out-of-bound `secs`.
///
/// # Example
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// use chrono::{FixedOffset, TimeZone};
/// let hour = 3600;
/// let datetime =
/// FixedOffset::west_opt(5 * hour).unwrap().with_ymd_and_hms(2016, 11, 08, 0, 0, 0).unwrap();
/// assert_eq!(&datetime.to_rfc3339(), "2016-11-08T00:00:00-05:00")
/// # }
/// ```
#[must_use]
pub const fn west_opt(secs: i32) -> Option<FixedOffset> {
if -86_400 < secs && secs < 86_400 {
Some(FixedOffset { local_minus_utc: -secs })
} else {
None
}
}
/// Returns the number of seconds to add to convert from UTC to the local time.
#[inline]
pub const fn local_minus_utc(&self) -> i32 {
self.local_minus_utc
}
/// Returns the number of seconds to add to convert from the local time to UTC.
#[inline]
pub const fn utc_minus_local(&self) -> i32 {
-self.local_minus_utc
}
}
/// Parsing a `str` into a `FixedOffset` uses the format [`%z`](crate::format::strftime).
impl FromStr for FixedOffset {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (_, offset) = scan::timezone_offset(s, scan::colon_or_space, false, false, true)?;
Self::east_opt(offset).ok_or(OUT_OF_RANGE)
}
}
impl TimeZone for FixedOffset {
type Offset = FixedOffset;
fn from_offset(offset: &FixedOffset) -> FixedOffset {
*offset
}
fn offset_from_local_date(&self, _local: &NaiveDate) -> MappedLocalTime<FixedOffset> {
MappedLocalTime::Single(*self)
}
fn offset_from_local_datetime(&self, _local: &NaiveDateTime) -> MappedLocalTime<FixedOffset> {
MappedLocalTime::Single(*self)
}
fn offset_from_utc_date(&self, _utc: &NaiveDate) -> FixedOffset {
*self
}
fn offset_from_utc_datetime(&self, _utc: &NaiveDateTime) -> FixedOffset {
*self
}
}
impl Offset for FixedOffset {
fn fix(&self) -> FixedOffset {
*self
}
}
impl fmt::Debug for FixedOffset {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let offset = self.local_minus_utc;
let (sign, offset) = if offset < 0 { ('-', -offset) } else { ('+', offset) };
let sec = offset.rem_euclid(60);
let mins = offset.div_euclid(60);
let min = mins.rem_euclid(60);
let hour = mins.div_euclid(60);
if sec == 0 {
write!(f, "{sign}{hour:02}:{min:02}")
} else {
write!(f, "{sign}{hour:02}:{min:02}:{sec:02}")
}
}
}
impl fmt::Display for FixedOffset {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
#[cfg(feature = "defmt")]
impl defmt::Format for FixedOffset {
fn format(&self, f: defmt::Formatter) {
let offset = self.local_minus_utc;
let (sign, offset) = if offset < 0 { ('-', -offset) } else { ('+', offset) };
let sec = offset.rem_euclid(60);
let mins = offset.div_euclid(60);
let min = mins.rem_euclid(60);
let hour = mins.div_euclid(60);
if sec == 0 {
defmt::write!(f, "{}{:02}:{:02}", sign, hour, min)
} else {
defmt::write!(f, "{}{:02}:{:02}:{:02}", sign, hour, min, sec)
}
}
}
#[cfg(all(feature = "arbitrary", feature = "std"))]
impl arbitrary::Arbitrary<'_> for FixedOffset {
fn arbitrary(u: &mut arbitrary::Unstructured) -> arbitrary::Result<FixedOffset> {
let secs = u.int_in_range(-86_399..=86_399)?;
let fixed_offset = FixedOffset::east_opt(secs)
.expect("Could not generate a valid chrono::FixedOffset. It looks like implementation of Arbitrary for FixedOffset is erroneous.");
Ok(fixed_offset)
}
}
#[cfg(test)]
mod tests {
use super::FixedOffset;
use crate::offset::TimeZone;
use std::str::FromStr;
#[test]
fn test_date_extreme_offset() {
// starting from 0.3 we don't have an offset exceeding one day.
// this makes everything easier!
let offset = FixedOffset::east_opt(86399).unwrap();
assert_eq!(
format!("{:?}", offset.with_ymd_and_hms(2012, 2, 29, 5, 6, 7).unwrap()),
"2012-02-29T05:06:07+23:59:59"
);
let offset = FixedOffset::east_opt(-86399).unwrap();
assert_eq!(
format!("{:?}", offset.with_ymd_and_hms(2012, 2, 29, 5, 6, 7).unwrap()),
"2012-02-29T05:06:07-23:59:59"
);
let offset = FixedOffset::west_opt(86399).unwrap();
assert_eq!(
format!("{:?}", offset.with_ymd_and_hms(2012, 3, 4, 5, 6, 7).unwrap()),
"2012-03-04T05:06:07-23:59:59"
);
let offset = FixedOffset::west_opt(-86399).unwrap();
assert_eq!(
format!("{:?}", offset.with_ymd_and_hms(2012, 3, 4, 5, 6, 7).unwrap()),
"2012-03-04T05:06:07+23:59:59"
);
}
#[test]
fn test_parse_offset() {
let offset = FixedOffset::from_str("-0500").unwrap();
assert_eq!(offset.local_minus_utc, -5 * 3600);
let offset = FixedOffset::from_str("-08:00").unwrap();
assert_eq!(offset.local_minus_utc, -8 * 3600);
let offset = FixedOffset::from_str("+06:30").unwrap();
assert_eq!(offset.local_minus_utc, (6 * 3600) + 1800);
}
#[test]
#[cfg(feature = "rkyv-validation")]
fn test_rkyv_validation() {
let offset = FixedOffset::from_str("-0500").unwrap();
let bytes = rkyv::to_bytes::<_, 4>(&offset).unwrap();
assert_eq!(rkyv::from_bytes::<FixedOffset>(&bytes).unwrap(), offset);
}
}
+543
View File
@@ -0,0 +1,543 @@
// This is a part of Chrono.
// See README.md and LICENSE.txt for details.
//! The local (system) time zone.
#[cfg(windows)]
use std::cmp::Ordering;
#[cfg(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))]
use rkyv::{Archive, Deserialize, Serialize};
use super::fixed::FixedOffset;
use super::{MappedLocalTime, TimeZone};
#[allow(deprecated)]
use crate::Date;
use crate::naive::{NaiveDate, NaiveDateTime, NaiveTime};
use crate::{DateTime, Utc};
#[cfg(unix)]
#[path = "unix.rs"]
mod inner;
#[cfg(windows)]
#[path = "windows.rs"]
mod inner;
#[cfg(all(windows, feature = "clock"))]
#[allow(unreachable_pub)]
mod win_bindings;
#[cfg(all(any(target_os = "android", target_env = "ohos", test), feature = "clock"))]
mod tz_data;
#[cfg(all(
not(unix),
not(windows),
not(all(
target_arch = "wasm32",
feature = "wasmbind",
not(any(target_os = "emscripten", target_os = "wasi"))
))
))]
mod inner {
use crate::{FixedOffset, MappedLocalTime, NaiveDateTime};
pub(super) fn offset_from_utc_datetime(
_utc_time: &NaiveDateTime,
) -> MappedLocalTime<FixedOffset> {
MappedLocalTime::Single(FixedOffset::east_opt(0).unwrap())
}
pub(super) fn offset_from_local_datetime(
_local_time: &NaiveDateTime,
) -> MappedLocalTime<FixedOffset> {
MappedLocalTime::Single(FixedOffset::east_opt(0).unwrap())
}
}
#[cfg(all(
target_arch = "wasm32",
feature = "wasmbind",
not(any(target_os = "emscripten", target_os = "wasi", target_os = "linux"))
))]
mod inner {
use crate::{Datelike, FixedOffset, MappedLocalTime, NaiveDateTime, Timelike};
pub(super) fn offset_from_utc_datetime(utc: &NaiveDateTime) -> MappedLocalTime<FixedOffset> {
let offset = js_sys::Date::from(utc.and_utc()).get_timezone_offset();
MappedLocalTime::Single(FixedOffset::west_opt((offset as i32) * 60).unwrap())
}
pub(super) fn offset_from_local_datetime(
local: &NaiveDateTime,
) -> MappedLocalTime<FixedOffset> {
let mut year = local.year();
if year < 100 {
// The API in `js_sys` does not let us create a `Date` with negative years.
// And values for years from `0` to `99` map to the years `1900` to `1999`.
// Shift the value by a multiple of 400 years until it is `>= 100`.
let shift_cycles = (year - 100).div_euclid(400);
year -= shift_cycles * 400;
}
let js_date = js_sys::Date::new_with_year_month_day_hr_min_sec(
year as u32,
local.month0() as i32,
local.day() as i32,
local.hour() as i32,
local.minute() as i32,
local.second() as i32,
// ignore milliseconds, our representation of leap seconds may be problematic
);
let offset = js_date.get_timezone_offset();
// We always get a result, even if this time does not exist or is ambiguous.
MappedLocalTime::Single(FixedOffset::west_opt((offset as i32) * 60).unwrap())
}
}
#[cfg(unix)]
mod tz_info;
/// The local timescale.
///
/// Using the [`TimeZone`](./trait.TimeZone.html) methods
/// on the Local struct is the preferred way to construct `DateTime<Local>`
/// instances.
///
/// # Example
///
/// ```
/// use chrono::{DateTime, Local, TimeZone};
///
/// let dt1: DateTime<Local> = Local::now();
/// let dt2: DateTime<Local> = Local.timestamp_opt(0, 0).unwrap();
/// assert!(dt1 >= dt2);
/// ```
#[derive(Copy, Clone, Debug)]
#[cfg_attr(
any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"),
derive(Archive, Deserialize, Serialize),
archive(compare(PartialEq)),
archive_attr(derive(Clone, Copy, Debug))
)]
#[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Local;
impl Local {
/// Returns a `Date` which corresponds to the current date.
#[deprecated(since = "0.4.23", note = "use `Local::now()` instead")]
#[allow(deprecated)]
#[must_use]
pub fn today() -> Date<Local> {
Local::now().date()
}
/// Returns a `DateTime<Local>` which corresponds to the current date, time and offset from
/// UTC.
///
/// See also the similar [`Utc::now()`] which returns `DateTime<Utc>`, i.e. without the local
/// offset.
///
/// # Example
///
/// ```
/// # #![allow(unused_variables)]
/// # use chrono::{DateTime, FixedOffset, Local};
/// // Current local time
/// let now = Local::now();
///
/// // Current local date
/// let today = now.date_naive();
///
/// // Current local time, converted to `DateTime<FixedOffset>`
/// let now_fixed_offset = Local::now().fixed_offset();
/// // or
/// let now_fixed_offset: DateTime<FixedOffset> = Local::now().into();
///
/// // Current time in some timezone (let's use +05:00)
/// // Note that it is usually more efficient to use `Utc::now` for this use case.
/// let offset = FixedOffset::east_opt(5 * 60 * 60).unwrap();
/// let now_with_offset = Local::now().with_timezone(&offset);
/// ```
pub fn now() -> DateTime<Local> {
Utc::now().with_timezone(&Local)
}
}
impl TimeZone for Local {
type Offset = FixedOffset;
fn from_offset(_offset: &FixedOffset) -> Local {
Local
}
#[allow(deprecated)]
fn offset_from_local_date(&self, local: &NaiveDate) -> MappedLocalTime<FixedOffset> {
// Get the offset at local midnight.
self.offset_from_local_datetime(&local.and_time(NaiveTime::MIN))
}
fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> MappedLocalTime<FixedOffset> {
inner::offset_from_local_datetime(local)
}
#[allow(deprecated)]
fn offset_from_utc_date(&self, utc: &NaiveDate) -> FixedOffset {
// Get the offset at midnight.
self.offset_from_utc_datetime(&utc.and_time(NaiveTime::MIN))
}
fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> FixedOffset {
inner::offset_from_utc_datetime(utc).unwrap()
}
}
#[cfg(windows)]
#[derive(Copy, Clone, Eq, PartialEq)]
struct Transition {
transition_utc: NaiveDateTime,
offset_before: FixedOffset,
offset_after: FixedOffset,
}
#[cfg(windows)]
impl Transition {
fn new(
transition_local: NaiveDateTime,
offset_before: FixedOffset,
offset_after: FixedOffset,
) -> Transition {
// It is no problem if the transition time in UTC falls a couple of hours inside the buffer
// space around the `NaiveDateTime` range (although it is very theoretical to have a
// transition at midnight around `NaiveDate::(MIN|MAX)`.
let transition_utc = transition_local.overflowing_sub_offset(offset_before);
Transition { transition_utc, offset_before, offset_after }
}
}
#[cfg(windows)]
impl PartialOrd for Transition {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[cfg(windows)]
impl Ord for Transition {
fn cmp(&self, other: &Self) -> Ordering {
self.transition_utc.cmp(&other.transition_utc)
}
}
// Calculate the time in UTC given a local time and transitions.
// `transitions` must be sorted.
#[cfg(windows)]
fn lookup_with_dst_transitions(
transitions: &[Transition],
dt: NaiveDateTime,
) -> MappedLocalTime<FixedOffset> {
for t in transitions.iter() {
// A transition can result in the wall clock time going forward (creating a gap) or going
// backward (creating a fold). We are interested in the earliest and latest wall time of the
// transition, as this are the times between which `dt` does may not exist or is ambiguous.
//
// It is no problem if the transition times falls a couple of hours inside the buffer
// space around the `NaiveDateTime` range (although it is very theoretical to have a
// transition at midnight around `NaiveDate::(MIN|MAX)`.
let (offset_min, offset_max) =
match t.offset_after.local_minus_utc() > t.offset_before.local_minus_utc() {
true => (t.offset_before, t.offset_after),
false => (t.offset_after, t.offset_before),
};
let wall_earliest = t.transition_utc.overflowing_add_offset(offset_min);
let wall_latest = t.transition_utc.overflowing_add_offset(offset_max);
if dt < wall_earliest {
return MappedLocalTime::Single(t.offset_before);
} else if dt <= wall_latest {
return match t.offset_after.local_minus_utc().cmp(&t.offset_before.local_minus_utc()) {
Ordering::Equal => MappedLocalTime::Single(t.offset_before),
Ordering::Less => MappedLocalTime::Ambiguous(t.offset_before, t.offset_after),
Ordering::Greater => {
if dt == wall_earliest {
MappedLocalTime::Single(t.offset_before)
} else if dt == wall_latest {
MappedLocalTime::Single(t.offset_after)
} else {
MappedLocalTime::None
}
}
};
}
}
MappedLocalTime::Single(transitions.last().unwrap().offset_after)
}
#[cfg(test)]
mod tests {
use super::Local;
use crate::offset::TimeZone;
#[cfg(windows)]
use crate::offset::local::{Transition, lookup_with_dst_transitions};
use crate::{Datelike, Days, Utc};
#[cfg(windows)]
use crate::{FixedOffset, MappedLocalTime, NaiveDate, NaiveDateTime};
#[test]
fn verify_correct_offsets() {
let now = Local::now();
let from_local = Local.from_local_datetime(&now.naive_local()).unwrap();
let from_utc = Local.from_utc_datetime(&now.naive_utc());
assert_eq!(now.offset().local_minus_utc(), from_local.offset().local_minus_utc());
assert_eq!(now.offset().local_minus_utc(), from_utc.offset().local_minus_utc());
assert_eq!(now, from_local);
assert_eq!(now, from_utc);
}
#[test]
fn verify_correct_offsets_distant_past() {
let distant_past = Local::now() - Days::new(365 * 500);
let from_local = Local.from_local_datetime(&distant_past.naive_local()).unwrap();
let from_utc = Local.from_utc_datetime(&distant_past.naive_utc());
assert_eq!(distant_past.offset().local_minus_utc(), from_local.offset().local_minus_utc());
assert_eq!(distant_past.offset().local_minus_utc(), from_utc.offset().local_minus_utc());
assert_eq!(distant_past, from_local);
assert_eq!(distant_past, from_utc);
}
#[test]
fn verify_correct_offsets_distant_future() {
let distant_future = Local::now() + Days::new(365 * 35000);
let from_local = Local.from_local_datetime(&distant_future.naive_local()).unwrap();
let from_utc = Local.from_utc_datetime(&distant_future.naive_utc());
assert_eq!(
distant_future.offset().local_minus_utc(),
from_local.offset().local_minus_utc()
);
assert_eq!(distant_future.offset().local_minus_utc(), from_utc.offset().local_minus_utc());
assert_eq!(distant_future, from_local);
assert_eq!(distant_future, from_utc);
}
#[test]
fn test_local_date_sanity_check() {
// issue #27
assert_eq!(Local.with_ymd_and_hms(2999, 12, 28, 0, 0, 0).unwrap().day(), 28);
}
#[test]
fn test_leap_second() {
// issue #123
let today = Utc::now().date_naive();
if let Some(dt) = today.and_hms_milli_opt(15, 2, 59, 1000) {
let timestr = dt.time().to_string();
// the OS API may or may not support the leap second,
// but there are only two sensible options.
assert!(
timestr == "15:02:60" || timestr == "15:03:00",
"unexpected timestr {timestr:?}"
);
}
if let Some(dt) = today.and_hms_milli_opt(15, 2, 3, 1234) {
let timestr = dt.time().to_string();
assert!(
timestr == "15:02:03.234" || timestr == "15:02:04.234",
"unexpected timestr {timestr:?}"
);
}
}
#[test]
#[cfg(windows)]
fn test_lookup_with_dst_transitions() {
let ymdhms = |y, m, d, h, n, s| {
NaiveDate::from_ymd_opt(y, m, d).unwrap().and_hms_opt(h, n, s).unwrap()
};
#[track_caller]
#[allow(clippy::too_many_arguments)]
fn compare_lookup(
transitions: &[Transition],
y: i32,
m: u32,
d: u32,
h: u32,
n: u32,
s: u32,
result: MappedLocalTime<FixedOffset>,
) {
let dt = NaiveDate::from_ymd_opt(y, m, d).unwrap().and_hms_opt(h, n, s).unwrap();
assert_eq!(lookup_with_dst_transitions(transitions, dt), result);
}
// dst transition before std transition
// dst offset > std offset
let std = FixedOffset::east_opt(3 * 60 * 60).unwrap();
let dst = FixedOffset::east_opt(4 * 60 * 60).unwrap();
let transitions = [
Transition::new(ymdhms(2023, 3, 26, 2, 0, 0), std, dst),
Transition::new(ymdhms(2023, 10, 29, 3, 0, 0), dst, std),
];
compare_lookup(&transitions, 2023, 3, 26, 1, 0, 0, MappedLocalTime::Single(std));
compare_lookup(&transitions, 2023, 3, 26, 2, 0, 0, MappedLocalTime::Single(std));
compare_lookup(&transitions, 2023, 3, 26, 2, 30, 0, MappedLocalTime::None);
compare_lookup(&transitions, 2023, 3, 26, 3, 0, 0, MappedLocalTime::Single(dst));
compare_lookup(&transitions, 2023, 3, 26, 4, 0, 0, MappedLocalTime::Single(dst));
compare_lookup(&transitions, 2023, 10, 29, 1, 0, 0, MappedLocalTime::Single(dst));
compare_lookup(&transitions, 2023, 10, 29, 2, 0, 0, MappedLocalTime::Ambiguous(dst, std));
compare_lookup(&transitions, 2023, 10, 29, 2, 30, 0, MappedLocalTime::Ambiguous(dst, std));
compare_lookup(&transitions, 2023, 10, 29, 3, 0, 0, MappedLocalTime::Ambiguous(dst, std));
compare_lookup(&transitions, 2023, 10, 29, 4, 0, 0, MappedLocalTime::Single(std));
// std transition before dst transition
// dst offset > std offset
let std = FixedOffset::east_opt(-5 * 60 * 60).unwrap();
let dst = FixedOffset::east_opt(-4 * 60 * 60).unwrap();
let transitions = [
Transition::new(ymdhms(2023, 3, 24, 3, 0, 0), dst, std),
Transition::new(ymdhms(2023, 10, 27, 2, 0, 0), std, dst),
];
compare_lookup(&transitions, 2023, 3, 24, 1, 0, 0, MappedLocalTime::Single(dst));
compare_lookup(&transitions, 2023, 3, 24, 2, 0, 0, MappedLocalTime::Ambiguous(dst, std));
compare_lookup(&transitions, 2023, 3, 24, 2, 30, 0, MappedLocalTime::Ambiguous(dst, std));
compare_lookup(&transitions, 2023, 3, 24, 3, 0, 0, MappedLocalTime::Ambiguous(dst, std));
compare_lookup(&transitions, 2023, 3, 24, 4, 0, 0, MappedLocalTime::Single(std));
compare_lookup(&transitions, 2023, 10, 27, 1, 0, 0, MappedLocalTime::Single(std));
compare_lookup(&transitions, 2023, 10, 27, 2, 0, 0, MappedLocalTime::Single(std));
compare_lookup(&transitions, 2023, 10, 27, 2, 30, 0, MappedLocalTime::None);
compare_lookup(&transitions, 2023, 10, 27, 3, 0, 0, MappedLocalTime::Single(dst));
compare_lookup(&transitions, 2023, 10, 27, 4, 0, 0, MappedLocalTime::Single(dst));
// dst transition before std transition
// dst offset < std offset
let std = FixedOffset::east_opt(3 * 60 * 60).unwrap();
let dst = FixedOffset::east_opt((2 * 60 + 30) * 60).unwrap();
let transitions = [
Transition::new(ymdhms(2023, 3, 26, 2, 30, 0), std, dst),
Transition::new(ymdhms(2023, 10, 29, 2, 0, 0), dst, std),
];
compare_lookup(&transitions, 2023, 3, 26, 1, 0, 0, MappedLocalTime::Single(std));
compare_lookup(&transitions, 2023, 3, 26, 2, 0, 0, MappedLocalTime::Ambiguous(std, dst));
compare_lookup(&transitions, 2023, 3, 26, 2, 15, 0, MappedLocalTime::Ambiguous(std, dst));
compare_lookup(&transitions, 2023, 3, 26, 2, 30, 0, MappedLocalTime::Ambiguous(std, dst));
compare_lookup(&transitions, 2023, 3, 26, 3, 0, 0, MappedLocalTime::Single(dst));
compare_lookup(&transitions, 2023, 10, 29, 1, 0, 0, MappedLocalTime::Single(dst));
compare_lookup(&transitions, 2023, 10, 29, 2, 0, 0, MappedLocalTime::Single(dst));
compare_lookup(&transitions, 2023, 10, 29, 2, 15, 0, MappedLocalTime::None);
compare_lookup(&transitions, 2023, 10, 29, 2, 30, 0, MappedLocalTime::Single(std));
compare_lookup(&transitions, 2023, 10, 29, 3, 0, 0, MappedLocalTime::Single(std));
// std transition before dst transition
// dst offset < std offset
let std = FixedOffset::east_opt(-(4 * 60 + 30) * 60).unwrap();
let dst = FixedOffset::east_opt(-5 * 60 * 60).unwrap();
let transitions = [
Transition::new(ymdhms(2023, 3, 24, 2, 0, 0), dst, std),
Transition::new(ymdhms(2023, 10, 27, 2, 30, 0), std, dst),
];
compare_lookup(&transitions, 2023, 3, 24, 1, 0, 0, MappedLocalTime::Single(dst));
compare_lookup(&transitions, 2023, 3, 24, 2, 0, 0, MappedLocalTime::Single(dst));
compare_lookup(&transitions, 2023, 3, 24, 2, 15, 0, MappedLocalTime::None);
compare_lookup(&transitions, 2023, 3, 24, 2, 30, 0, MappedLocalTime::Single(std));
compare_lookup(&transitions, 2023, 3, 24, 3, 0, 0, MappedLocalTime::Single(std));
compare_lookup(&transitions, 2023, 10, 27, 1, 0, 0, MappedLocalTime::Single(std));
compare_lookup(&transitions, 2023, 10, 27, 2, 0, 0, MappedLocalTime::Ambiguous(std, dst));
compare_lookup(&transitions, 2023, 10, 27, 2, 15, 0, MappedLocalTime::Ambiguous(std, dst));
compare_lookup(&transitions, 2023, 10, 27, 2, 30, 0, MappedLocalTime::Ambiguous(std, dst));
compare_lookup(&transitions, 2023, 10, 27, 3, 0, 0, MappedLocalTime::Single(dst));
// offset stays the same
let std = FixedOffset::east_opt(3 * 60 * 60).unwrap();
let transitions = [
Transition::new(ymdhms(2023, 3, 26, 2, 0, 0), std, std),
Transition::new(ymdhms(2023, 10, 29, 3, 0, 0), std, std),
];
compare_lookup(&transitions, 2023, 3, 26, 2, 0, 0, MappedLocalTime::Single(std));
compare_lookup(&transitions, 2023, 10, 29, 3, 0, 0, MappedLocalTime::Single(std));
// single transition
let std = FixedOffset::east_opt(3 * 60 * 60).unwrap();
let dst = FixedOffset::east_opt(4 * 60 * 60).unwrap();
let transitions = [Transition::new(ymdhms(2023, 3, 26, 2, 0, 0), std, dst)];
compare_lookup(&transitions, 2023, 3, 26, 1, 0, 0, MappedLocalTime::Single(std));
compare_lookup(&transitions, 2023, 3, 26, 2, 0, 0, MappedLocalTime::Single(std));
compare_lookup(&transitions, 2023, 3, 26, 2, 30, 0, MappedLocalTime::None);
compare_lookup(&transitions, 2023, 3, 26, 3, 0, 0, MappedLocalTime::Single(dst));
compare_lookup(&transitions, 2023, 3, 26, 4, 0, 0, MappedLocalTime::Single(dst));
}
#[test]
#[cfg(windows)]
fn test_lookup_with_dst_transitions_limits() {
// Transition beyond UTC year end doesn't panic in year of `NaiveDate::MAX`
let std = FixedOffset::east_opt(3 * 60 * 60).unwrap();
let dst = FixedOffset::east_opt(4 * 60 * 60).unwrap();
let transitions = [
Transition::new(NaiveDateTime::MAX.with_month(7).unwrap(), std, dst),
Transition::new(NaiveDateTime::MAX, dst, std),
];
assert_eq!(
lookup_with_dst_transitions(&transitions, NaiveDateTime::MAX.with_month(3).unwrap()),
MappedLocalTime::Single(std)
);
assert_eq!(
lookup_with_dst_transitions(&transitions, NaiveDateTime::MAX.with_month(8).unwrap()),
MappedLocalTime::Single(dst)
);
// Doesn't panic with `NaiveDateTime::MAX` as argument (which would be out of range when
// converted to UTC).
assert_eq!(
lookup_with_dst_transitions(&transitions, NaiveDateTime::MAX),
MappedLocalTime::Ambiguous(dst, std)
);
// Transition before UTC year end doesn't panic in year of `NaiveDate::MIN`
let std = FixedOffset::west_opt(3 * 60 * 60).unwrap();
let dst = FixedOffset::west_opt(4 * 60 * 60).unwrap();
let transitions = [
Transition::new(NaiveDateTime::MIN, std, dst),
Transition::new(NaiveDateTime::MIN.with_month(6).unwrap(), dst, std),
];
assert_eq!(
lookup_with_dst_transitions(&transitions, NaiveDateTime::MIN.with_month(3).unwrap()),
MappedLocalTime::Single(dst)
);
assert_eq!(
lookup_with_dst_transitions(&transitions, NaiveDateTime::MIN.with_month(8).unwrap()),
MappedLocalTime::Single(std)
);
// Doesn't panic with `NaiveDateTime::MIN` as argument (which would be out of range when
// converted to UTC).
assert_eq!(
lookup_with_dst_transitions(&transitions, NaiveDateTime::MIN),
MappedLocalTime::Ambiguous(std, dst)
);
}
#[test]
#[cfg(feature = "rkyv-validation")]
fn test_rkyv_validation() {
let local = Local;
// Local is a ZST and serializes to 0 bytes
let bytes = rkyv::to_bytes::<_, 0>(&local).unwrap();
assert_eq!(bytes.len(), 0);
// but is deserialized to an archived variant without a
// wrapping object
assert_eq!(rkyv::from_bytes::<Local>(&bytes).unwrap(), super::ArchivedLocal);
}
}
+272
View File
@@ -0,0 +1,272 @@
//! Rust parser of ZoneInfoDb(`tzdata`) on Android and OpenHarmony
//!
//! Ported from: https://android.googlesource.com/platform/prebuilts/fullsdk/sources/+/refs/heads/androidx-appcompat-release/android-34/com/android/i18n/timezone/ZoneInfoDb.java
use std::{
ffi::CStr,
fmt::Debug,
fs::File,
io::{Error, ErrorKind, Read, Result, Seek, SeekFrom},
};
/// Get timezone data from the `tzdata` file of HarmonyOS NEXT.
#[cfg(target_env = "ohos")]
pub(crate) fn for_zone(tz_string: &str) -> Result<Option<Vec<u8>>> {
let mut file = File::open("/system/etc/zoneinfo/tzdata")?;
find_tz_data::<OHOS_ENTRY_LEN>(&mut file, tz_string.as_bytes())
}
/// Get timezone data from the `tzdata` file of Android.
#[cfg(target_os = "android")]
pub(crate) fn for_zone(tz_string: &str) -> Result<Option<Vec<u8>>> {
let mut file = open_android_tz_data_file()?;
find_tz_data::<ANDROID_ENTRY_LEN>(&mut file, tz_string.as_bytes())
}
/// Open the `tzdata` file of Android from the environment variables.
#[cfg(target_os = "android")]
fn open_android_tz_data_file() -> Result<File> {
for (env_var, path) in [
// Default root path: /apex/com.android.tzdata
("ANDROID_TZDATA_ROOT", "/etc/tz"),
// Default root path: /data
("ANDROID_DATA", "/misc/zoneinfo/current"),
// Default root path: /system
("ANDROID_ROOT", "/usr/share/zoneinfo"),
] {
if let Ok(env_value) = std::env::var(env_var) {
if let Ok(file) = File::open(format!("{}{}/tzdata", env_value, path)) {
return Ok(file);
}
}
}
Err(Error::from(ErrorKind::NotFound))
}
/// Get timezone data from the `tzdata` file reader
#[cfg(any(test, target_env = "ohos", target_os = "android"))]
fn find_tz_data<const ENTRY_LEN: usize>(
mut reader: impl Read + Seek,
tz_name: &[u8],
) -> Result<Option<Vec<u8>>> {
let header = TzDataHeader::new(&mut reader)?;
let index = TzDataIndexes::new::<ENTRY_LEN>(&mut reader, &header)?;
Ok(if let Some(entry) = index.find_timezone(tz_name) {
Some(index.find_tzdata(reader, &header, entry)?)
} else {
None
})
}
/// Header of the `tzdata` file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct TzDataHeader {
version: [u8; 5],
index_offset: u32,
data_offset: u32,
zonetab_offset: u32,
}
impl TzDataHeader {
/// Parse the header of the `tzdata` file.
fn new(mut data: impl Read) -> Result<Self> {
let version = {
let mut magic = [0; TZDATA_VERSION_LEN];
data.read_exact(&mut magic)?;
if !magic.starts_with(b"tzdata") || magic[TZDATA_VERSION_LEN - 1] != 0 {
return Err(Error::new(ErrorKind::Other, "invalid tzdata header magic"));
}
let mut version = [0; 5];
version.copy_from_slice(&magic[6..11]);
version
};
let mut offset = [0; 4];
data.read_exact(&mut offset)?;
let index_offset = u32::from_be_bytes(offset);
data.read_exact(&mut offset)?;
let data_offset = u32::from_be_bytes(offset);
data.read_exact(&mut offset)?;
let zonetab_offset = u32::from_be_bytes(offset);
Ok(Self { version, index_offset, data_offset, zonetab_offset })
}
}
/// Indexes of the `tzdata` file.
struct TzDataIndexes {
indexes: Vec<TzDataIndex>,
}
impl TzDataIndexes {
/// Create a new `TzDataIndexes` from the `tzdata` file reader.
fn new<const ENTRY_LEN: usize>(mut reader: impl Read, header: &TzDataHeader) -> Result<Self> {
let mut buf = vec![0; header.data_offset.saturating_sub(header.index_offset) as usize];
reader.read_exact(&mut buf)?;
// replace chunks with array_chunks when it's stable
Ok(TzDataIndexes {
indexes: buf
.chunks(ENTRY_LEN)
.filter_map(|chunk| {
from_bytes_until_nul(&chunk[..TZ_NAME_LEN]).map(|name| {
let name = name.to_bytes().to_vec().into_boxed_slice();
let offset = u32::from_be_bytes(
chunk[TZ_NAME_LEN..TZ_NAME_LEN + 4].try_into().unwrap(),
);
let length = u32::from_be_bytes(
chunk[TZ_NAME_LEN + 4..TZ_NAME_LEN + 8].try_into().unwrap(),
);
TzDataIndex { name, offset, length }
})
})
.collect(),
})
}
/// Find a timezone by name.
fn find_timezone(&self, timezone: &[u8]) -> Option<&TzDataIndex> {
// timezones in tzdata are sorted by name.
self.indexes.binary_search_by_key(&timezone, |x| &x.name).map(|x| &self.indexes[x]).ok()
}
/// Retrieve a chunk of timezone data by the index.
fn find_tzdata(
&self,
mut reader: impl Read + Seek,
header: &TzDataHeader,
index: &TzDataIndex,
) -> Result<Vec<u8>> {
reader.seek(SeekFrom::Start(index.offset as u64 + header.data_offset as u64))?;
let mut buffer = vec![0; index.length as usize];
reader.read_exact(&mut buffer)?;
Ok(buffer)
}
}
/// Index entry of the `tzdata` file.
struct TzDataIndex {
name: Box<[u8]>,
offset: u32,
length: u32,
}
/// TODO: Change this `CStr::from_bytes_until_nul` once MSRV was bumped above 1.72.0
fn from_bytes_until_nul(bytes: &[u8]) -> Option<&CStr> {
let nul_pos = bytes.iter().position(|&b| b == 0)?;
// SAFETY:
// 1. nul_pos + 1 <= bytes.len()
// 2. We know there is a nul byte at nul_pos, so this slice (ending at the nul byte) is a well-formed C string.
Some(unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[..=nul_pos]) })
}
/// Ohos tzdata index entry size: `name + offset + length`
#[cfg(any(test, target_env = "ohos"))]
const OHOS_ENTRY_LEN: usize = TZ_NAME_LEN + 2 * size_of::<u32>();
/// Android tzdata index entry size: `name + offset + length + raw_utc_offset(legacy)`:
/// [reference](https://android.googlesource.com/platform/prebuilts/fullsdk/sources/+/refs/heads/androidx-appcompat-release/android-34/com/android/i18n/timezone/ZoneInfoDb.java#271)
#[cfg(any(test, target_os = "android"))]
const ANDROID_ENTRY_LEN: usize = TZ_NAME_LEN + 3 * size_of::<u32>();
/// The database reserves 40 bytes for each id.
const TZ_NAME_LEN: usize = 40;
/// Size of the version string in the header of `tzdata` file.
/// e.g. `tzdata2024b\0`
const TZDATA_VERSION_LEN: usize = 12;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ohos_tzdata_header_and_index() {
let file = File::open("./tests/ohos/tzdata").unwrap();
let header = TzDataHeader::new(&file).unwrap();
assert_eq!(header.version, *b"2024a");
assert_eq!(header.index_offset, 24);
assert_eq!(header.data_offset, 21240);
assert_eq!(header.zonetab_offset, 272428);
let iter = TzDataIndexes::new::<OHOS_ENTRY_LEN>(&file, &header).unwrap();
assert_eq!(iter.indexes.len(), 442);
assert!(iter.find_timezone(b"Asia/Shanghai").is_some());
assert!(iter.find_timezone(b"Pacific/Noumea").is_some());
}
#[test]
fn test_ohos_tzdata_loading() {
let file = File::open("./tests/ohos/tzdata").unwrap();
let header = TzDataHeader::new(&file).unwrap();
let iter = TzDataIndexes::new::<OHOS_ENTRY_LEN>(&file, &header).unwrap();
let timezone = iter.find_timezone(b"Asia/Shanghai").unwrap();
let tzdata = iter.find_tzdata(&file, &header, timezone).unwrap();
assert_eq!(tzdata.len(), 393);
}
#[test]
fn test_invalid_tzdata_header() {
TzDataHeader::new(&b"tzdaaa2024aaaaaaaaaaaaaaa\0"[..]).unwrap_err();
}
#[test]
fn test_android_tzdata_header_and_index() {
let file = File::open("./tests/android/tzdata").unwrap();
let header = TzDataHeader::new(&file).unwrap();
assert_eq!(header.version, *b"2021a");
assert_eq!(header.index_offset, 24);
assert_eq!(header.data_offset, 30860);
assert_eq!(header.zonetab_offset, 491837);
let iter = TzDataIndexes::new::<ANDROID_ENTRY_LEN>(&file, &header).unwrap();
assert_eq!(iter.indexes.len(), 593);
assert!(iter.find_timezone(b"Asia/Shanghai").is_some());
assert!(iter.find_timezone(b"Pacific/Noumea").is_some());
}
#[test]
fn test_android_tzdata_loading() {
let file = File::open("./tests/android/tzdata").unwrap();
let header = TzDataHeader::new(&file).unwrap();
let iter = TzDataIndexes::new::<ANDROID_ENTRY_LEN>(&file, &header).unwrap();
let timezone = iter.find_timezone(b"Asia/Shanghai").unwrap();
let tzdata = iter.find_tzdata(&file, &header, timezone).unwrap();
assert_eq!(tzdata.len(), 573);
}
#[test]
fn test_ohos_tzdata_find() {
let file = File::open("./tests/ohos/tzdata").unwrap();
let tzdata = find_tz_data::<OHOS_ENTRY_LEN>(file, b"Asia/Shanghai").unwrap().unwrap();
assert_eq!(tzdata.len(), 393);
}
#[test]
fn test_ohos_tzdata_find_missing() {
let file = File::open("./tests/ohos/tzdata").unwrap();
assert!(find_tz_data::<OHOS_ENTRY_LEN>(file, b"Asia/Sjasdfai").unwrap().is_none());
}
#[test]
fn test_android_tzdata_find() {
let file = File::open("./tests/android/tzdata").unwrap();
let tzdata = find_tz_data::<ANDROID_ENTRY_LEN>(file, b"Asia/Shanghai").unwrap().unwrap();
assert_eq!(tzdata.len(), 573);
}
#[test]
fn test_android_tzdata_find_missing() {
let file = File::open("./tests/android/tzdata").unwrap();
assert!(find_tz_data::<ANDROID_ENTRY_LEN>(file, b"Asia/S000000i").unwrap().is_none());
}
#[cfg(target_env = "ohos")]
#[test]
fn test_ohos_machine_tz_data_loading() {
let tzdata = for_zone(b"Asia/Shanghai").unwrap().unwrap();
assert!(!tzdata.is_empty());
}
#[cfg(target_os = "android")]
#[test]
fn test_android_machine_tz_data_loading() {
let tzdata = for_zone(b"Asia/Shanghai").unwrap().unwrap();
assert!(!tzdata.is_empty());
}
}
+116
View File
@@ -0,0 +1,116 @@
#![deny(missing_docs)]
#![allow(dead_code)]
#![warn(unreachable_pub)]
use std::num::ParseIntError;
use std::str::Utf8Error;
use std::time::SystemTimeError;
use std::{error, fmt, io};
mod timezone;
pub(crate) use timezone::TimeZone;
mod parser;
mod rule;
/// Unified error type for everything in the crate
#[derive(Debug)]
pub(crate) enum Error {
/// Date time error
DateTime(&'static str),
/// Local time type search error
FindLocalTimeType(&'static str),
/// Local time type error
LocalTimeType(&'static str),
/// Invalid slice for integer conversion
InvalidSlice(&'static str),
/// Invalid Tzif file
InvalidTzFile(&'static str),
/// Invalid TZ string
InvalidTzString(&'static str),
/// I/O error
Io(io::Error),
/// Out of range error
OutOfRange(&'static str),
/// Integer parsing error
ParseInt(ParseIntError),
/// Date time projection error
ProjectDateTime(&'static str),
/// System time error
SystemTime(SystemTimeError),
/// Time zone error
TimeZone(&'static str),
/// Transition rule error
TransitionRule(&'static str),
/// Unsupported Tzif file
UnsupportedTzFile(&'static str),
/// Unsupported TZ string
UnsupportedTzString(&'static str),
/// UTF-8 error
Utf8(Utf8Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use Error::*;
match self {
DateTime(error) => write!(f, "invalid date time: {error}"),
FindLocalTimeType(error) => error.fmt(f),
LocalTimeType(error) => write!(f, "invalid local time type: {error}"),
InvalidSlice(error) => error.fmt(f),
InvalidTzString(error) => write!(f, "invalid TZ string: {error}"),
InvalidTzFile(error) => error.fmt(f),
Io(error) => error.fmt(f),
OutOfRange(error) => error.fmt(f),
ParseInt(error) => error.fmt(f),
ProjectDateTime(error) => error.fmt(f),
SystemTime(error) => error.fmt(f),
TransitionRule(error) => write!(f, "invalid transition rule: {error}"),
TimeZone(error) => write!(f, "invalid time zone: {error}"),
UnsupportedTzFile(error) => error.fmt(f),
UnsupportedTzString(error) => write!(f, "unsupported TZ string: {error}"),
Utf8(error) => error.fmt(f),
}
}
}
impl error::Error for Error {}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Self {
Error::Io(error)
}
}
impl From<ParseIntError> for Error {
fn from(error: ParseIntError) -> Self {
Error::ParseInt(error)
}
}
impl From<SystemTimeError> for Error {
fn from(error: SystemTimeError) -> Self {
Error::SystemTime(error)
}
}
impl From<Utf8Error> for Error {
fn from(error: Utf8Error) -> Self {
Error::Utf8(error)
}
}
/// Number of hours in one day
const HOURS_PER_DAY: i64 = 24;
/// Number of seconds in one hour
const SECONDS_PER_HOUR: i64 = 3600;
/// Number of seconds in one day
const SECONDS_PER_DAY: i64 = SECONDS_PER_HOUR * HOURS_PER_DAY;
/// Number of days in one week
const DAYS_PER_WEEK: i64 = 7;
/// Month days in a normal year
const DAY_IN_MONTHS_NORMAL_YEAR: [i64; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
/// Cumulated month days in a normal year
const CUMUL_DAY_IN_MONTHS_NORMAL_YEAR: [i64; 12] =
[0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
+348
View File
@@ -0,0 +1,348 @@
use std::io::{self, ErrorKind};
use std::iter;
use std::num::ParseIntError;
use std::str::{self, FromStr};
use super::Error;
use super::rule::TransitionRule;
use super::timezone::{LeapSecond, LocalTimeType, TimeZone, Transition};
pub(super) fn parse(bytes: &[u8]) -> Result<TimeZone, Error> {
let mut cursor = Cursor::new(bytes);
let state = State::new(&mut cursor, true)?;
let (state, footer) = match state.header.version {
Version::V1 => match cursor.is_empty() {
true => (state, None),
false => {
return Err(Error::InvalidTzFile("remaining data after end of TZif v1 data block"));
}
},
Version::V2 | Version::V3 => {
let state = State::new(&mut cursor, false)?;
(state, Some(cursor.remaining()))
}
};
let mut transitions = Vec::with_capacity(state.header.transition_count);
for (arr_time, &local_time_type_index) in
state.transition_times.chunks_exact(state.time_size).zip(state.transition_types)
{
let unix_leap_time =
state.parse_time(&arr_time[0..state.time_size], state.header.version)?;
let local_time_type_index = local_time_type_index as usize;
transitions.push(Transition::new(unix_leap_time, local_time_type_index));
}
let mut local_time_types = Vec::with_capacity(state.header.type_count);
for arr in state.local_time_types.chunks_exact(6) {
let ut_offset = read_be_i32(&arr[..4])?;
let is_dst = match arr[4] {
0 => false,
1 => true,
_ => return Err(Error::InvalidTzFile("invalid DST indicator")),
};
let char_index = arr[5] as usize;
if char_index >= state.header.char_count {
return Err(Error::InvalidTzFile("invalid time zone name char index"));
}
let position = match state.names[char_index..].iter().position(|&c| c == b'\0') {
Some(position) => position,
None => return Err(Error::InvalidTzFile("invalid time zone name char index")),
};
let name = &state.names[char_index..char_index + position];
let name = if !name.is_empty() { Some(name) } else { None };
local_time_types.push(LocalTimeType::new(ut_offset, is_dst, name)?);
}
let mut leap_seconds = Vec::with_capacity(state.header.leap_count);
for arr in state.leap_seconds.chunks_exact(state.time_size + 4) {
let unix_leap_time = state.parse_time(&arr[0..state.time_size], state.header.version)?;
let correction = read_be_i32(&arr[state.time_size..state.time_size + 4])?;
leap_seconds.push(LeapSecond::new(unix_leap_time, correction));
}
let std_walls_iter = state.std_walls.iter().copied().chain(iter::repeat(0));
let ut_locals_iter = state.ut_locals.iter().copied().chain(iter::repeat(0));
if std_walls_iter.zip(ut_locals_iter).take(state.header.type_count).any(|pair| pair == (0, 1)) {
return Err(Error::InvalidTzFile(
"invalid couple of standard/wall and UT/local indicators",
));
}
let extra_rule = match footer {
Some(footer) => {
let footer = str::from_utf8(footer)?;
if !(footer.starts_with('\n') && footer.ends_with('\n')) {
return Err(Error::InvalidTzFile("invalid footer"));
}
let tz_string = footer.trim_matches(|c: char| c.is_ascii_whitespace());
if tz_string.starts_with(':') || tz_string.contains('\0') {
return Err(Error::InvalidTzFile("invalid footer"));
}
match tz_string.is_empty() {
true => None,
false => Some(TransitionRule::from_tz_string(
tz_string.as_bytes(),
state.header.version == Version::V3,
)?),
}
}
None => None,
};
TimeZone::new(transitions, local_time_types, leap_seconds, extra_rule)
}
/// TZif data blocks
struct State<'a> {
header: Header,
/// Time size in bytes
time_size: usize,
/// Transition times data block
transition_times: &'a [u8],
/// Transition types data block
transition_types: &'a [u8],
/// Local time types data block
local_time_types: &'a [u8],
/// Time zone names data block
names: &'a [u8],
/// Leap seconds data block
leap_seconds: &'a [u8],
/// UT/local indicators data block
std_walls: &'a [u8],
/// Standard/wall indicators data block
ut_locals: &'a [u8],
}
impl<'a> State<'a> {
/// Read TZif data blocks
fn new(cursor: &mut Cursor<'a>, first: bool) -> Result<Self, Error> {
let header = Header::new(cursor)?;
let time_size = match first {
true => 4, // We always parse V1 first
false => 8,
};
Ok(Self {
time_size,
transition_times: cursor.read_exact(header.transition_count * time_size)?,
transition_types: cursor.read_exact(header.transition_count)?,
local_time_types: cursor.read_exact(header.type_count * 6)?,
names: cursor.read_exact(header.char_count)?,
leap_seconds: cursor.read_exact(header.leap_count * (time_size + 4))?,
std_walls: cursor.read_exact(header.std_wall_count)?,
ut_locals: cursor.read_exact(header.ut_local_count)?,
header,
})
}
/// Parse time values
fn parse_time(&self, arr: &[u8], version: Version) -> Result<i64, Error> {
match version {
Version::V1 => Ok(read_be_i32(&arr[..4])?.into()),
Version::V2 | Version::V3 => read_be_i64(arr),
}
}
}
/// TZif header
#[derive(Debug)]
struct Header {
/// TZif version
version: Version,
/// Number of UT/local indicators
ut_local_count: usize,
/// Number of standard/wall indicators
std_wall_count: usize,
/// Number of leap-second records
leap_count: usize,
/// Number of transition times
transition_count: usize,
/// Number of local time type records
type_count: usize,
/// Number of time zone names bytes
char_count: usize,
}
impl Header {
fn new(cursor: &mut Cursor) -> Result<Self, Error> {
let magic = cursor.read_exact(4)?;
if magic != *b"TZif" {
return Err(Error::InvalidTzFile("invalid magic number"));
}
let version = match cursor.read_exact(1)? {
[0x00] => Version::V1,
[0x32] => Version::V2,
[0x33] => Version::V3,
_ => return Err(Error::UnsupportedTzFile("unsupported TZif version")),
};
cursor.read_exact(15)?;
let ut_local_count = cursor.read_be_u32()?;
let std_wall_count = cursor.read_be_u32()?;
let leap_count = cursor.read_be_u32()?;
let transition_count = cursor.read_be_u32()?;
let type_count = cursor.read_be_u32()?;
let char_count = cursor.read_be_u32()?;
if !(type_count != 0
&& char_count != 0
&& (ut_local_count == 0 || ut_local_count == type_count)
&& (std_wall_count == 0 || std_wall_count == type_count))
{
return Err(Error::InvalidTzFile("invalid header"));
}
Ok(Self {
version,
ut_local_count: ut_local_count as usize,
std_wall_count: std_wall_count as usize,
leap_count: leap_count as usize,
transition_count: transition_count as usize,
type_count: type_count as usize,
char_count: char_count as usize,
})
}
}
/// A `Cursor` contains a slice of a buffer and a read count.
#[derive(Debug, Eq, PartialEq)]
pub(crate) struct Cursor<'a> {
/// Slice representing the remaining data to be read
remaining: &'a [u8],
/// Number of already read bytes
read_count: usize,
}
impl<'a> Cursor<'a> {
/// Construct a new `Cursor` from remaining data
pub(crate) const fn new(remaining: &'a [u8]) -> Self {
Self { remaining, read_count: 0 }
}
pub(crate) fn peek(&self) -> Option<&u8> {
self.remaining().first()
}
/// Returns remaining data
pub(crate) const fn remaining(&self) -> &'a [u8] {
self.remaining
}
/// Returns `true` if data is remaining
pub(crate) const fn is_empty(&self) -> bool {
self.remaining.is_empty()
}
pub(crate) fn read_be_u32(&mut self) -> Result<u32, Error> {
let mut buf = [0; 4];
buf.copy_from_slice(self.read_exact(4)?);
Ok(u32::from_be_bytes(buf))
}
#[cfg(target_env = "ohos")]
pub(crate) fn seek_after(&mut self, offset: usize) -> Result<usize, io::Error> {
if offset < self.read_count {
return Err(io::Error::from(ErrorKind::UnexpectedEof));
}
match self.remaining.get((offset - self.read_count)..) {
Some(remaining) => {
self.remaining = remaining;
self.read_count = offset;
Ok(offset)
}
_ => Err(io::Error::from(ErrorKind::UnexpectedEof)),
}
}
/// Read exactly `count` bytes, reducing remaining data and incrementing read count
pub(crate) fn read_exact(&mut self, count: usize) -> Result<&'a [u8], io::Error> {
match (self.remaining.get(..count), self.remaining.get(count..)) {
(Some(result), Some(remaining)) => {
self.remaining = remaining;
self.read_count += count;
Ok(result)
}
_ => Err(io::Error::from(ErrorKind::UnexpectedEof)),
}
}
/// Read bytes and compare them to the provided tag
pub(crate) fn read_tag(&mut self, tag: &[u8]) -> Result<(), io::Error> {
if self.read_exact(tag.len())? == tag {
Ok(())
} else {
Err(io::Error::from(ErrorKind::InvalidData))
}
}
/// Read bytes if the remaining data is prefixed by the provided tag
pub(crate) fn read_optional_tag(&mut self, tag: &[u8]) -> Result<bool, io::Error> {
if self.remaining.starts_with(tag) {
self.read_exact(tag.len())?;
Ok(true)
} else {
Ok(false)
}
}
/// Read bytes as long as the provided predicate is true
pub(crate) fn read_while<F: Fn(&u8) -> bool>(&mut self, f: F) -> Result<&'a [u8], io::Error> {
match self.remaining.iter().position(|x| !f(x)) {
None => self.read_exact(self.remaining.len()),
Some(position) => self.read_exact(position),
}
}
// Parse an integer out of the ASCII digits
pub(crate) fn read_int<T: FromStr<Err = ParseIntError>>(&mut self) -> Result<T, Error> {
let bytes = self.read_while(u8::is_ascii_digit)?;
Ok(str::from_utf8(bytes)?.parse()?)
}
/// Read bytes until the provided predicate is true
pub(crate) fn read_until<F: Fn(&u8) -> bool>(&mut self, f: F) -> Result<&'a [u8], io::Error> {
match self.remaining.iter().position(f) {
None => self.read_exact(self.remaining.len()),
Some(position) => self.read_exact(position),
}
}
}
pub(crate) fn read_be_i32(bytes: &[u8]) -> Result<i32, Error> {
if bytes.len() != 4 {
return Err(Error::InvalidSlice("too short for i32"));
}
let mut buf = [0; 4];
buf.copy_from_slice(bytes);
Ok(i32::from_be_bytes(buf))
}
pub(crate) fn read_be_i64(bytes: &[u8]) -> Result<i64, Error> {
if bytes.len() != 8 {
return Err(Error::InvalidSlice("too short for i64"));
}
let mut buf = [0; 8];
buf.copy_from_slice(bytes);
Ok(i64::from_be_bytes(buf))
}
/// TZif version
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum Version {
/// Version 1
V1,
/// Version 2
V2,
/// Version 3
V3,
}
File diff suppressed because it is too large Load Diff
+948
View File
@@ -0,0 +1,948 @@
//! Types related to a time zone.
use std::fs::{self, File};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::{cmp::Ordering, fmt, str};
use super::rule::{AlternateTime, TransitionRule};
use super::{DAYS_PER_WEEK, Error, SECONDS_PER_DAY, parser};
use crate::NaiveDateTime;
/// Time zone
#[derive(Debug, Clone, Eq, PartialEq)]
pub(crate) struct TimeZone {
/// List of transitions
transitions: Vec<Transition>,
/// List of local time types (cannot be empty)
local_time_types: Vec<LocalTimeType>,
/// List of leap seconds
leap_seconds: Vec<LeapSecond>,
/// Extra transition rule applicable after the last transition
extra_rule: Option<TransitionRule>,
}
impl TimeZone {
/// Returns local time zone.
///
/// This method in not supported on non-UNIX platforms, and returns the UTC time zone instead.
pub(crate) fn local(env_tz: Option<&str>) -> Result<Self, Error> {
match env_tz {
Some(tz) => Self::from_posix_tz(tz),
None => Self::from_posix_tz("localtime"),
}
}
/// Construct a time zone from a POSIX TZ string, as described in [the POSIX documentation of the `TZ` environment variable](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html).
fn from_posix_tz(tz_string: &str) -> Result<Self, Error> {
// It is commonly agreed (but not standard) that setting an empty `TZ=` uses UTC.
if tz_string.is_empty() {
return Ok(Self::utc());
}
if tz_string == "localtime" {
return Self::from_tz_data(&fs::read("/etc/localtime")?);
}
// attributes are not allowed on if blocks in Rust 1.38
#[cfg(any(target_os = "android", target_env = "ohos"))]
{
if let Ok(Some(bytes)) = crate::offset::local::tz_data::for_zone(tz_string) {
return Self::from_tz_data(&bytes);
}
}
let mut chars = tz_string.chars();
if chars.next() == Some(':') {
return Self::from_file(&mut find_tz_file(chars.as_str())?);
}
if let Ok(mut file) = find_tz_file(tz_string) {
return Self::from_file(&mut file);
}
// TZ string extensions are not allowed
let tz_string = tz_string.trim_matches(|c: char| c.is_ascii_whitespace());
let rule = TransitionRule::from_tz_string(tz_string.as_bytes(), false)?;
Self::new(
vec![],
match rule {
TransitionRule::Fixed(local_time_type) => vec![local_time_type],
TransitionRule::Alternate(AlternateTime { std, dst, .. }) => vec![std, dst],
},
vec![],
Some(rule),
)
}
/// Construct a time zone
pub(super) fn new(
transitions: Vec<Transition>,
local_time_types: Vec<LocalTimeType>,
leap_seconds: Vec<LeapSecond>,
extra_rule: Option<TransitionRule>,
) -> Result<Self, Error> {
let new = Self { transitions, local_time_types, leap_seconds, extra_rule };
new.as_ref().validate()?;
Ok(new)
}
/// Construct a time zone from the contents of a time zone file
fn from_file(file: &mut File) -> Result<Self, Error> {
let mut bytes = Vec::new();
file.read_to_end(&mut bytes)?;
Self::from_tz_data(&bytes)
}
/// Construct a time zone from the contents of a time zone file
///
/// Parse TZif data as described in [RFC 8536](https://datatracker.ietf.org/doc/html/rfc8536).
pub(crate) fn from_tz_data(bytes: &[u8]) -> Result<Self, Error> {
parser::parse(bytes)
}
/// Construct a time zone with the specified UTC offset in seconds
fn fixed(ut_offset: i32) -> Result<Self, Error> {
Ok(Self {
transitions: Vec::new(),
local_time_types: vec![LocalTimeType::with_offset(ut_offset)?],
leap_seconds: Vec::new(),
extra_rule: None,
})
}
/// Construct the time zone associated to UTC
pub(crate) fn utc() -> Self {
Self {
transitions: Vec::new(),
local_time_types: vec![LocalTimeType::UTC],
leap_seconds: Vec::new(),
extra_rule: None,
}
}
/// Find the local time type associated to the time zone at the specified Unix time in seconds
pub(crate) fn find_local_time_type(&self, unix_time: i64) -> Result<&LocalTimeType, Error> {
self.as_ref().find_local_time_type(unix_time)
}
pub(crate) fn find_local_time_type_from_local(
&self,
local_time: NaiveDateTime,
) -> Result<crate::MappedLocalTime<LocalTimeType>, Error> {
self.as_ref().find_local_time_type_from_local(local_time)
}
/// Returns a reference to the time zone
fn as_ref(&self) -> TimeZoneRef<'_> {
TimeZoneRef {
transitions: &self.transitions,
local_time_types: &self.local_time_types,
leap_seconds: &self.leap_seconds,
extra_rule: &self.extra_rule,
}
}
}
/// Reference to a time zone
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub(crate) struct TimeZoneRef<'a> {
/// List of transitions
transitions: &'a [Transition],
/// List of local time types (cannot be empty)
local_time_types: &'a [LocalTimeType],
/// List of leap seconds
leap_seconds: &'a [LeapSecond],
/// Extra transition rule applicable after the last transition
extra_rule: &'a Option<TransitionRule>,
}
impl<'a> TimeZoneRef<'a> {
/// Find the local time type associated to the time zone at the specified Unix time in seconds
pub(crate) fn find_local_time_type(&self, unix_time: i64) -> Result<&'a LocalTimeType, Error> {
let extra_rule = match self.transitions.last() {
None => match self.extra_rule {
Some(extra_rule) => extra_rule,
None => return Ok(&self.local_time_types[0]),
},
Some(last_transition) => {
let unix_leap_time = match self.unix_time_to_unix_leap_time(unix_time) {
Ok(unix_leap_time) => unix_leap_time,
Err(Error::OutOfRange(error)) => return Err(Error::FindLocalTimeType(error)),
Err(err) => return Err(err),
};
if unix_leap_time >= last_transition.unix_leap_time {
match self.extra_rule {
Some(extra_rule) => extra_rule,
None => {
// RFC 8536 3.2:
// "Local time for timestamps on or after the last transition is
// specified by the TZ string in the footer (Section 3.3) if present
// and nonempty; otherwise, it is unspecified."
//
// Older versions of macOS (1.12 and before?) have TZif file with a
// missing TZ string, and use the offset given by the last transition.
return Ok(
&self.local_time_types[last_transition.local_time_type_index]
);
}
}
} else {
let index = match self
.transitions
.binary_search_by_key(&unix_leap_time, Transition::unix_leap_time)
{
Ok(x) => x + 1,
Err(x) => x,
};
let local_time_type_index = if index > 0 {
self.transitions[index - 1].local_time_type_index
} else {
0
};
return Ok(&self.local_time_types[local_time_type_index]);
}
}
};
match extra_rule.find_local_time_type(unix_time) {
Ok(local_time_type) => Ok(local_time_type),
Err(Error::OutOfRange(error)) => Err(Error::FindLocalTimeType(error)),
err => err,
}
}
pub(crate) fn find_local_time_type_from_local(
&self,
local_time: NaiveDateTime,
) -> Result<crate::MappedLocalTime<LocalTimeType>, Error> {
// #TODO: this is wrong as we need 'local_time_to_local_leap_time ?
// but ... does the local time even include leap seconds ??
// let unix_leap_time = match self.unix_time_to_unix_leap_time(local_time) {
// Ok(unix_leap_time) => unix_leap_time,
// Err(Error::OutOfRange(error)) => return Err(Error::FindLocalTimeType(error)),
// Err(err) => return Err(err),
// };
let local_leap_time = local_time.and_utc().timestamp();
// if we have at least one transition,
// we must check _all_ of them, in case of any Overlapping (MappedLocalTime::Ambiguous) or Skipping (MappedLocalTime::None) transitions
let offset_after_last = if !self.transitions.is_empty() {
let mut prev = self.local_time_types[0];
for transition in self.transitions {
let after_ltt = self.local_time_types[transition.local_time_type_index];
// the end and start here refers to where the time starts prior to the transition
// and where it ends up after. not the temporal relationship.
let transition_end = transition.unix_leap_time + i64::from(after_ltt.ut_offset);
let transition_start = transition.unix_leap_time + i64::from(prev.ut_offset);
match transition_start.cmp(&transition_end) {
Ordering::Greater => {
// backwards transition, eg from DST to regular
// this means a given local time could have one of two possible offsets
if local_leap_time < transition_end {
return Ok(crate::MappedLocalTime::Single(prev));
} else if local_leap_time >= transition_end
&& local_leap_time <= transition_start
{
if prev.ut_offset < after_ltt.ut_offset {
return Ok(crate::MappedLocalTime::Ambiguous(prev, after_ltt));
} else {
return Ok(crate::MappedLocalTime::Ambiguous(after_ltt, prev));
}
}
}
Ordering::Equal => {
// should this ever happen? presumably we have to handle it anyway.
if local_leap_time < transition_start {
return Ok(crate::MappedLocalTime::Single(prev));
} else if local_leap_time == transition_end {
if prev.ut_offset < after_ltt.ut_offset {
return Ok(crate::MappedLocalTime::Ambiguous(prev, after_ltt));
} else {
return Ok(crate::MappedLocalTime::Ambiguous(after_ltt, prev));
}
}
}
Ordering::Less => {
// forwards transition, eg from regular to DST
// this means that times that are skipped are invalid local times
if local_leap_time <= transition_start {
return Ok(crate::MappedLocalTime::Single(prev));
} else if local_leap_time < transition_end {
return Ok(crate::MappedLocalTime::None);
} else if local_leap_time == transition_end {
return Ok(crate::MappedLocalTime::Single(after_ltt));
}
}
}
// try the next transition, we are fully after this one
prev = after_ltt;
}
prev
} else {
self.local_time_types[0]
};
if let Some(extra_rule) = self.extra_rule {
match extra_rule.find_local_time_type_from_local(local_time) {
Ok(local_time_type) => Ok(local_time_type),
Err(Error::OutOfRange(error)) => Err(Error::FindLocalTimeType(error)),
err => err,
}
} else {
Ok(crate::MappedLocalTime::Single(offset_after_last))
}
}
/// Check time zone inputs
fn validate(&self) -> Result<(), Error> {
// Check local time types
let local_time_types_size = self.local_time_types.len();
if local_time_types_size == 0 {
return Err(Error::TimeZone("list of local time types must not be empty"));
}
// Check transitions
let mut i_transition = 0;
while i_transition < self.transitions.len() {
if self.transitions[i_transition].local_time_type_index >= local_time_types_size {
return Err(Error::TimeZone("invalid local time type index"));
}
if i_transition + 1 < self.transitions.len()
&& self.transitions[i_transition].unix_leap_time
>= self.transitions[i_transition + 1].unix_leap_time
{
return Err(Error::TimeZone("invalid transition"));
}
i_transition += 1;
}
// Check leap seconds
if !(self.leap_seconds.is_empty()
|| self.leap_seconds[0].unix_leap_time >= 0
&& self.leap_seconds[0].correction.saturating_abs() == 1)
{
return Err(Error::TimeZone("invalid leap second"));
}
let min_interval = SECONDS_PER_28_DAYS - 1;
let mut i_leap_second = 0;
while i_leap_second < self.leap_seconds.len() {
if i_leap_second + 1 < self.leap_seconds.len() {
let x0 = &self.leap_seconds[i_leap_second];
let x1 = &self.leap_seconds[i_leap_second + 1];
let diff_unix_leap_time = x1.unix_leap_time.saturating_sub(x0.unix_leap_time);
let abs_diff_correction =
x1.correction.saturating_sub(x0.correction).saturating_abs();
if !(diff_unix_leap_time >= min_interval && abs_diff_correction == 1) {
return Err(Error::TimeZone("invalid leap second"));
}
}
i_leap_second += 1;
}
// Check extra rule
let (extra_rule, last_transition) = match (&self.extra_rule, self.transitions.last()) {
(Some(rule), Some(trans)) => (rule, trans),
_ => return Ok(()),
};
let last_local_time_type = &self.local_time_types[last_transition.local_time_type_index];
let unix_time = match self.unix_leap_time_to_unix_time(last_transition.unix_leap_time) {
Ok(unix_time) => unix_time,
Err(Error::OutOfRange(error)) => return Err(Error::TimeZone(error)),
Err(err) => return Err(err),
};
let rule_local_time_type = match extra_rule.find_local_time_type(unix_time) {
Ok(rule_local_time_type) => rule_local_time_type,
Err(Error::OutOfRange(error)) => return Err(Error::TimeZone(error)),
Err(err) => return Err(err),
};
let check = last_local_time_type.ut_offset == rule_local_time_type.ut_offset
&& last_local_time_type.is_dst == rule_local_time_type.is_dst
&& match (&last_local_time_type.name, &rule_local_time_type.name) {
(Some(x), Some(y)) => x.equal(y),
(None, None) => true,
_ => false,
};
if !check {
return Err(Error::TimeZone(
"extra transition rule is inconsistent with the last transition",
));
}
Ok(())
}
/// Convert Unix time to Unix leap time, from the list of leap seconds in a time zone
const fn unix_time_to_unix_leap_time(&self, unix_time: i64) -> Result<i64, Error> {
let mut unix_leap_time = unix_time;
let mut i = 0;
while i < self.leap_seconds.len() {
let leap_second = &self.leap_seconds[i];
if unix_leap_time < leap_second.unix_leap_time {
break;
}
unix_leap_time = match unix_time.checked_add(leap_second.correction as i64) {
Some(unix_leap_time) => unix_leap_time,
None => return Err(Error::OutOfRange("out of range operation")),
};
i += 1;
}
Ok(unix_leap_time)
}
/// Convert Unix leap time to Unix time, from the list of leap seconds in a time zone
fn unix_leap_time_to_unix_time(&self, unix_leap_time: i64) -> Result<i64, Error> {
if unix_leap_time == i64::MIN {
return Err(Error::OutOfRange("out of range operation"));
}
let index = match self
.leap_seconds
.binary_search_by_key(&(unix_leap_time - 1), LeapSecond::unix_leap_time)
{
Ok(x) => x + 1,
Err(x) => x,
};
let correction = if index > 0 { self.leap_seconds[index - 1].correction } else { 0 };
match unix_leap_time.checked_sub(correction as i64) {
Some(unix_time) => Ok(unix_time),
None => Err(Error::OutOfRange("out of range operation")),
}
}
/// The UTC time zone
const UTC: TimeZoneRef<'static> = TimeZoneRef {
transitions: &[],
local_time_types: &[LocalTimeType::UTC],
leap_seconds: &[],
extra_rule: &None,
};
}
/// Transition of a TZif file
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub(super) struct Transition {
/// Unix leap time
unix_leap_time: i64,
/// Index specifying the local time type of the transition
local_time_type_index: usize,
}
impl Transition {
/// Construct a TZif file transition
pub(super) const fn new(unix_leap_time: i64, local_time_type_index: usize) -> Self {
Self { unix_leap_time, local_time_type_index }
}
/// Returns Unix leap time
const fn unix_leap_time(&self) -> i64 {
self.unix_leap_time
}
}
/// Leap second of a TZif file
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub(super) struct LeapSecond {
/// Unix leap time
unix_leap_time: i64,
/// Leap second correction
correction: i32,
}
impl LeapSecond {
/// Construct a TZif file leap second
pub(super) const fn new(unix_leap_time: i64, correction: i32) -> Self {
Self { unix_leap_time, correction }
}
/// Returns Unix leap time
const fn unix_leap_time(&self) -> i64 {
self.unix_leap_time
}
}
/// ASCII-encoded fixed-capacity string, used for storing time zone names
#[derive(Copy, Clone, Eq, PartialEq)]
struct TimeZoneName {
/// Length-prefixed string buffer
bytes: [u8; 8],
}
impl TimeZoneName {
/// Construct a time zone name
///
/// man tzfile(5):
/// Time zone designations should consist of at least three (3) and no more than six (6) ASCII
/// characters from the set of alphanumerics, “-”, and “+”. This is for compatibility with
/// POSIX requirements for time zone abbreviations.
fn new(input: &[u8]) -> Result<Self, Error> {
let len = input.len();
if !(3..=7).contains(&len) {
return Err(Error::LocalTimeType(
"time zone name must have between 3 and 7 characters",
));
}
let mut bytes = [0; 8];
bytes[0] = input.len() as u8;
let mut i = 0;
while i < len {
let b = input[i];
match b {
b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b'+' | b'-' => {}
_ => return Err(Error::LocalTimeType("invalid characters in time zone name")),
}
bytes[i + 1] = b;
i += 1;
}
Ok(Self { bytes })
}
/// Returns time zone name as a byte slice
fn as_bytes(&self) -> &[u8] {
match self.bytes[0] {
3 => &self.bytes[1..4],
4 => &self.bytes[1..5],
5 => &self.bytes[1..6],
6 => &self.bytes[1..7],
7 => &self.bytes[1..8],
_ => unreachable!(),
}
}
/// Check if two time zone names are equal
fn equal(&self, other: &Self) -> bool {
self.bytes == other.bytes
}
}
impl AsRef<str> for TimeZoneName {
fn as_ref(&self) -> &str {
// SAFETY: ASCII is valid UTF-8
unsafe { str::from_utf8_unchecked(self.as_bytes()) }
}
}
impl fmt::Debug for TimeZoneName {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.as_ref().fmt(f)
}
}
/// Local time type associated to a time zone
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub(crate) struct LocalTimeType {
/// Offset from UTC in seconds
pub(super) ut_offset: i32,
/// Daylight Saving Time indicator
is_dst: bool,
/// Time zone name
name: Option<TimeZoneName>,
}
impl LocalTimeType {
/// Construct a local time type
pub(super) fn new(ut_offset: i32, is_dst: bool, name: Option<&[u8]>) -> Result<Self, Error> {
if ut_offset == i32::MIN {
return Err(Error::LocalTimeType("invalid UTC offset"));
}
let name = match name {
Some(name) => TimeZoneName::new(name)?,
None => return Ok(Self { ut_offset, is_dst, name: None }),
};
Ok(Self { ut_offset, is_dst, name: Some(name) })
}
/// Construct a local time type with the specified UTC offset in seconds
pub(super) const fn with_offset(ut_offset: i32) -> Result<Self, Error> {
if ut_offset == i32::MIN {
return Err(Error::LocalTimeType("invalid UTC offset"));
}
Ok(Self { ut_offset, is_dst: false, name: None })
}
/// Returns offset from UTC in seconds
pub(crate) const fn offset(&self) -> i32 {
self.ut_offset
}
/// Returns daylight saving time indicator
pub(super) const fn is_dst(&self) -> bool {
self.is_dst
}
pub(super) const UTC: LocalTimeType = Self { ut_offset: 0, is_dst: false, name: None };
}
/// Open the TZif file corresponding to a TZ string
fn find_tz_file(path: impl AsRef<Path>) -> Result<File, Error> {
// Don't check system timezone directories on non-UNIX platforms
#[cfg(not(unix))]
return Ok(File::open(path)?);
#[cfg(unix)]
{
let path = path.as_ref();
if path.is_absolute() {
return Ok(File::open(path)?);
}
for folder in &ZONE_INFO_DIRECTORIES {
if let Ok(file) = File::open(PathBuf::from(folder).join(path)) {
return Ok(file);
}
}
Err(Error::Io(io::ErrorKind::NotFound.into()))
}
}
// Possible system timezone directories
#[cfg(unix)]
const ZONE_INFO_DIRECTORIES: [&str; 4] =
["/usr/share/zoneinfo", "/share/zoneinfo", "/etc/zoneinfo", "/usr/share/lib/zoneinfo"];
/// Number of seconds in one week
pub(crate) const SECONDS_PER_WEEK: i64 = SECONDS_PER_DAY * DAYS_PER_WEEK;
/// Number of seconds in 28 days
const SECONDS_PER_28_DAYS: i64 = SECONDS_PER_DAY * 28;
#[cfg(test)]
mod tests {
use super::super::Error;
use super::{LeapSecond, LocalTimeType, TimeZone, TimeZoneName, Transition, TransitionRule};
#[test]
fn test_no_dst() -> Result<(), Error> {
let tz_string = b"HST10";
let transition_rule = TransitionRule::from_tz_string(tz_string, false)?;
assert_eq!(transition_rule, LocalTimeType::new(-36000, false, Some(b"HST"))?.into());
Ok(())
}
#[test]
fn test_error() -> Result<(), Error> {
assert!(matches!(
TransitionRule::from_tz_string(b"IST-1GMT0", false),
Err(Error::UnsupportedTzString(_))
));
assert!(matches!(
TransitionRule::from_tz_string(b"EET-2EEST", false),
Err(Error::UnsupportedTzString(_))
));
Ok(())
}
#[test]
fn test_v1_file_with_leap_seconds() -> Result<(), Error> {
let bytes = b"TZif\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01\0\0\0\x01\0\0\0\x1b\0\0\0\0\0\0\0\x01\0\0\0\x04\0\0\0\0\0\0UTC\0\x04\xb2\x58\0\0\0\0\x01\x05\xa4\xec\x01\0\0\0\x02\x07\x86\x1f\x82\0\0\0\x03\x09\x67\x53\x03\0\0\0\x04\x0b\x48\x86\x84\0\0\0\x05\x0d\x2b\x0b\x85\0\0\0\x06\x0f\x0c\x3f\x06\0\0\0\x07\x10\xed\x72\x87\0\0\0\x08\x12\xce\xa6\x08\0\0\0\x09\x15\x9f\xca\x89\0\0\0\x0a\x17\x80\xfe\x0a\0\0\0\x0b\x19\x62\x31\x8b\0\0\0\x0c\x1d\x25\xea\x0c\0\0\0\x0d\x21\xda\xe5\x0d\0\0\0\x0e\x25\x9e\x9d\x8e\0\0\0\x0f\x27\x7f\xd1\x0f\0\0\0\x10\x2a\x50\xf5\x90\0\0\0\x11\x2c\x32\x29\x11\0\0\0\x12\x2e\x13\x5c\x92\0\0\0\x13\x30\xe7\x24\x13\0\0\0\x14\x33\xb8\x48\x94\0\0\0\x15\x36\x8c\x10\x15\0\0\0\x16\x43\xb7\x1b\x96\0\0\0\x17\x49\x5c\x07\x97\0\0\0\x18\x4f\xef\x93\x18\0\0\0\x19\x55\x93\x2d\x99\0\0\0\x1a\x58\x68\x46\x9a\0\0\0\x1b\0\0";
let time_zone = TimeZone::from_tz_data(bytes)?;
let time_zone_result = TimeZone::new(
Vec::new(),
vec![LocalTimeType::new(0, false, Some(b"UTC"))?],
vec![
LeapSecond::new(78796800, 1),
LeapSecond::new(94694401, 2),
LeapSecond::new(126230402, 3),
LeapSecond::new(157766403, 4),
LeapSecond::new(189302404, 5),
LeapSecond::new(220924805, 6),
LeapSecond::new(252460806, 7),
LeapSecond::new(283996807, 8),
LeapSecond::new(315532808, 9),
LeapSecond::new(362793609, 10),
LeapSecond::new(394329610, 11),
LeapSecond::new(425865611, 12),
LeapSecond::new(489024012, 13),
LeapSecond::new(567993613, 14),
LeapSecond::new(631152014, 15),
LeapSecond::new(662688015, 16),
LeapSecond::new(709948816, 17),
LeapSecond::new(741484817, 18),
LeapSecond::new(773020818, 19),
LeapSecond::new(820454419, 20),
LeapSecond::new(867715220, 21),
LeapSecond::new(915148821, 22),
LeapSecond::new(1136073622, 23),
LeapSecond::new(1230768023, 24),
LeapSecond::new(1341100824, 25),
LeapSecond::new(1435708825, 26),
LeapSecond::new(1483228826, 27),
],
None,
)?;
assert_eq!(time_zone, time_zone_result);
Ok(())
}
#[test]
fn test_v2_file() -> Result<(), Error> {
let bytes = b"TZif2\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x06\0\0\0\x06\0\0\0\0\0\0\0\x07\0\0\0\x06\0\0\0\x14\x80\0\0\0\xbb\x05\x43\x48\xbb\x21\x71\x58\xcb\x89\x3d\xc8\xd2\x23\xf4\x70\xd2\x61\x49\x38\xd5\x8d\x73\x48\x01\x02\x01\x03\x04\x01\x05\xff\xff\x6c\x02\0\0\xff\xff\x6c\x58\0\x04\xff\xff\x7a\x68\x01\x08\xff\xff\x7a\x68\x01\x0c\xff\xff\x7a\x68\x01\x10\xff\xff\x73\x60\0\x04LMT\0HST\0HDT\0HWT\0HPT\0\0\0\0\0\x01\0\0\0\0\0\x01\0TZif2\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x06\0\0\0\x06\0\0\0\0\0\0\0\x07\0\0\0\x06\0\0\0\x14\xff\xff\xff\xff\x74\xe0\x70\xbe\xff\xff\xff\xff\xbb\x05\x43\x48\xff\xff\xff\xff\xbb\x21\x71\x58\xff\xff\xff\xff\xcb\x89\x3d\xc8\xff\xff\xff\xff\xd2\x23\xf4\x70\xff\xff\xff\xff\xd2\x61\x49\x38\xff\xff\xff\xff\xd5\x8d\x73\x48\x01\x02\x01\x03\x04\x01\x05\xff\xff\x6c\x02\0\0\xff\xff\x6c\x58\0\x04\xff\xff\x7a\x68\x01\x08\xff\xff\x7a\x68\x01\x0c\xff\xff\x7a\x68\x01\x10\xff\xff\x73\x60\0\x04LMT\0HST\0HDT\0HWT\0HPT\0\0\0\0\0\x01\0\0\0\0\0\x01\0\x0aHST10\x0a";
let time_zone = TimeZone::from_tz_data(bytes)?;
let time_zone_result = TimeZone::new(
vec![
Transition::new(-2334101314, 1),
Transition::new(-1157283000, 2),
Transition::new(-1155436200, 1),
Transition::new(-880198200, 3),
Transition::new(-769395600, 4),
Transition::new(-765376200, 1),
Transition::new(-712150200, 5),
],
vec![
LocalTimeType::new(-37886, false, Some(b"LMT"))?,
LocalTimeType::new(-37800, false, Some(b"HST"))?,
LocalTimeType::new(-34200, true, Some(b"HDT"))?,
LocalTimeType::new(-34200, true, Some(b"HWT"))?,
LocalTimeType::new(-34200, true, Some(b"HPT"))?,
LocalTimeType::new(-36000, false, Some(b"HST"))?,
],
Vec::new(),
Some(TransitionRule::from(LocalTimeType::new(-36000, false, Some(b"HST"))?)),
)?;
assert_eq!(time_zone, time_zone_result);
assert_eq!(
*time_zone.find_local_time_type(-1156939200)?,
LocalTimeType::new(-34200, true, Some(b"HDT"))?
);
assert_eq!(
*time_zone.find_local_time_type(1546300800)?,
LocalTimeType::new(-36000, false, Some(b"HST"))?
);
Ok(())
}
#[test]
fn test_no_tz_string() -> Result<(), Error> {
// Guayaquil from macOS 10.11
let bytes = b"TZif\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x02\0\0\0\x02\0\0\0\0\0\0\0\x01\0\0\0\x02\0\0\0\x08\xb6\xa4B\x18\x01\xff\xff\xb6h\0\0\xff\xff\xb9\xb0\0\x04QMT\0ECT\0\0\0\0\0";
let time_zone = TimeZone::from_tz_data(bytes)?;
dbg!(&time_zone);
let time_zone_result = TimeZone::new(
vec![Transition::new(-1230749160, 1)],
vec![
LocalTimeType::new(-18840, false, Some(b"QMT"))?,
LocalTimeType::new(-18000, false, Some(b"ECT"))?,
],
Vec::new(),
None,
)?;
assert_eq!(time_zone, time_zone_result);
assert_eq!(
*time_zone.find_local_time_type(-1500000000)?,
LocalTimeType::new(-18840, false, Some(b"QMT"))?
);
assert_eq!(
*time_zone.find_local_time_type(0)?,
LocalTimeType::new(-18000, false, Some(b"ECT"))?
);
Ok(())
}
#[test]
fn test_tz_ascii_str() -> Result<(), Error> {
assert!(matches!(TimeZoneName::new(b""), Err(Error::LocalTimeType(_))));
assert!(matches!(TimeZoneName::new(b"A"), Err(Error::LocalTimeType(_))));
assert!(matches!(TimeZoneName::new(b"AB"), Err(Error::LocalTimeType(_))));
assert_eq!(TimeZoneName::new(b"CET")?.as_bytes(), b"CET");
assert_eq!(TimeZoneName::new(b"CHADT")?.as_bytes(), b"CHADT");
assert_eq!(TimeZoneName::new(b"abcdefg")?.as_bytes(), b"abcdefg");
assert_eq!(TimeZoneName::new(b"UTC+02")?.as_bytes(), b"UTC+02");
assert_eq!(TimeZoneName::new(b"-1230")?.as_bytes(), b"-1230");
assert!(matches!(TimeZoneName::new("−0330".as_bytes()), Err(Error::LocalTimeType(_)))); // MINUS SIGN (U+2212)
assert!(matches!(TimeZoneName::new(b"\x00123"), Err(Error::LocalTimeType(_))));
assert!(matches!(TimeZoneName::new(b"12345678"), Err(Error::LocalTimeType(_))));
assert!(matches!(TimeZoneName::new(b"GMT\0\0\0"), Err(Error::LocalTimeType(_))));
Ok(())
}
#[test]
fn test_time_zone() -> Result<(), Error> {
let utc = LocalTimeType::UTC;
let cet = LocalTimeType::with_offset(3600)?;
let utc_local_time_types = vec![utc];
let fixed_extra_rule = TransitionRule::from(cet);
let time_zone_1 = TimeZone::new(vec![], utc_local_time_types.clone(), vec![], None)?;
let time_zone_2 =
TimeZone::new(vec![], utc_local_time_types.clone(), vec![], Some(fixed_extra_rule))?;
let time_zone_3 =
TimeZone::new(vec![Transition::new(0, 0)], utc_local_time_types.clone(), vec![], None)?;
let time_zone_4 = TimeZone::new(
vec![Transition::new(i32::MIN.into(), 0), Transition::new(0, 1)],
vec![utc, cet],
Vec::new(),
Some(fixed_extra_rule),
)?;
assert_eq!(*time_zone_1.find_local_time_type(0)?, utc);
assert_eq!(*time_zone_2.find_local_time_type(0)?, cet);
assert_eq!(*time_zone_3.find_local_time_type(-1)?, utc);
assert_eq!(*time_zone_3.find_local_time_type(0)?, utc);
assert_eq!(*time_zone_4.find_local_time_type(-1)?, utc);
assert_eq!(*time_zone_4.find_local_time_type(0)?, cet);
let time_zone_err = TimeZone::new(
vec![Transition::new(0, 0)],
utc_local_time_types,
vec![],
Some(fixed_extra_rule),
);
assert!(time_zone_err.is_err());
Ok(())
}
#[test]
fn test_time_zone_from_posix_tz() -> Result<(), Error> {
#[cfg(unix)]
{
// if the TZ var is set, this essentially _overrides_ the
// time set by the localtime symlink
// so just ensure that ::local() acts as expected
// in this case
if let Ok(tz) = std::env::var("TZ") {
let time_zone_local = TimeZone::local(Some(tz.as_str()))?;
let time_zone_local_1 = TimeZone::from_posix_tz(&tz)?;
assert_eq!(time_zone_local, time_zone_local_1);
}
// `TimeZone::from_posix_tz("UTC")` will return `Error` if the environment does not have
// a time zone database, like for example some docker containers.
// In that case skip the test.
if let Ok(time_zone_utc) = TimeZone::from_posix_tz("UTC") {
assert_eq!(time_zone_utc.find_local_time_type(0)?.offset(), 0);
}
}
assert!(TimeZone::from_posix_tz("EST5EDT,0/0,J365/25").is_err());
assert_eq!(TimeZone::from_posix_tz("").unwrap().find_local_time_type(0)?.offset(), 0);
Ok(())
}
#[test]
fn test_leap_seconds() -> Result<(), Error> {
let time_zone = TimeZone::new(
Vec::new(),
vec![LocalTimeType::new(0, false, Some(b"UTC"))?],
vec![
LeapSecond::new(78796800, 1),
LeapSecond::new(94694401, 2),
LeapSecond::new(126230402, 3),
LeapSecond::new(157766403, 4),
LeapSecond::new(189302404, 5),
LeapSecond::new(220924805, 6),
LeapSecond::new(252460806, 7),
LeapSecond::new(283996807, 8),
LeapSecond::new(315532808, 9),
LeapSecond::new(362793609, 10),
LeapSecond::new(394329610, 11),
LeapSecond::new(425865611, 12),
LeapSecond::new(489024012, 13),
LeapSecond::new(567993613, 14),
LeapSecond::new(631152014, 15),
LeapSecond::new(662688015, 16),
LeapSecond::new(709948816, 17),
LeapSecond::new(741484817, 18),
LeapSecond::new(773020818, 19),
LeapSecond::new(820454419, 20),
LeapSecond::new(867715220, 21),
LeapSecond::new(915148821, 22),
LeapSecond::new(1136073622, 23),
LeapSecond::new(1230768023, 24),
LeapSecond::new(1341100824, 25),
LeapSecond::new(1435708825, 26),
LeapSecond::new(1483228826, 27),
],
None,
)?;
let time_zone_ref = time_zone.as_ref();
assert!(matches!(time_zone_ref.unix_leap_time_to_unix_time(1136073621), Ok(1136073599)));
assert!(matches!(time_zone_ref.unix_leap_time_to_unix_time(1136073622), Ok(1136073600)));
assert!(matches!(time_zone_ref.unix_leap_time_to_unix_time(1136073623), Ok(1136073600)));
assert!(matches!(time_zone_ref.unix_leap_time_to_unix_time(1136073624), Ok(1136073601)));
assert!(matches!(time_zone_ref.unix_time_to_unix_leap_time(1136073599), Ok(1136073621)));
assert!(matches!(time_zone_ref.unix_time_to_unix_leap_time(1136073600), Ok(1136073623)));
assert!(matches!(time_zone_ref.unix_time_to_unix_leap_time(1136073601), Ok(1136073624)));
Ok(())
}
#[test]
fn test_leap_seconds_overflow() -> Result<(), Error> {
let time_zone_err = TimeZone::new(
vec![Transition::new(i64::MIN, 0)],
vec![LocalTimeType::UTC],
vec![LeapSecond::new(0, 1)],
Some(TransitionRule::from(LocalTimeType::UTC)),
);
assert!(time_zone_err.is_err());
let time_zone = TimeZone::new(
vec![Transition::new(i64::MAX, 0)],
vec![LocalTimeType::UTC],
vec![LeapSecond::new(0, 1)],
None,
)?;
assert!(matches!(
time_zone.find_local_time_type(i64::MAX),
Err(Error::FindLocalTimeType(_))
));
Ok(())
}
}
+171
View File
@@ -0,0 +1,171 @@
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::{cell::RefCell, collections::hash_map, env, fs, hash::Hasher, time::SystemTime};
use super::tz_info::TimeZone;
use super::{FixedOffset, NaiveDateTime};
use crate::MappedLocalTime;
pub(super) fn offset_from_utc_datetime(utc: &NaiveDateTime) -> MappedLocalTime<FixedOffset> {
offset(utc, false)
}
pub(super) fn offset_from_local_datetime(local: &NaiveDateTime) -> MappedLocalTime<FixedOffset> {
offset(local, true)
}
fn offset(d: &NaiveDateTime, local: bool) -> MappedLocalTime<FixedOffset> {
TZ_INFO.with(|maybe_cache| {
maybe_cache.borrow_mut().get_or_insert_with(Cache::default).offset(*d, local)
})
}
// we have to store the `Cache` in an option as it can't
// be initialized in a static context.
thread_local! {
static TZ_INFO: RefCell<Option<Cache>> = Default::default();
}
enum Source {
LocalTime { mtime: SystemTime },
Environment { hash: u64 },
}
impl Source {
fn new(env_tz: Option<&str>) -> Source {
match env_tz {
Some(tz) => {
let mut hasher = hash_map::DefaultHasher::new();
hasher.write(tz.as_bytes());
let hash = hasher.finish();
Source::Environment { hash }
}
None => match fs::symlink_metadata("/etc/localtime") {
Ok(data) => Source::LocalTime {
// we have to pick a sensible default when the mtime fails
// by picking SystemTime::now() we raise the probability of
// the cache being invalidated if/when the mtime starts working
mtime: data.modified().unwrap_or_else(|_| SystemTime::now()),
},
Err(_) => {
// as above, now() should be a better default than some constant
// TODO: see if we can improve caching in the case where the fallback is a valid timezone
Source::LocalTime { mtime: SystemTime::now() }
}
},
}
}
}
struct Cache {
zone: TimeZone,
source: Source,
last_checked: SystemTime,
}
#[cfg(target_os = "aix")]
const TZDB_LOCATION: &str = "/usr/share/lib/zoneinfo";
#[cfg(not(any(target_os = "android", target_os = "aix", target_env = "ohos")))]
const TZDB_LOCATION: &str = "/usr/share/zoneinfo";
fn fallback_timezone() -> Option<TimeZone> {
let tz_name = iana_time_zone::get_timezone().ok()?;
#[cfg(not(any(target_os = "android", target_env = "ohos")))]
let bytes = fs::read(format!("{TZDB_LOCATION}/{tz_name}")).ok()?;
#[cfg(any(target_os = "android", target_env = "ohos"))]
let bytes = crate::offset::local::tz_data::for_zone(&tz_name).ok()??;
TimeZone::from_tz_data(&bytes).ok()
}
impl Default for Cache {
fn default() -> Cache {
// default to UTC if no local timezone can be found
let env_tz = env::var("TZ").ok();
let env_ref = env_tz.as_deref();
Cache {
last_checked: SystemTime::now(),
source: Source::new(env_ref),
zone: current_zone(env_ref),
}
}
}
fn current_zone(var: Option<&str>) -> TimeZone {
TimeZone::local(var).ok().or_else(fallback_timezone).unwrap_or_else(TimeZone::utc)
}
impl Cache {
fn offset(&mut self, d: NaiveDateTime, local: bool) -> MappedLocalTime<FixedOffset> {
let now = SystemTime::now();
match now.duration_since(self.last_checked) {
// If the cache has been around for less than a second then we reuse it
// unconditionally. This is a reasonable tradeoff because the timezone
// generally won't be changing _that_ often, but if the time zone does
// change, it will reflect sufficiently quickly from an application
// user's perspective.
Ok(d) if d.as_secs() < 1 => (),
Ok(_) | Err(_) => {
let env_tz = env::var("TZ").ok();
let env_ref = env_tz.as_deref();
let new_source = Source::new(env_ref);
let out_of_date = match (&self.source, &new_source) {
// change from env to file or file to env, must recreate the zone
(Source::Environment { .. }, Source::LocalTime { .. })
| (Source::LocalTime { .. }, Source::Environment { .. }) => true,
// stay as file, but mtime has changed
(Source::LocalTime { mtime: old_mtime }, Source::LocalTime { mtime })
if old_mtime != mtime =>
{
true
}
// stay as env, but hash of variable has changed
(Source::Environment { hash: old_hash }, Source::Environment { hash })
if old_hash != hash =>
{
true
}
// cache can be reused
_ => false,
};
if out_of_date {
self.zone = current_zone(env_ref);
}
self.last_checked = now;
self.source = new_source;
}
}
if !local {
let offset = self
.zone
.find_local_time_type(d.and_utc().timestamp())
.expect("unable to select local time type")
.offset();
return match FixedOffset::east_opt(offset) {
Some(offset) => MappedLocalTime::Single(offset),
None => MappedLocalTime::None,
};
}
// we pass through the year as the year of a local point in time must either be valid in that locale, or
// the entire time was skipped in which case we will return MappedLocalTime::None anyway.
self.zone
.find_local_time_type_from_local(d)
.expect("unable to select local time type")
.and_then(|o| FixedOffset::east_opt(o.offset()))
}
}
+59
View File
@@ -0,0 +1,59 @@
#![allow(non_snake_case, non_upper_case_globals, non_camel_case_types, dead_code, clippy::all)]
windows_link::link!("kernel32.dll" "system" fn GetTimeZoneInformationForYear(wyear : u16, pdtzi : *const DYNAMIC_TIME_ZONE_INFORMATION, ptzi : *mut TIME_ZONE_INFORMATION) -> BOOL);
windows_link::link!("kernel32.dll" "system" fn SystemTimeToFileTime(lpsystemtime : *const SYSTEMTIME, lpfiletime : *mut FILETIME) -> BOOL);
windows_link::link!("kernel32.dll" "system" fn SystemTimeToTzSpecificLocalTime(lptimezoneinformation : *const TIME_ZONE_INFORMATION, lpuniversaltime : *const SYSTEMTIME, lplocaltime : *mut SYSTEMTIME) -> BOOL);
windows_link::link!("kernel32.dll" "system" fn TzSpecificLocalTimeToSystemTime(lptimezoneinformation : *const TIME_ZONE_INFORMATION, lplocaltime : *const SYSTEMTIME, lpuniversaltime : *mut SYSTEMTIME) -> BOOL);
pub type BOOL = i32;
#[repr(C)]
#[derive(Clone, Copy)]
pub struct DYNAMIC_TIME_ZONE_INFORMATION {
pub Bias: i32,
pub StandardName: [u16; 32],
pub StandardDate: SYSTEMTIME,
pub StandardBias: i32,
pub DaylightName: [u16; 32],
pub DaylightDate: SYSTEMTIME,
pub DaylightBias: i32,
pub TimeZoneKeyName: [u16; 128],
pub DynamicDaylightTimeDisabled: bool,
}
impl Default for DYNAMIC_TIME_ZONE_INFORMATION {
fn default() -> Self {
unsafe { core::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Clone, Copy, Default)]
pub struct FILETIME {
pub dwLowDateTime: u32,
pub dwHighDateTime: u32,
}
#[repr(C)]
#[derive(Clone, Copy, Default)]
pub struct SYSTEMTIME {
pub wYear: u16,
pub wMonth: u16,
pub wDayOfWeek: u16,
pub wDay: u16,
pub wHour: u16,
pub wMinute: u16,
pub wSecond: u16,
pub wMilliseconds: u16,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub struct TIME_ZONE_INFORMATION {
pub Bias: i32,
pub StandardName: [u16; 32],
pub StandardDate: SYSTEMTIME,
pub StandardBias: i32,
pub DaylightName: [u16; 32],
pub DaylightDate: SYSTEMTIME,
pub DaylightBias: i32,
}
impl Default for TIME_ZONE_INFORMATION {
fn default() -> Self {
unsafe { core::mem::zeroed() }
}
}
+293
View File
@@ -0,0 +1,293 @@
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cmp::Ordering;
use std::mem::MaybeUninit;
use std::ptr;
use super::win_bindings::{GetTimeZoneInformationForYear, SYSTEMTIME, TIME_ZONE_INFORMATION};
use crate::offset::local::{Transition, lookup_with_dst_transitions};
use crate::{Datelike, FixedOffset, MappedLocalTime, NaiveDate, NaiveDateTime, NaiveTime, Weekday};
// We don't use `SystemTimeToTzSpecificLocalTime` because it doesn't support the same range of dates
// as Chrono. Also it really isn't that difficult to work out the correct offset from the provided
// DST rules.
//
// This method uses `overflowing_sub_offset` because it is no problem if the transition time in UTC
// falls a couple of hours inside the buffer space around the `NaiveDateTime` range (although it is
// very theoretical to have a transition at midnight around `NaiveDate::(MIN|MAX)`.
pub(super) fn offset_from_utc_datetime(utc: &NaiveDateTime) -> MappedLocalTime<FixedOffset> {
// Using a `TzInfo` based on the year of an UTC datetime is technically wrong, we should be
// using the rules for the year of the corresponding local time. But this matches what
// `SystemTimeToTzSpecificLocalTime` is documented to do.
let tz_info = match TzInfo::for_year(utc.year()) {
Some(tz_info) => tz_info,
None => return MappedLocalTime::None,
};
let offset = match (tz_info.std_transition, tz_info.dst_transition) {
(Some(std_transition), Some(dst_transition)) => {
let std_transition_utc = std_transition.overflowing_sub_offset(tz_info.dst_offset);
let dst_transition_utc = dst_transition.overflowing_sub_offset(tz_info.std_offset);
if dst_transition_utc < std_transition_utc {
match utc >= &dst_transition_utc && utc < &std_transition_utc {
true => tz_info.dst_offset,
false => tz_info.std_offset,
}
} else {
match utc >= &std_transition_utc && utc < &dst_transition_utc {
true => tz_info.std_offset,
false => tz_info.dst_offset,
}
}
}
(Some(std_transition), None) => {
let std_transition_utc = std_transition.overflowing_sub_offset(tz_info.dst_offset);
match utc < &std_transition_utc {
true => tz_info.dst_offset,
false => tz_info.std_offset,
}
}
(None, Some(dst_transition)) => {
let dst_transition_utc = dst_transition.overflowing_sub_offset(tz_info.std_offset);
match utc < &dst_transition_utc {
true => tz_info.std_offset,
false => tz_info.dst_offset,
}
}
(None, None) => tz_info.std_offset,
};
MappedLocalTime::Single(offset)
}
// We don't use `TzSpecificLocalTimeToSystemTime` because it doesn't let us choose how to handle
// ambiguous cases (during a DST transition). Instead we get the timezone information for the
// current year and compute it ourselves, like we do on Unix.
pub(super) fn offset_from_local_datetime(local: &NaiveDateTime) -> MappedLocalTime<FixedOffset> {
let tz_info = match TzInfo::for_year(local.year()) {
Some(tz_info) => tz_info,
None => return MappedLocalTime::None,
};
// Create a sorted slice of transitions and use `lookup_with_dst_transitions`.
match (tz_info.std_transition, tz_info.dst_transition) {
(Some(std_transition), Some(dst_transition)) => {
let std_transition =
Transition::new(std_transition, tz_info.dst_offset, tz_info.std_offset);
let dst_transition =
Transition::new(dst_transition, tz_info.std_offset, tz_info.dst_offset);
let transitions = match std_transition.cmp(&dst_transition) {
Ordering::Less => [std_transition, dst_transition],
Ordering::Greater => [dst_transition, std_transition],
Ordering::Equal => {
// This doesn't make sense. Let's just return the standard offset.
return MappedLocalTime::Single(tz_info.std_offset);
}
};
lookup_with_dst_transitions(&transitions, *local)
}
(Some(std_transition), None) => {
let transitions =
[Transition::new(std_transition, tz_info.dst_offset, tz_info.std_offset)];
lookup_with_dst_transitions(&transitions, *local)
}
(None, Some(dst_transition)) => {
let transitions =
[Transition::new(dst_transition, tz_info.std_offset, tz_info.dst_offset)];
lookup_with_dst_transitions(&transitions, *local)
}
(None, None) => MappedLocalTime::Single(tz_info.std_offset),
}
}
// The basis for Windows timezone and DST support has been in place since Windows 2000. It does not
// allow for complex rules like the IANA timezone database:
// - A timezone has the same base offset the whole year.
// - There seem to be either zero or two DST transitions (but we support having just one).
// - As of Vista(?) only years from 2004 until a few years into the future are supported.
// - All other years get the base settings, which seem to be that of the current year.
//
// These details don't matter much, we just work with the offsets and transition dates Windows
// returns through `GetTimeZoneInformationForYear` for a particular year.
struct TzInfo {
// Offset from UTC during standard time.
std_offset: FixedOffset,
// Offset from UTC during daylight saving time.
dst_offset: FixedOffset,
// Transition from standard time to daylight saving time, given in local standard time.
std_transition: Option<NaiveDateTime>,
// Transition from daylight saving time to standard time, given in local daylight saving time.
dst_transition: Option<NaiveDateTime>,
}
impl TzInfo {
fn for_year(year: i32) -> Option<TzInfo> {
// The API limits years to 1601..=30827.
// Working with timezones and daylight saving time this far into the past or future makes
// little sense. But whatever is extrapolated for 1601 or 30827 is what can be extrapolated
// for years beyond.
let ref_year = year.clamp(1601, 30827) as u16;
let tz_info = unsafe {
let mut tz_info = MaybeUninit::<TIME_ZONE_INFORMATION>::uninit();
if GetTimeZoneInformationForYear(ref_year, ptr::null_mut(), tz_info.as_mut_ptr()) == 0 {
return None;
}
tz_info.assume_init()
};
let std_offset = (tz_info.Bias)
.checked_add(tz_info.StandardBias)
.and_then(|o| o.checked_mul(60))
.and_then(FixedOffset::west_opt)?;
let dst_offset = (tz_info.Bias)
.checked_add(tz_info.DaylightBias)
.and_then(|o| o.checked_mul(60))
.and_then(FixedOffset::west_opt)?;
Some(TzInfo {
std_offset,
dst_offset,
std_transition: naive_date_time_from_system_time(tz_info.StandardDate, year).ok()?,
dst_transition: naive_date_time_from_system_time(tz_info.DaylightDate, year).ok()?,
})
}
}
/// Resolve a `SYSTEMTIME` object to an `Option<NaiveDateTime>`.
///
/// A `SYSTEMTIME` within a `TIME_ZONE_INFORMATION` struct can be zero to indicate there is no
/// transition.
/// If it has year, month and day values it is a concrete date.
/// If the year is missing the `SYSTEMTIME` is a rule, which this method resolves for the provided
/// year. A rule has a month, weekday, and nth weekday of the month as components.
///
/// Returns `Err` if any of the values is invalid, which should never happen.
fn naive_date_time_from_system_time(
st: SYSTEMTIME,
year: i32,
) -> Result<Option<NaiveDateTime>, ()> {
if st.wYear == 0 && st.wMonth == 0 {
return Ok(None);
}
let time = NaiveTime::from_hms_milli_opt(
st.wHour as u32,
st.wMinute as u32,
st.wSecond as u32,
st.wMilliseconds as u32,
)
.ok_or(())?;
if st.wYear != 0 {
// We have a concrete date.
let date =
NaiveDate::from_ymd_opt(st.wYear as i32, st.wMonth as u32, st.wDay as u32).ok_or(())?;
return Ok(Some(date.and_time(time)));
}
// Resolve a rule with month, weekday, and nth weekday of the month to a date in the current
// year.
let weekday = match st.wDayOfWeek {
0 => Weekday::Sun,
1 => Weekday::Mon,
2 => Weekday::Tue,
3 => Weekday::Wed,
4 => Weekday::Thu,
5 => Weekday::Fri,
6 => Weekday::Sat,
_ => return Err(()),
};
let nth_day = match st.wDay {
1..=5 => st.wDay as u8,
_ => return Err(()),
};
let date = NaiveDate::from_weekday_of_month_opt(year, st.wMonth as u32, weekday, nth_day)
.or_else(|| NaiveDate::from_weekday_of_month_opt(year, st.wMonth as u32, weekday, 4))
.ok_or(())?; // `st.wMonth` must be invalid
Ok(Some(date.and_time(time)))
}
#[cfg(test)]
mod tests {
use crate::offset::local::win_bindings::{
FILETIME, SYSTEMTIME, SystemTimeToFileTime, TzSpecificLocalTimeToSystemTime,
};
use crate::{DateTime, FixedOffset, Local, NaiveDate, NaiveDateTime, TimeDelta};
use crate::{Datelike, TimeZone, Timelike};
use std::mem::MaybeUninit;
use std::ptr;
#[test]
fn verify_against_tz_specific_local_time_to_system_time() {
// The implementation in Windows itself is the source of truth on how to work with the OS
// timezone information. This test compares for every hour over a period of 125 years our
// implementation to `TzSpecificLocalTimeToSystemTime`.
//
// This uses parts of a previous Windows `Local` implementation in chrono.
fn from_local_time(dt: &NaiveDateTime) -> DateTime<Local> {
let st = system_time_from_naive_date_time(dt);
let utc_time = local_to_utc_time(&st);
let utc_secs = system_time_as_unix_seconds(&utc_time);
let local_secs = system_time_as_unix_seconds(&st);
let offset = (local_secs - utc_secs) as i32;
let offset = FixedOffset::east_opt(offset).unwrap();
DateTime::from_naive_utc_and_offset(*dt - offset, offset)
}
fn system_time_from_naive_date_time(dt: &NaiveDateTime) -> SYSTEMTIME {
SYSTEMTIME {
// Valid values: 1601-30827
wYear: dt.year() as u16,
// Valid values:1-12
wMonth: dt.month() as u16,
// Valid values: 0-6, starting Sunday.
// NOTE: enum returns 1-7, starting Monday, so we are
// off here, but this is not currently used in local.
wDayOfWeek: dt.weekday() as u16,
// Valid values: 1-31
wDay: dt.day() as u16,
// Valid values: 0-23
wHour: dt.hour() as u16,
// Valid values: 0-59
wMinute: dt.minute() as u16,
// Valid values: 0-59
wSecond: dt.second() as u16,
// Valid values: 0-999
wMilliseconds: 0,
}
}
fn local_to_utc_time(local: &SYSTEMTIME) -> SYSTEMTIME {
let mut sys_time = MaybeUninit::<SYSTEMTIME>::uninit();
unsafe { TzSpecificLocalTimeToSystemTime(ptr::null(), local, sys_time.as_mut_ptr()) };
// SAFETY: TzSpecificLocalTimeToSystemTime must have succeeded at this point, so we can
// assume the value is initialized.
unsafe { sys_time.assume_init() }
}
const HECTONANOSECS_IN_SEC: i64 = 10_000_000;
const HECTONANOSEC_TO_UNIX_EPOCH: i64 = 11_644_473_600 * HECTONANOSECS_IN_SEC;
fn system_time_as_unix_seconds(st: &SYSTEMTIME) -> i64 {
let mut init = MaybeUninit::<FILETIME>::uninit();
unsafe {
SystemTimeToFileTime(st, init.as_mut_ptr());
}
// SystemTimeToFileTime must have succeeded at this point, so we can assume the value is
// initialized.
let filetime = unsafe { init.assume_init() };
let bit_shift =
((filetime.dwHighDateTime as u64) << 32) | (filetime.dwLowDateTime as u64);
(bit_shift as i64 - HECTONANOSEC_TO_UNIX_EPOCH) / HECTONANOSECS_IN_SEC
}
let mut date = NaiveDate::from_ymd_opt(1975, 1, 1).unwrap().and_hms_opt(0, 30, 0).unwrap();
while date.year() < 2078 {
// Windows doesn't handle non-existing dates, it just treats it as valid.
if let Some(our_result) = Local.from_local_datetime(&date).earliest() {
assert_eq!(from_local_time(&date), our_result);
}
date += TimeDelta::try_hours(1).unwrap();
}
}
}
+715
View File
@@ -0,0 +1,715 @@
// This is a part of Chrono.
// See README.md and LICENSE.txt for details.
//! The time zone, which calculates offsets from the local time to UTC.
//!
//! There are four operations provided by the `TimeZone` trait:
//!
//! 1. Converting the local `NaiveDateTime` to `DateTime<Tz>`
//! 2. Converting the UTC `NaiveDateTime` to `DateTime<Tz>`
//! 3. Converting `DateTime<Tz>` to the local `NaiveDateTime`
//! 4. Constructing `DateTime<Tz>` objects from various offsets
//!
//! 1 is used for constructors. 2 is used for the `with_timezone` method of date and time types.
//! 3 is used for other methods, e.g. `year()` or `format()`, and provided by an associated type
//! which implements `Offset` (which then passed to `TimeZone` for actual implementations).
//! Technically speaking `TimeZone` has a total knowledge about given timescale,
//! but `Offset` is used as a cache to avoid the repeated conversion
//! and provides implementations for 1 and 3.
//! An `TimeZone` instance can be reconstructed from the corresponding `Offset` instance.
use core::fmt;
use crate::Weekday;
use crate::format::{ParseResult, Parsed, StrftimeItems, parse};
use crate::naive::{NaiveDate, NaiveDateTime, NaiveTime};
#[allow(deprecated)]
use crate::{Date, DateTime};
pub(crate) mod fixed;
pub use self::fixed::FixedOffset;
#[cfg(feature = "clock")]
pub(crate) mod local;
#[cfg(feature = "clock")]
pub use self::local::Local;
pub(crate) mod utc;
pub use self::utc::Utc;
/// The result of mapping a local time to a concrete instant in a given time zone.
///
/// The calculation to go from a local time (wall clock time) to an instant in UTC can end up in
/// three cases:
/// * A single, simple result.
/// * An ambiguous result when the clock is turned backwards during a transition due to for example
/// DST.
/// * No result when the clock is turned forwards during a transition due to for example DST.
///
/// <div class="warning">
///
/// In wasm, when using [`Local`], only the [`LocalResult::Single`] variant is returned.
/// Specifically:
///
/// * When the clock is turned backwards, where `Ambiguous(earliest, latest)` would be expected,
/// `Single(earliest)` is returned instead.
/// * When the clock is turned forwards, where `None` would be expected, `Single(t)` is returned,
/// with `t` being the requested local time represented as though there is no transition on that
/// day (i.e. still "summer time")
///
/// This is caused because of limitations in the JavaScript
/// [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
/// API, which always parses a local time as a single, valid time - even for an
/// input which describes a nonexistent or ambiguous time.
///
/// See further discussion and workarounds in <https://github.com/chronotope/chrono/issues/1701>.
///
/// </div>
///
/// When the clock is turned backwards it creates a _fold_ in local time, during which the local
/// time is _ambiguous_. When the clock is turned forwards it creates a _gap_ in local time, during
/// which the local time is _missing_, or does not exist.
///
/// Chrono does not return a default choice or invalid data during time zone transitions, but has
/// the `MappedLocalTime` type to help deal with the result correctly.
///
/// The type of `T` is usually a [`DateTime`] but may also be only an offset.
pub type MappedLocalTime<T> = LocalResult<T>;
#[derive(Clone, PartialEq, Debug, Copy, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
/// Old name of [`MappedLocalTime`]. See that type for more documentation.
pub enum LocalResult<T> {
/// The local time maps to a single unique result.
Single(T),
/// The local time is _ambiguous_ because there is a _fold_ in the local time.
///
/// This variant contains the two possible results, in the order `(earliest, latest)`.
Ambiguous(T, T),
/// The local time does not exist because there is a _gap_ in the local time.
///
/// This variant may also be returned if there was an error while resolving the local time,
/// caused by for example missing time zone data files, an error in an OS API, or overflow.
None,
}
impl<T> MappedLocalTime<T> {
/// Returns `Some` if the time zone mapping has a single result.
///
/// # Errors
///
/// Returns `None` if local time falls in a _fold_ or _gap_ in the local time, or if there was
/// an error.
#[must_use]
pub fn single(self) -> Option<T> {
match self {
MappedLocalTime::Single(t) => Some(t),
_ => None,
}
}
/// Returns the earliest possible result of the time zone mapping.
///
/// # Errors
///
/// Returns `None` if local time falls in a _gap_ in the local time, or if there was an error.
#[must_use]
pub fn earliest(self) -> Option<T> {
match self {
MappedLocalTime::Single(t) | MappedLocalTime::Ambiguous(t, _) => Some(t),
_ => None,
}
}
/// Returns the latest possible result of the time zone mapping.
///
/// # Errors
///
/// Returns `None` if local time falls in a _gap_ in the local time, or if there was an error.
#[must_use]
pub fn latest(self) -> Option<T> {
match self {
MappedLocalTime::Single(t) | MappedLocalTime::Ambiguous(_, t) => Some(t),
_ => None,
}
}
/// Maps a `MappedLocalTime<T>` into `MappedLocalTime<U>` with given function.
#[must_use]
pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> MappedLocalTime<U> {
match self {
MappedLocalTime::None => MappedLocalTime::None,
MappedLocalTime::Single(v) => MappedLocalTime::Single(f(v)),
MappedLocalTime::Ambiguous(min, max) => MappedLocalTime::Ambiguous(f(min), f(max)),
}
}
/// Maps a `MappedLocalTime<T>` into `MappedLocalTime<U>` with given function.
///
/// Returns `MappedLocalTime::None` if the function returns `None`.
#[must_use]
pub(crate) fn and_then<U, F: FnMut(T) -> Option<U>>(self, mut f: F) -> MappedLocalTime<U> {
match self {
MappedLocalTime::None => MappedLocalTime::None,
MappedLocalTime::Single(v) => match f(v) {
Some(new) => MappedLocalTime::Single(new),
None => MappedLocalTime::None,
},
MappedLocalTime::Ambiguous(min, max) => match (f(min), f(max)) {
(Some(min), Some(max)) => MappedLocalTime::Ambiguous(min, max),
_ => MappedLocalTime::None,
},
}
}
}
#[allow(deprecated)]
impl<Tz: TimeZone> MappedLocalTime<Date<Tz>> {
/// Makes a new `DateTime` from the current date and given `NaiveTime`.
/// The offset in the current date is preserved.
///
/// Propagates any error. Ambiguous result would be discarded.
#[inline]
#[must_use]
pub fn and_time(self, time: NaiveTime) -> MappedLocalTime<DateTime<Tz>> {
match self {
MappedLocalTime::Single(d) => {
d.and_time(time).map_or(MappedLocalTime::None, MappedLocalTime::Single)
}
_ => MappedLocalTime::None,
}
}
/// Makes a new `DateTime` from the current date, hour, minute and second.
/// The offset in the current date is preserved.
///
/// Propagates any error. Ambiguous result would be discarded.
#[inline]
#[must_use]
pub fn and_hms_opt(self, hour: u32, min: u32, sec: u32) -> MappedLocalTime<DateTime<Tz>> {
match self {
MappedLocalTime::Single(d) => {
d.and_hms_opt(hour, min, sec).map_or(MappedLocalTime::None, MappedLocalTime::Single)
}
_ => MappedLocalTime::None,
}
}
/// Makes a new `DateTime` from the current date, hour, minute, second and millisecond.
/// The millisecond part can exceed 1,000 in order to represent the leap second.
/// The offset in the current date is preserved.
///
/// Propagates any error. Ambiguous result would be discarded.
#[inline]
#[must_use]
pub fn and_hms_milli_opt(
self,
hour: u32,
min: u32,
sec: u32,
milli: u32,
) -> MappedLocalTime<DateTime<Tz>> {
match self {
MappedLocalTime::Single(d) => d
.and_hms_milli_opt(hour, min, sec, milli)
.map_or(MappedLocalTime::None, MappedLocalTime::Single),
_ => MappedLocalTime::None,
}
}
/// Makes a new `DateTime` from the current date, hour, minute, second and microsecond.
/// The microsecond part can exceed 1,000,000 in order to represent the leap second.
/// The offset in the current date is preserved.
///
/// Propagates any error. Ambiguous result would be discarded.
#[inline]
#[must_use]
pub fn and_hms_micro_opt(
self,
hour: u32,
min: u32,
sec: u32,
micro: u32,
) -> MappedLocalTime<DateTime<Tz>> {
match self {
MappedLocalTime::Single(d) => d
.and_hms_micro_opt(hour, min, sec, micro)
.map_or(MappedLocalTime::None, MappedLocalTime::Single),
_ => MappedLocalTime::None,
}
}
/// Makes a new `DateTime` from the current date, hour, minute, second and nanosecond.
/// The nanosecond part can exceed 1,000,000,000 in order to represent the leap second.
/// The offset in the current date is preserved.
///
/// Propagates any error. Ambiguous result would be discarded.
#[inline]
#[must_use]
pub fn and_hms_nano_opt(
self,
hour: u32,
min: u32,
sec: u32,
nano: u32,
) -> MappedLocalTime<DateTime<Tz>> {
match self {
MappedLocalTime::Single(d) => d
.and_hms_nano_opt(hour, min, sec, nano)
.map_or(MappedLocalTime::None, MappedLocalTime::Single),
_ => MappedLocalTime::None,
}
}
}
impl<T: fmt::Debug> MappedLocalTime<T> {
/// Returns a single unique conversion result or panics.
///
/// `unwrap()` is best combined with time zone types where the mapping can never fail like
/// [`Utc`] and [`FixedOffset`]. Note that for [`FixedOffset`] there is a rare case where a
/// resulting [`DateTime`] can be out of range.
///
/// # Panics
///
/// Panics if the local time falls within a _fold_ or a _gap_ in the local time, and on any
/// error that may have been returned by the type implementing [`TimeZone`].
#[must_use]
#[track_caller]
pub fn unwrap(self) -> T {
match self {
MappedLocalTime::None => panic!("No such local time"),
MappedLocalTime::Single(t) => t,
MappedLocalTime::Ambiguous(t1, t2) => {
panic!("Ambiguous local time, ranging from {t1:?} to {t2:?}")
}
}
}
}
/// The offset from the local time to UTC.
pub trait Offset: Sized + Clone + fmt::Debug {
/// Returns the fixed offset from UTC to the local time stored.
fn fix(&self) -> FixedOffset;
}
/// The time zone.
///
/// The methods here are the primary constructors for the [`DateTime`] type.
pub trait TimeZone: Sized + Clone {
/// An associated offset type.
/// This type is used to store the actual offset in date and time types.
/// The original `TimeZone` value can be recovered via `TimeZone::from_offset`.
type Offset: Offset;
/// Make a new `DateTime` from year, month, day, time components and current time zone.
///
/// This assumes the proleptic Gregorian calendar, with the year 0 being 1 BCE.
///
/// Returns `MappedLocalTime::None` on invalid input data.
fn with_ymd_and_hms(
&self,
year: i32,
month: u32,
day: u32,
hour: u32,
min: u32,
sec: u32,
) -> MappedLocalTime<DateTime<Self>> {
match NaiveDate::from_ymd_opt(year, month, day).and_then(|d| d.and_hms_opt(hour, min, sec))
{
Some(dt) => self.from_local_datetime(&dt),
None => MappedLocalTime::None,
}
}
/// Makes a new `Date` from year, month, day and the current time zone.
/// This assumes the proleptic Gregorian calendar, with the year 0 being 1 BCE.
///
/// The time zone normally does not affect the date (unless it is between UTC-24 and UTC+24),
/// but it will propagate to the `DateTime` values constructed via this date.
///
/// Panics on the out-of-range date, invalid month and/or day.
#[deprecated(since = "0.4.23", note = "use `with_ymd_and_hms()` instead")]
#[allow(deprecated)]
fn ymd(&self, year: i32, month: u32, day: u32) -> Date<Self> {
self.ymd_opt(year, month, day).unwrap()
}
/// Makes a new `Date` from year, month, day and the current time zone.
/// This assumes the proleptic Gregorian calendar, with the year 0 being 1 BCE.
///
/// The time zone normally does not affect the date (unless it is between UTC-24 and UTC+24),
/// but it will propagate to the `DateTime` values constructed via this date.
///
/// Returns `None` on the out-of-range date, invalid month and/or day.
#[deprecated(since = "0.4.23", note = "use `with_ymd_and_hms()` instead")]
#[allow(deprecated)]
fn ymd_opt(&self, year: i32, month: u32, day: u32) -> MappedLocalTime<Date<Self>> {
match NaiveDate::from_ymd_opt(year, month, day) {
Some(d) => self.from_local_date(&d),
None => MappedLocalTime::None,
}
}
/// Makes a new `Date` from year, day of year (DOY or "ordinal") and the current time zone.
/// This assumes the proleptic Gregorian calendar, with the year 0 being 1 BCE.
///
/// The time zone normally does not affect the date (unless it is between UTC-24 and UTC+24),
/// but it will propagate to the `DateTime` values constructed via this date.
///
/// Panics on the out-of-range date and/or invalid DOY.
#[deprecated(
since = "0.4.23",
note = "use `from_local_datetime()` with a `NaiveDateTime` instead"
)]
#[allow(deprecated)]
fn yo(&self, year: i32, ordinal: u32) -> Date<Self> {
self.yo_opt(year, ordinal).unwrap()
}
/// Makes a new `Date` from year, day of year (DOY or "ordinal") and the current time zone.
/// This assumes the proleptic Gregorian calendar, with the year 0 being 1 BCE.
///
/// The time zone normally does not affect the date (unless it is between UTC-24 and UTC+24),
/// but it will propagate to the `DateTime` values constructed via this date.
///
/// Returns `None` on the out-of-range date and/or invalid DOY.
#[deprecated(
since = "0.4.23",
note = "use `from_local_datetime()` with a `NaiveDateTime` instead"
)]
#[allow(deprecated)]
fn yo_opt(&self, year: i32, ordinal: u32) -> MappedLocalTime<Date<Self>> {
match NaiveDate::from_yo_opt(year, ordinal) {
Some(d) => self.from_local_date(&d),
None => MappedLocalTime::None,
}
}
/// Makes a new `Date` from ISO week date (year and week number), day of the week (DOW) and
/// the current time zone.
/// This assumes the proleptic Gregorian calendar, with the year 0 being 1 BCE.
/// The resulting `Date` may have a different year from the input year.
///
/// The time zone normally does not affect the date (unless it is between UTC-24 and UTC+24),
/// but it will propagate to the `DateTime` values constructed via this date.
///
/// Panics on the out-of-range date and/or invalid week number.
#[deprecated(
since = "0.4.23",
note = "use `from_local_datetime()` with a `NaiveDateTime` instead"
)]
#[allow(deprecated)]
fn isoywd(&self, year: i32, week: u32, weekday: Weekday) -> Date<Self> {
self.isoywd_opt(year, week, weekday).unwrap()
}
/// Makes a new `Date` from ISO week date (year and week number), day of the week (DOW) and
/// the current time zone.
/// This assumes the proleptic Gregorian calendar, with the year 0 being 1 BCE.
/// The resulting `Date` may have a different year from the input year.
///
/// The time zone normally does not affect the date (unless it is between UTC-24 and UTC+24),
/// but it will propagate to the `DateTime` values constructed via this date.
///
/// Returns `None` on the out-of-range date and/or invalid week number.
#[deprecated(
since = "0.4.23",
note = "use `from_local_datetime()` with a `NaiveDateTime` instead"
)]
#[allow(deprecated)]
fn isoywd_opt(&self, year: i32, week: u32, weekday: Weekday) -> MappedLocalTime<Date<Self>> {
match NaiveDate::from_isoywd_opt(year, week, weekday) {
Some(d) => self.from_local_date(&d),
None => MappedLocalTime::None,
}
}
/// Makes a new `DateTime` from the number of non-leap seconds
/// since January 1, 1970 0:00:00 UTC (aka "UNIX timestamp")
/// and the number of nanoseconds since the last whole non-leap second.
///
/// The nanosecond part can exceed 1,000,000,000 in order to represent a
/// [leap second](crate::NaiveTime#leap-second-handling), but only when `secs % 60 == 59`.
/// (The true "UNIX timestamp" cannot represent a leap second unambiguously.)
///
/// # Panics
///
/// Panics on the out-of-range number of seconds and/or invalid nanosecond,
/// for a non-panicking version see [`timestamp_opt`](#method.timestamp_opt).
#[deprecated(since = "0.4.23", note = "use `timestamp_opt()` instead")]
fn timestamp(&self, secs: i64, nsecs: u32) -> DateTime<Self> {
self.timestamp_opt(secs, nsecs).unwrap()
}
/// Makes a new `DateTime` from the number of non-leap seconds
/// since January 1, 1970 0:00:00 UTC (aka "UNIX timestamp")
/// and the number of nanoseconds since the last whole non-leap second.
///
/// The nanosecond part can exceed 1,000,000,000 in order to represent a
/// [leap second](crate::NaiveTime#leap-second-handling), but only when `secs % 60 == 59`.
/// (The true "UNIX timestamp" cannot represent a leap second unambiguously.)
///
/// # Errors
///
/// Returns `MappedLocalTime::None` on out-of-range number of seconds and/or
/// invalid nanosecond, otherwise always returns `MappedLocalTime::Single`.
///
/// # Example
///
/// ```
/// use chrono::{TimeZone, Utc};
///
/// assert_eq!(Utc.timestamp_opt(1431648000, 0).unwrap().to_string(), "2015-05-15 00:00:00 UTC");
/// ```
fn timestamp_opt(&self, secs: i64, nsecs: u32) -> MappedLocalTime<DateTime<Self>> {
match DateTime::from_timestamp(secs, nsecs) {
Some(dt) => MappedLocalTime::Single(self.from_utc_datetime(&dt.naive_utc())),
None => MappedLocalTime::None,
}
}
/// Makes a new `DateTime` from the number of non-leap milliseconds
/// since January 1, 1970 0:00:00 UTC (aka "UNIX timestamp").
///
/// Panics on out-of-range number of milliseconds for a non-panicking
/// version see [`timestamp_millis_opt`](#method.timestamp_millis_opt).
#[deprecated(since = "0.4.23", note = "use `timestamp_millis_opt()` instead")]
fn timestamp_millis(&self, millis: i64) -> DateTime<Self> {
self.timestamp_millis_opt(millis).unwrap()
}
/// Makes a new `DateTime` from the number of non-leap milliseconds
/// since January 1, 1970 0:00:00 UTC (aka "UNIX timestamp").
///
///
/// Returns `MappedLocalTime::None` on out-of-range number of milliseconds
/// and/or invalid nanosecond, otherwise always returns
/// `MappedLocalTime::Single`.
///
/// # Example
///
/// ```
/// use chrono::{MappedLocalTime, TimeZone, Utc};
/// match Utc.timestamp_millis_opt(1431648000) {
/// MappedLocalTime::Single(dt) => assert_eq!(dt.timestamp(), 1431648),
/// _ => panic!("Incorrect timestamp_millis"),
/// };
/// ```
fn timestamp_millis_opt(&self, millis: i64) -> MappedLocalTime<DateTime<Self>> {
match DateTime::from_timestamp_millis(millis) {
Some(dt) => MappedLocalTime::Single(self.from_utc_datetime(&dt.naive_utc())),
None => MappedLocalTime::None,
}
}
/// Makes a new `DateTime` from the number of non-leap nanoseconds
/// since January 1, 1970 0:00:00 UTC (aka "UNIX timestamp").
///
/// Unlike [`timestamp_millis_opt`](#method.timestamp_millis_opt), this never fails.
///
/// # Example
///
/// ```
/// use chrono::{TimeZone, Utc};
///
/// assert_eq!(Utc.timestamp_nanos(1431648000000000).timestamp(), 1431648);
/// ```
fn timestamp_nanos(&self, nanos: i64) -> DateTime<Self> {
self.from_utc_datetime(&DateTime::from_timestamp_nanos(nanos).naive_utc())
}
/// Makes a new `DateTime` from the number of non-leap microseconds
/// since January 1, 1970 0:00:00 UTC (aka "UNIX timestamp").
///
/// # Example
///
/// ```
/// use chrono::{TimeZone, Utc};
///
/// assert_eq!(Utc.timestamp_micros(1431648000000).unwrap().timestamp(), 1431648);
/// ```
fn timestamp_micros(&self, micros: i64) -> MappedLocalTime<DateTime<Self>> {
match DateTime::from_timestamp_micros(micros) {
Some(dt) => MappedLocalTime::Single(self.from_utc_datetime(&dt.naive_utc())),
None => MappedLocalTime::None,
}
}
/// Parses a string with the specified format string and returns a
/// `DateTime` with the current offset.
///
/// See the [`crate::format::strftime`] module on the
/// supported escape sequences.
///
/// If the to-be-parsed string includes an offset, it *must* match the
/// offset of the TimeZone, otherwise an error will be returned.
///
/// See also [`DateTime::parse_from_str`] which gives a [`DateTime`] with
/// parsed [`FixedOffset`].
///
/// See also [`NaiveDateTime::parse_from_str`] which gives a [`NaiveDateTime`] without
/// an offset, but can be converted to a [`DateTime`] with [`NaiveDateTime::and_utc`] or
/// [`NaiveDateTime::and_local_timezone`].
#[deprecated(
since = "0.4.29",
note = "use `DateTime::parse_from_str` or `NaiveDateTime::parse_from_str` with `and_utc()` or `and_local_timezone()` instead"
)]
fn datetime_from_str(&self, s: &str, fmt: &str) -> ParseResult<DateTime<Self>> {
let mut parsed = Parsed::new();
parse(&mut parsed, s, StrftimeItems::new(fmt))?;
parsed.to_datetime_with_timezone(self)
}
/// Reconstructs the time zone from the offset.
fn from_offset(offset: &Self::Offset) -> Self;
/// Creates the offset(s) for given local `NaiveDate` if possible.
fn offset_from_local_date(&self, local: &NaiveDate) -> MappedLocalTime<Self::Offset>;
/// Creates the offset(s) for given local `NaiveDateTime` if possible.
fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> MappedLocalTime<Self::Offset>;
/// Converts the local `NaiveDate` to the timezone-aware `Date` if possible.
#[allow(clippy::wrong_self_convention)]
#[deprecated(since = "0.4.23", note = "use `from_local_datetime()` instead")]
#[allow(deprecated)]
fn from_local_date(&self, local: &NaiveDate) -> MappedLocalTime<Date<Self>> {
self.offset_from_local_date(local).map(|offset| {
// since FixedOffset is within +/- 1 day, the date is never affected
Date::from_utc(*local, offset)
})
}
/// Converts the local `NaiveDateTime` to the timezone-aware `DateTime` if possible.
#[allow(clippy::wrong_self_convention)]
fn from_local_datetime(&self, local: &NaiveDateTime) -> MappedLocalTime<DateTime<Self>> {
self.offset_from_local_datetime(local).and_then(|off| {
local
.checked_sub_offset(off.fix())
.map(|dt| DateTime::from_naive_utc_and_offset(dt, off))
})
}
/// Creates the offset for given UTC `NaiveDate`. This cannot fail.
fn offset_from_utc_date(&self, utc: &NaiveDate) -> Self::Offset;
/// Creates the offset for given UTC `NaiveDateTime`. This cannot fail.
fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> Self::Offset;
/// Converts the UTC `NaiveDate` to the local time.
/// The UTC is continuous and thus this cannot fail (but can give the duplicate local time).
#[allow(clippy::wrong_self_convention)]
#[deprecated(since = "0.4.23", note = "use `from_utc_datetime()` instead")]
#[allow(deprecated)]
fn from_utc_date(&self, utc: &NaiveDate) -> Date<Self> {
Date::from_utc(*utc, self.offset_from_utc_date(utc))
}
/// Converts the UTC `NaiveDateTime` to the local time.
/// The UTC is continuous and thus this cannot fail (but can give the duplicate local time).
#[allow(clippy::wrong_self_convention)]
fn from_utc_datetime(&self, utc: &NaiveDateTime) -> DateTime<Self> {
DateTime::from_naive_utc_and_offset(*utc, self.offset_from_utc_datetime(utc))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fixed_offset_min_max_dates() {
for offset_hour in -23..=23 {
dbg!(offset_hour);
let offset = FixedOffset::east_opt(offset_hour * 60 * 60).unwrap();
let local_max = offset.from_utc_datetime(&NaiveDateTime::MAX);
assert_eq!(local_max.naive_utc(), NaiveDateTime::MAX);
let local_min = offset.from_utc_datetime(&NaiveDateTime::MIN);
assert_eq!(local_min.naive_utc(), NaiveDateTime::MIN);
let local_max = offset.from_local_datetime(&NaiveDateTime::MAX);
if offset_hour >= 0 {
assert_eq!(local_max.unwrap().naive_local(), NaiveDateTime::MAX);
} else {
assert_eq!(local_max, MappedLocalTime::None);
}
let local_min = offset.from_local_datetime(&NaiveDateTime::MIN);
if offset_hour <= 0 {
assert_eq!(local_min.unwrap().naive_local(), NaiveDateTime::MIN);
} else {
assert_eq!(local_min, MappedLocalTime::None);
}
}
}
#[test]
fn test_negative_millis() {
let dt = Utc.timestamp_millis_opt(-1000).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:59 UTC");
let dt = Utc.timestamp_millis_opt(-7000).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:53 UTC");
let dt = Utc.timestamp_millis_opt(-7001).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:52.999 UTC");
let dt = Utc.timestamp_millis_opt(-7003).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:52.997 UTC");
let dt = Utc.timestamp_millis_opt(-999).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:59.001 UTC");
let dt = Utc.timestamp_millis_opt(-1).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:59.999 UTC");
let dt = Utc.timestamp_millis_opt(-60000).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:00 UTC");
let dt = Utc.timestamp_millis_opt(-3600000).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:00:00 UTC");
for (millis, expected) in &[
(-7000, "1969-12-31 23:59:53 UTC"),
(-7001, "1969-12-31 23:59:52.999 UTC"),
(-7003, "1969-12-31 23:59:52.997 UTC"),
] {
match Utc.timestamp_millis_opt(*millis) {
MappedLocalTime::Single(dt) => {
assert_eq!(dt.to_string(), *expected);
}
e => panic!("Got {e:?} instead of an okay answer"),
}
}
}
#[test]
fn test_negative_nanos() {
let dt = Utc.timestamp_nanos(-1_000_000_000);
assert_eq!(dt.to_string(), "1969-12-31 23:59:59 UTC");
let dt = Utc.timestamp_nanos(-999_999_999);
assert_eq!(dt.to_string(), "1969-12-31 23:59:59.000000001 UTC");
let dt = Utc.timestamp_nanos(-1);
assert_eq!(dt.to_string(), "1969-12-31 23:59:59.999999999 UTC");
let dt = Utc.timestamp_nanos(-60_000_000_000);
assert_eq!(dt.to_string(), "1969-12-31 23:59:00 UTC");
let dt = Utc.timestamp_nanos(-3_600_000_000_000);
assert_eq!(dt.to_string(), "1969-12-31 23:00:00 UTC");
}
#[test]
fn test_nanos_never_panics() {
Utc.timestamp_nanos(i64::MAX);
Utc.timestamp_nanos(i64::default());
Utc.timestamp_nanos(i64::MIN);
}
#[test]
fn test_negative_micros() {
let dt = Utc.timestamp_micros(-1_000_000).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:59 UTC");
let dt = Utc.timestamp_micros(-999_999).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:59.000001 UTC");
let dt = Utc.timestamp_micros(-1).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:59.999999 UTC");
let dt = Utc.timestamp_micros(-60_000_000).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:59:00 UTC");
let dt = Utc.timestamp_micros(-3_600_000_000).unwrap();
assert_eq!(dt.to_string(), "1969-12-31 23:00:00 UTC");
}
}
+159
View File
@@ -0,0 +1,159 @@
// This is a part of Chrono.
// See README.md and LICENSE.txt for details.
//! The UTC (Coordinated Universal Time) time zone.
use core::fmt;
#[cfg(all(
feature = "now",
not(all(
target_arch = "wasm32",
feature = "wasmbind",
not(any(target_os = "emscripten", target_os = "wasi", target_os = "linux"))
))
))]
use std::time::{SystemTime, UNIX_EPOCH};
#[cfg(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))]
use rkyv::{Archive, Deserialize, Serialize};
use super::{FixedOffset, MappedLocalTime, Offset, TimeZone};
use crate::naive::{NaiveDate, NaiveDateTime};
#[cfg(feature = "now")]
#[allow(deprecated)]
use crate::{Date, DateTime};
/// The UTC time zone. This is the most efficient time zone when you don't need the local time.
/// It is also used as an offset (which is also a dummy type).
///
/// Using the [`TimeZone`](./trait.TimeZone.html) methods
/// on the UTC struct is the preferred way to construct `DateTime<Utc>`
/// instances.
///
/// # Example
///
/// ```
/// use chrono::{DateTime, TimeZone, Utc};
///
/// let dt = DateTime::from_timestamp(61, 0).unwrap();
///
/// assert_eq!(Utc.timestamp_opt(61, 0).unwrap(), dt);
/// assert_eq!(Utc.with_ymd_and_hms(1970, 1, 1, 0, 1, 1).unwrap(), dt);
/// ```
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(
any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"),
derive(Archive, Deserialize, Serialize),
archive(compare(PartialEq)),
archive_attr(derive(Clone, Copy, PartialEq, Eq, Debug, Hash))
)]
#[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
#[cfg_attr(all(feature = "arbitrary", feature = "std"), derive(arbitrary::Arbitrary))]
pub struct Utc;
#[cfg(feature = "now")]
impl Utc {
/// Returns a `Date` which corresponds to the current date.
#[deprecated(
since = "0.4.23",
note = "use `Utc::now()` instead, potentially with `.date_naive()`"
)]
#[allow(deprecated)]
#[must_use]
pub fn today() -> Date<Utc> {
Utc::now().date()
}
/// Returns a `DateTime<Utc>` which corresponds to the current date and time in UTC.
///
/// See also the similar [`Local::now()`] which returns `DateTime<Local>`, i.e. the local date
/// and time including offset from UTC.
///
/// [`Local::now()`]: crate::Local::now
///
/// # Example
///
/// ```
/// # #![allow(unused_variables)]
/// # use chrono::{FixedOffset, Utc};
/// // Current time in UTC
/// let now_utc = Utc::now();
///
/// // Current date in UTC
/// let today_utc = now_utc.date_naive();
///
/// // Current time in some timezone (let's use +05:00)
/// let offset = FixedOffset::east_opt(5 * 60 * 60).unwrap();
/// let now_with_offset = Utc::now().with_timezone(&offset);
/// ```
#[cfg(not(all(
target_arch = "wasm32",
feature = "wasmbind",
not(any(target_os = "emscripten", target_os = "wasi", target_os = "linux"))
)))]
#[must_use]
pub fn now() -> DateTime<Utc> {
let now =
SystemTime::now().duration_since(UNIX_EPOCH).expect("system time before Unix epoch");
DateTime::from_timestamp(now.as_secs() as i64, now.subsec_nanos()).unwrap()
}
/// Returns a `DateTime` which corresponds to the current date and time.
#[cfg(all(
target_arch = "wasm32",
feature = "wasmbind",
not(any(target_os = "emscripten", target_os = "wasi", target_os = "linux"))
))]
#[must_use]
pub fn now() -> DateTime<Utc> {
let now = js_sys::Date::new_0();
DateTime::<Utc>::from(now)
}
}
impl TimeZone for Utc {
type Offset = Utc;
fn from_offset(_state: &Utc) -> Utc {
Utc
}
fn offset_from_local_date(&self, _local: &NaiveDate) -> MappedLocalTime<Utc> {
MappedLocalTime::Single(Utc)
}
fn offset_from_local_datetime(&self, _local: &NaiveDateTime) -> MappedLocalTime<Utc> {
MappedLocalTime::Single(Utc)
}
fn offset_from_utc_date(&self, _utc: &NaiveDate) -> Utc {
Utc
}
fn offset_from_utc_datetime(&self, _utc: &NaiveDateTime) -> Utc {
Utc
}
}
impl Offset for Utc {
fn fix(&self) -> FixedOffset {
FixedOffset::east_opt(0).unwrap()
}
}
impl fmt::Debug for Utc {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Z")
}
}
impl fmt::Display for Utc {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "UTC")
}
}
#[cfg(feature = "defmt")]
impl defmt::Format for Utc {
fn format(&self, fmt: defmt::Formatter) {
defmt::write!(fmt, "Z");
}
}