diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:02:58 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:02:58 +0000 |
commit | 698f8c2f01ea549d77d7dc3338a12e04c11057b9 (patch) | |
tree | 173a775858bd501c378080a10dca74132f05bc50 /vendor/chrono/src/offset | |
parent | Initial commit. (diff) | |
download | rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.tar.xz rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.zip |
Adding upstream version 1.64.0+dfsg1.upstream/1.64.0+dfsg1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vendor/chrono/src/offset')
-rw-r--r-- | vendor/chrono/src/offset/fixed.rs | 244 | ||||
-rw-r--r-- | vendor/chrono/src/offset/local.rs | 227 | ||||
-rw-r--r-- | vendor/chrono/src/offset/mod.rs | 531 | ||||
-rw-r--r-- | vendor/chrono/src/offset/utc.rs | 100 |
4 files changed, 1102 insertions, 0 deletions
diff --git a/vendor/chrono/src/offset/fixed.rs b/vendor/chrono/src/offset/fixed.rs new file mode 100644 index 000000000..83f42a1a4 --- /dev/null +++ b/vendor/chrono/src/offset/fixed.rs @@ -0,0 +1,244 @@ +// 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::ops::{Add, Sub}; +use oldtime::Duration as OldDuration; + +use super::{LocalResult, Offset, TimeZone}; +use div::div_mod_floor; +use naive::{NaiveDate, NaiveDateTime, NaiveTime}; +use DateTime; +use Timelike; + +/// 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`](#method.east) and +/// [`west`](#method.west) methods for examples. +#[derive(PartialEq, Eq, Hash, Copy, Clone)] +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`. + /// + /// # Example + /// + /// ~~~~ + /// use chrono::{FixedOffset, TimeZone}; + /// let hour = 3600; + /// let datetime = FixedOffset::east(5 * hour).ymd(2016, 11, 08) + /// .and_hms(0, 0, 0); + /// assert_eq!(&datetime.to_rfc3339(), "2016-11-08T00:00:00+05:00") + /// ~~~~ + 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`. + pub 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`. + /// + /// # Example + /// + /// ~~~~ + /// use chrono::{FixedOffset, TimeZone}; + /// let hour = 3600; + /// let datetime = FixedOffset::west(5 * hour).ymd(2016, 11, 08) + /// .and_hms(0, 0, 0); + /// assert_eq!(&datetime.to_rfc3339(), "2016-11-08T00:00:00-05:00") + /// ~~~~ + 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`. + pub 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 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 fn utc_minus_local(&self) -> i32 { + -self.local_minus_utc + } +} + +impl TimeZone for FixedOffset { + type Offset = FixedOffset; + + fn from_offset(offset: &FixedOffset) -> FixedOffset { + *offset + } + + fn offset_from_local_date(&self, _local: &NaiveDate) -> LocalResult<FixedOffset> { + LocalResult::Single(*self) + } + fn offset_from_local_datetime(&self, _local: &NaiveDateTime) -> LocalResult<FixedOffset> { + LocalResult::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 (mins, sec) = div_mod_floor(offset, 60); + let (hour, min) = div_mod_floor(mins, 60); + if sec == 0 { + write!(f, "{}{:02}:{:02}", sign, hour, min) + } else { + write!(f, "{}{:02}:{:02}:{:02}", sign, hour, min, sec) + } + } +} + +impl fmt::Display for FixedOffset { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(self, f) + } +} + +// addition or subtraction of FixedOffset to/from Timelike values is the same as +// adding or subtracting the offset's local_minus_utc value +// but keep keeps the leap second information. +// this should be implemented more efficiently, but for the time being, this is generic right now. + +fn add_with_leapsecond<T>(lhs: &T, rhs: i32) -> T +where + T: Timelike + Add<OldDuration, Output = T>, +{ + // extract and temporarily remove the fractional part and later recover it + let nanos = lhs.nanosecond(); + let lhs = lhs.with_nanosecond(0).unwrap(); + (lhs + OldDuration::seconds(i64::from(rhs))).with_nanosecond(nanos).unwrap() +} + +impl Add<FixedOffset> for NaiveTime { + type Output = NaiveTime; + + #[inline] + fn add(self, rhs: FixedOffset) -> NaiveTime { + add_with_leapsecond(&self, rhs.local_minus_utc) + } +} + +impl Sub<FixedOffset> for NaiveTime { + type Output = NaiveTime; + + #[inline] + fn sub(self, rhs: FixedOffset) -> NaiveTime { + add_with_leapsecond(&self, -rhs.local_minus_utc) + } +} + +impl Add<FixedOffset> for NaiveDateTime { + type Output = NaiveDateTime; + + #[inline] + fn add(self, rhs: FixedOffset) -> NaiveDateTime { + add_with_leapsecond(&self, rhs.local_minus_utc) + } +} + +impl Sub<FixedOffset> for NaiveDateTime { + type Output = NaiveDateTime; + + #[inline] + fn sub(self, rhs: FixedOffset) -> NaiveDateTime { + add_with_leapsecond(&self, -rhs.local_minus_utc) + } +} + +impl<Tz: TimeZone> Add<FixedOffset> for DateTime<Tz> { + type Output = DateTime<Tz>; + + #[inline] + fn add(self, rhs: FixedOffset) -> DateTime<Tz> { + add_with_leapsecond(&self, rhs.local_minus_utc) + } +} + +impl<Tz: TimeZone> Sub<FixedOffset> for DateTime<Tz> { + type Output = DateTime<Tz>; + + #[inline] + fn sub(self, rhs: FixedOffset) -> DateTime<Tz> { + add_with_leapsecond(&self, -rhs.local_minus_utc) + } +} + +#[cfg(test)] +mod tests { + use super::FixedOffset; + use offset::TimeZone; + + #[test] + fn test_date_extreme_offset() { + // starting from 0.3 we don't have an offset exceeding one day. + // this makes everything easier! + assert_eq!( + format!("{:?}", FixedOffset::east(86399).ymd(2012, 2, 29)), + "2012-02-29+23:59:59".to_string() + ); + assert_eq!( + format!("{:?}", FixedOffset::east(86399).ymd(2012, 2, 29).and_hms(5, 6, 7)), + "2012-02-29T05:06:07+23:59:59".to_string() + ); + assert_eq!( + format!("{:?}", FixedOffset::west(86399).ymd(2012, 3, 4)), + "2012-03-04-23:59:59".to_string() + ); + assert_eq!( + format!("{:?}", FixedOffset::west(86399).ymd(2012, 3, 4).and_hms(5, 6, 7)), + "2012-03-04T05:06:07-23:59:59".to_string() + ); + } +} diff --git a/vendor/chrono/src/offset/local.rs b/vendor/chrono/src/offset/local.rs new file mode 100644 index 000000000..1abb3a9db --- /dev/null +++ b/vendor/chrono/src/offset/local.rs @@ -0,0 +1,227 @@ +// This is a part of Chrono. +// See README.md and LICENSE.txt for details. + +//! The local (system) time zone. + +#[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind")))] +use sys::{self, Timespec}; + +use super::fixed::FixedOffset; +use super::{LocalResult, TimeZone}; +#[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind")))] +use naive::NaiveTime; +use naive::{NaiveDate, NaiveDateTime}; +use {Date, DateTime}; +#[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind")))] +use {Datelike, Timelike}; + +/// Converts a `time::Tm` struct into the timezone-aware `DateTime`. +/// This assumes that `time` is working correctly, i.e. any error is fatal. +#[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind")))] +fn tm_to_datetime(mut tm: sys::Tm) -> DateTime<Local> { + if tm.tm_sec >= 60 { + tm.tm_nsec += (tm.tm_sec - 59) * 1_000_000_000; + tm.tm_sec = 59; + } + + #[cfg(not(windows))] + fn tm_to_naive_date(tm: &sys::Tm) -> NaiveDate { + // from_yo is more efficient than from_ymd (since it's the internal representation). + NaiveDate::from_yo(tm.tm_year + 1900, tm.tm_yday as u32 + 1) + } + + #[cfg(windows)] + fn tm_to_naive_date(tm: &sys::Tm) -> NaiveDate { + // ...but tm_yday is broken in Windows (issue #85) + NaiveDate::from_ymd(tm.tm_year + 1900, tm.tm_mon as u32 + 1, tm.tm_mday as u32) + } + + let date = tm_to_naive_date(&tm); + let time = NaiveTime::from_hms_nano( + tm.tm_hour as u32, + tm.tm_min as u32, + tm.tm_sec as u32, + tm.tm_nsec as u32, + ); + let offset = FixedOffset::east(tm.tm_utcoff); + DateTime::from_utc(date.and_time(time) - offset, offset) +} + +/// Converts a local `NaiveDateTime` to the `time::Timespec`. +#[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind")))] +fn datetime_to_timespec(d: &NaiveDateTime, local: bool) -> sys::Timespec { + // well, this exploits an undocumented `Tm::to_timespec` behavior + // to get the exact function we want (either `timegm` or `mktime`). + // the number 1 is arbitrary but should be non-zero to trigger `mktime`. + let tm_utcoff = if local { 1 } else { 0 }; + + let tm = sys::Tm { + tm_sec: d.second() as i32, + tm_min: d.minute() as i32, + tm_hour: d.hour() as i32, + tm_mday: d.day() as i32, + tm_mon: d.month0() as i32, // yes, C is that strange... + tm_year: d.year() - 1900, // this doesn't underflow, we know that d is `NaiveDateTime`. + tm_wday: 0, // to_local ignores this + tm_yday: 0, // and this + tm_isdst: -1, + tm_utcoff: tm_utcoff, + // do not set this, OS APIs are heavily inconsistent in terms of leap second handling + tm_nsec: 0, + }; + + tm.to_timespec() +} + +/// The local timescale. This is implemented via the standard `time` crate. +/// +/// Using the [`TimeZone`](./trait.TimeZone.html) methods +/// on the Local struct is the preferred way to construct `DateTime<Local>` +/// instances. +/// +/// # Example +/// +/// ~~~~ +/// use chrono::{Local, DateTime, TimeZone}; +/// +/// let dt: DateTime<Local> = Local::now(); +/// let dt: DateTime<Local> = Local.timestamp(0, 0); +/// ~~~~ +#[derive(Copy, Clone, Debug)] +pub struct Local; + +impl Local { + /// Returns a `Date` which corresponds to the current date. + pub fn today() -> Date<Local> { + Local::now().date() + } + + /// Returns a `DateTime` which corresponds to the current date. + #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind")))] + pub fn now() -> DateTime<Local> { + tm_to_datetime(Timespec::now().local()) + } + + /// Returns a `DateTime` which corresponds to the current date. + #[cfg(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind"))] + pub fn now() -> DateTime<Local> { + use super::Utc; + let now: DateTime<Utc> = super::Utc::now(); + + // Workaround missing timezone logic in `time` crate + let offset = FixedOffset::west((js_sys::Date::new_0().get_timezone_offset() as i32) * 60); + DateTime::from_utc(now.naive_utc(), offset) + } +} + +impl TimeZone for Local { + type Offset = FixedOffset; + + fn from_offset(_offset: &FixedOffset) -> Local { + Local + } + + // they are easier to define in terms of the finished date and time unlike other offsets + fn offset_from_local_date(&self, local: &NaiveDate) -> LocalResult<FixedOffset> { + self.from_local_date(local).map(|date| *date.offset()) + } + + fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<FixedOffset> { + self.from_local_datetime(local).map(|datetime| *datetime.offset()) + } + + fn offset_from_utc_date(&self, utc: &NaiveDate) -> FixedOffset { + *self.from_utc_date(utc).offset() + } + + fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> FixedOffset { + *self.from_utc_datetime(utc).offset() + } + + // override them for avoiding redundant works + fn from_local_date(&self, local: &NaiveDate) -> LocalResult<Date<Local>> { + // this sounds very strange, but required for keeping `TimeZone::ymd` sane. + // in the other words, we use the offset at the local midnight + // but keep the actual date unaltered (much like `FixedOffset`). + let midnight = self.from_local_datetime(&local.and_hms(0, 0, 0)); + midnight.map(|datetime| Date::from_utc(*local, *datetime.offset())) + } + + #[cfg(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind"))] + fn from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<DateTime<Local>> { + let mut local = local.clone(); + // Get the offset from the js runtime + let offset = FixedOffset::west((js_sys::Date::new_0().get_timezone_offset() as i32) * 60); + local -= ::Duration::seconds(offset.local_minus_utc() as i64); + LocalResult::Single(DateTime::from_utc(local, offset)) + } + + #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind")))] + fn from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<DateTime<Local>> { + let timespec = datetime_to_timespec(local, true); + + // datetime_to_timespec completely ignores leap seconds, so we need to adjust for them + let mut tm = timespec.local(); + assert_eq!(tm.tm_nsec, 0); + tm.tm_nsec = local.nanosecond() as i32; + + LocalResult::Single(tm_to_datetime(tm)) + } + + fn from_utc_date(&self, utc: &NaiveDate) -> Date<Local> { + let midnight = self.from_utc_datetime(&utc.and_hms(0, 0, 0)); + Date::from_utc(*utc, *midnight.offset()) + } + + #[cfg(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind"))] + fn from_utc_datetime(&self, utc: &NaiveDateTime) -> DateTime<Local> { + // Get the offset from the js runtime + let offset = FixedOffset::west((js_sys::Date::new_0().get_timezone_offset() as i32) * 60); + DateTime::from_utc(*utc, offset) + } + + #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind")))] + fn from_utc_datetime(&self, utc: &NaiveDateTime) -> DateTime<Local> { + let timespec = datetime_to_timespec(utc, false); + + // datetime_to_timespec completely ignores leap seconds, so we need to adjust for them + let mut tm = timespec.local(); + assert_eq!(tm.tm_nsec, 0); + tm.tm_nsec = utc.nanosecond() as i32; + + tm_to_datetime(tm) + } +} + +#[cfg(test)] +mod tests { + use super::Local; + use offset::TimeZone; + use Datelike; + + #[test] + fn test_local_date_sanity_check() { + // issue #27 + assert_eq!(Local.ymd(2999, 12, 28).day(), 28); + } + + #[test] + fn test_leap_second() { + // issue #123 + let today = Local::today(); + + let dt = today.and_hms_milli(1, 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 == "01:02:60" || timestr == "01:03:00", "unexpected timestr {:?}", timestr); + + let dt = today.and_hms_milli(1, 2, 3, 1234); + let timestr = dt.time().to_string(); + assert!( + timestr == "01:02:03.234" || timestr == "01:02:04.234", + "unexpected timestr {:?}", + timestr + ); + } +} diff --git a/vendor/chrono/src/offset/mod.rs b/vendor/chrono/src/offset/mod.rs new file mode 100644 index 000000000..0da6bfb42 --- /dev/null +++ b/vendor/chrono/src/offset/mod.rs @@ -0,0 +1,531 @@ +// 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 format::{parse, ParseResult, Parsed, StrftimeItems}; +use naive::{NaiveDate, NaiveDateTime, NaiveTime}; +use Weekday; +use {Date, DateTime}; + +/// The conversion result from the local time to the timezone-aware datetime types. +#[derive(Clone, PartialEq, Debug, Copy, Eq, Hash)] +pub enum LocalResult<T> { + /// Given local time representation is invalid. + /// This can occur when, for example, the positive timezone transition. + None, + /// Given local time representation has a single unique result. + Single(T), + /// Given local time representation has multiple results and thus ambiguous. + /// This can occur when, for example, the negative timezone transition. + Ambiguous(T /*min*/, T /*max*/), +} + +impl<T> LocalResult<T> { + /// Returns `Some` only when the conversion result is unique, or `None` otherwise. + pub fn single(self) -> Option<T> { + match self { + LocalResult::Single(t) => Some(t), + _ => None, + } + } + + /// Returns `Some` for the earliest possible conversion result, or `None` if none. + pub fn earliest(self) -> Option<T> { + match self { + LocalResult::Single(t) | LocalResult::Ambiguous(t, _) => Some(t), + _ => None, + } + } + + /// Returns `Some` for the latest possible conversion result, or `None` if none. + pub fn latest(self) -> Option<T> { + match self { + LocalResult::Single(t) | LocalResult::Ambiguous(_, t) => Some(t), + _ => None, + } + } + + /// Maps a `LocalResult<T>` into `LocalResult<U>` with given function. + pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> LocalResult<U> { + match self { + LocalResult::None => LocalResult::None, + LocalResult::Single(v) => LocalResult::Single(f(v)), + LocalResult::Ambiguous(min, max) => LocalResult::Ambiguous(f(min), f(max)), + } + } +} + +impl<Tz: TimeZone> LocalResult<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] + pub fn and_time(self, time: NaiveTime) -> LocalResult<DateTime<Tz>> { + match self { + LocalResult::Single(d) => { + d.and_time(time).map_or(LocalResult::None, LocalResult::Single) + } + _ => LocalResult::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] + pub fn and_hms_opt(self, hour: u32, min: u32, sec: u32) -> LocalResult<DateTime<Tz>> { + match self { + LocalResult::Single(d) => { + d.and_hms_opt(hour, min, sec).map_or(LocalResult::None, LocalResult::Single) + } + _ => LocalResult::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] + pub fn and_hms_milli_opt( + self, + hour: u32, + min: u32, + sec: u32, + milli: u32, + ) -> LocalResult<DateTime<Tz>> { + match self { + LocalResult::Single(d) => d + .and_hms_milli_opt(hour, min, sec, milli) + .map_or(LocalResult::None, LocalResult::Single), + _ => LocalResult::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] + pub fn and_hms_micro_opt( + self, + hour: u32, + min: u32, + sec: u32, + micro: u32, + ) -> LocalResult<DateTime<Tz>> { + match self { + LocalResult::Single(d) => d + .and_hms_micro_opt(hour, min, sec, micro) + .map_or(LocalResult::None, LocalResult::Single), + _ => LocalResult::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] + pub fn and_hms_nano_opt( + self, + hour: u32, + min: u32, + sec: u32, + nano: u32, + ) -> LocalResult<DateTime<Tz>> { + match self { + LocalResult::Single(d) => d + .and_hms_nano_opt(hour, min, sec, nano) + .map_or(LocalResult::None, LocalResult::Single), + _ => LocalResult::None, + } + } +} + +impl<T: fmt::Debug> LocalResult<T> { + /// Returns the single unique conversion result, or panics accordingly. + pub fn unwrap(self) -> T { + match self { + LocalResult::None => panic!("No such local time"), + LocalResult::Single(t) => t, + LocalResult::Ambiguous(t1, t2) => { + panic!("Ambiguous local time, ranging from {:?} to {:?}", t1, 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 primarily constructors for [`Date`](../struct.Date.html) and +/// [`DateTime`](../struct.DateTime.html) types. +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; + + /// 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. + /// + /// # Example + /// + /// ~~~~ + /// use chrono::{Utc, TimeZone}; + /// + /// assert_eq!(Utc.ymd(2015, 5, 15).to_string(), "2015-05-15UTC"); + /// ~~~~ + 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. + /// + /// # Example + /// + /// ~~~~ + /// use chrono::{Utc, LocalResult, TimeZone}; + /// + /// assert_eq!(Utc.ymd_opt(2015, 5, 15).unwrap().to_string(), "2015-05-15UTC"); + /// assert_eq!(Utc.ymd_opt(2000, 0, 0), LocalResult::None); + /// ~~~~ + fn ymd_opt(&self, year: i32, month: u32, day: u32) -> LocalResult<Date<Self>> { + match NaiveDate::from_ymd_opt(year, month, day) { + Some(d) => self.from_local_date(&d), + None => LocalResult::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. + /// + /// # Example + /// + /// ~~~~ + /// use chrono::{Utc, TimeZone}; + /// + /// assert_eq!(Utc.yo(2015, 135).to_string(), "2015-05-15UTC"); + /// ~~~~ + 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. + fn yo_opt(&self, year: i32, ordinal: u32) -> LocalResult<Date<Self>> { + match NaiveDate::from_yo_opt(year, ordinal) { + Some(d) => self.from_local_date(&d), + None => LocalResult::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. + /// + /// # Example + /// + /// ~~~~ + /// use chrono::{Utc, Weekday, TimeZone}; + /// + /// assert_eq!(Utc.isoywd(2015, 20, Weekday::Fri).to_string(), "2015-05-15UTC"); + /// ~~~~ + 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. + fn isoywd_opt(&self, year: i32, week: u32, weekday: Weekday) -> LocalResult<Date<Self>> { + match NaiveDate::from_isoywd_opt(year, week, weekday) { + Some(d) => self.from_local_date(&d), + None => LocalResult::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. + /// + /// Panics on the out-of-range number of seconds and/or invalid nanosecond, + /// for a non-panicking version see [`timestamp_opt`](#method.timestamp_opt). + /// + /// # Example + /// + /// ~~~~ + /// use chrono::{Utc, TimeZone}; + /// + /// assert_eq!(Utc.timestamp(1431648000, 0).to_string(), "2015-05-15 00:00:00 UTC"); + /// ~~~~ + 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. + /// + /// Returns `LocalResult::None` on out-of-range number of seconds and/or + /// invalid nanosecond, otherwise always returns `LocalResult::Single`. + fn timestamp_opt(&self, secs: i64, nsecs: u32) -> LocalResult<DateTime<Self>> { + match NaiveDateTime::from_timestamp_opt(secs, nsecs) { + Some(dt) => LocalResult::Single(self.from_utc_datetime(&dt)), + None => LocalResult::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). + /// + /// # Example + /// + /// ~~~~ + /// use chrono::{Utc, TimeZone}; + /// + /// assert_eq!(Utc.timestamp_millis(1431648000).timestamp(), 1431648); + /// ~~~~ + 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 `LocalResult::None` on out-of-range number of milliseconds + /// and/or invalid nanosecond, otherwise always returns + /// `LocalResult::Single`. + /// + /// # Example + /// + /// ~~~~ + /// use chrono::{Utc, TimeZone, LocalResult}; + /// match Utc.timestamp_millis_opt(1431648000) { + /// LocalResult::Single(dt) => assert_eq!(dt.timestamp(), 1431648), + /// _ => panic!("Incorrect timestamp_millis"), + /// }; + /// ~~~~ + fn timestamp_millis_opt(&self, millis: i64) -> LocalResult<DateTime<Self>> { + let (mut secs, mut millis) = (millis / 1000, millis % 1000); + if millis < 0 { + secs -= 1; + millis += 1000; + } + self.timestamp_opt(secs, millis as u32 * 1_000_000) + } + + /// 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`](#method.timestamp_millis), this never + /// panics. + /// + /// # Example + /// + /// ~~~~ + /// use chrono::{Utc, TimeZone}; + /// + /// assert_eq!(Utc.timestamp_nanos(1431648000000000).timestamp(), 1431648); + /// ~~~~ + fn timestamp_nanos(&self, nanos: i64) -> DateTime<Self> { + let (mut secs, mut nanos) = (nanos / 1_000_000_000, nanos % 1_000_000_000); + if nanos < 0 { + secs -= 1; + nanos += 1_000_000_000; + } + self.timestamp_opt(secs, nanos as u32).unwrap() + } + + /// Parses a string with the specified format string and + /// returns a `DateTime` with the current offset. + /// See the [`format::strftime` module](../format/strftime/index.html) + /// on the supported escape sequences. + /// + /// If the format does not include offsets, the current offset is assumed; + /// otherwise the input should have a matching UTC offset. + /// + /// See also `DateTime::parse_from_str` which gives a local `DateTime` + /// with parsed `FixedOffset`. + 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) -> LocalResult<Self::Offset>; + + /// Creates the offset(s) for given local `NaiveDateTime` if possible. + fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<Self::Offset>; + + /// Converts the local `NaiveDate` to the timezone-aware `Date` if possible. + fn from_local_date(&self, local: &NaiveDate) -> LocalResult<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. + fn from_local_datetime(&self, local: &NaiveDateTime) -> LocalResult<DateTime<Self>> { + self.offset_from_local_datetime(local) + .map(|offset| DateTime::from_utc(*local - offset.fix(), offset)) + } + + /// 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). + 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). + fn from_utc_datetime(&self, utc: &NaiveDateTime) -> DateTime<Self> { + DateTime::from_utc(*utc, self.offset_from_utc_datetime(utc)) + } +} + +mod fixed; +#[cfg(feature = "clock")] +mod local; +mod utc; + +pub use self::fixed::FixedOffset; +#[cfg(feature = "clock")] +pub use self::local::Local; +pub use self::utc::Utc; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_negative_millis() { + let dt = Utc.timestamp_millis(-1000); + assert_eq!(dt.to_string(), "1969-12-31 23:59:59 UTC"); + let dt = Utc.timestamp_millis(-7000); + assert_eq!(dt.to_string(), "1969-12-31 23:59:53 UTC"); + let dt = Utc.timestamp_millis(-7001); + assert_eq!(dt.to_string(), "1969-12-31 23:59:52.999 UTC"); + let dt = Utc.timestamp_millis(-7003); + assert_eq!(dt.to_string(), "1969-12-31 23:59:52.997 UTC"); + let dt = Utc.timestamp_millis(-999); + assert_eq!(dt.to_string(), "1969-12-31 23:59:59.001 UTC"); + let dt = Utc.timestamp_millis(-1); + assert_eq!(dt.to_string(), "1969-12-31 23:59:59.999 UTC"); + let dt = Utc.timestamp_millis(-60000); + assert_eq!(dt.to_string(), "1969-12-31 23:59:00 UTC"); + let dt = Utc.timestamp_millis(-3600000); + 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) { + LocalResult::Single(dt) => { + assert_eq!(dt.to_string(), *expected); + } + e => panic!("Got {:?} instead of an okay answer", e), + } + } + } + + #[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_value()); + Utc.timestamp_nanos(i64::default()); + Utc.timestamp_nanos(i64::min_value()); + } +} diff --git a/vendor/chrono/src/offset/utc.rs b/vendor/chrono/src/offset/utc.rs new file mode 100644 index 000000000..aec6667b0 --- /dev/null +++ b/vendor/chrono/src/offset/utc.rs @@ -0,0 +1,100 @@ +// This is a part of Chrono. +// See README.md and LICENSE.txt for details. + +//! The UTC (Coordinated Universal Time) time zone. + +use core::fmt; + +use super::{FixedOffset, LocalResult, Offset, TimeZone}; +use naive::{NaiveDate, NaiveDateTime}; +#[cfg(all( + feature = "clock", + not(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind")) +))] +use std::time::{SystemTime, UNIX_EPOCH}; +#[cfg(feature = "clock")] +use {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, NaiveDateTime, Utc}; +/// +/// let dt = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(61, 0), Utc); +/// +/// assert_eq!(Utc.timestamp(61, 0), dt); +/// assert_eq!(Utc.ymd(1970, 1, 1).and_hms(0, 1, 1), dt); +/// ~~~~ +#[derive(Copy, Clone, PartialEq, Eq)] +pub struct Utc; + +#[cfg(feature = "clock")] +impl Utc { + /// Returns a `Date` which corresponds to the current date. + pub fn today() -> Date<Utc> { + Utc::now().date() + } + + /// Returns a `DateTime` which corresponds to the current date. + #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind")))] + pub fn now() -> DateTime<Utc> { + let now = + SystemTime::now().duration_since(UNIX_EPOCH).expect("system time before Unix epoch"); + let naive = NaiveDateTime::from_timestamp(now.as_secs() as i64, now.subsec_nanos() as u32); + DateTime::from_utc(naive, Utc) + } + + /// Returns a `DateTime` which corresponds to the current date. + #[cfg(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind"))] + 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) -> LocalResult<Utc> { + LocalResult::Single(Utc) + } + fn offset_from_local_datetime(&self, _local: &NaiveDateTime) -> LocalResult<Utc> { + LocalResult::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(0) + } +} + +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") + } +} |