spinoso_time/time/tzrs/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
use core::cmp::Ordering;
use core::hash::{Hash, Hasher};

use tz::datetime::DateTime;

mod build;
mod convert;
mod error;
mod math;
mod offset;
mod parts;
mod strftime;
mod timezone;
mod to_a;

pub use error::{IntOverflowError, TimeError, TzOutOfRangeError, TzStringError};
pub use offset::{Offset, MAX_OFFSET_SECONDS, MIN_OFFSET_SECONDS};
pub use to_a::ToA;

/// Alias for [`std::result::Result`] with the unified [`TimeError`].
pub type Result<T> = std::result::Result<T, TimeError>;

use crate::NANOS_IN_SECOND;

/// Implementation of Ruby [`Time`], a timezone-aware datetime, based on
/// [`tz-rs`] and [`tzdb`].
///
/// `Time` is represented as:
///
/// - a 64-bit signed integer of seconds since January 1, 1970 UTC (a Unix
///   timestamp).
/// - an unsigned 32-bit integer of nanoseconds since the timestamp.
/// - An offset from UTC. See [`Offset`] for the types of supported offsets.
///
/// This data structure allows representing roughly 584 billion years. Unlike
/// MRI, there is no promotion to `Bignum` or `Rational`. The maximum
/// granularity of a `Time` object is nanoseconds.
///
/// # Examples
///
/// ```
/// # use spinoso_time::tzrs::{Time, TimeError};
/// # fn example() -> Result<(), TimeError> {
/// // Create a Time to the current system clock with local offset
/// let time = Time::now()?;
/// assert!(!time.is_utc());
/// println!("{}", time.is_sunday());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
///
/// ```
/// # use spinoso_time::tzrs::{Time, TimeError};
/// # fn example() -> Result<(), TimeError> {
/// let time = Time::now()?;
/// let one_hour_ago: Time = time.checked_sub_u64(60 * 60)?;
/// assert_eq!(time.to_int() - 3600, one_hour_ago.to_int());
/// assert_eq!(time.nanoseconds(), one_hour_ago.nanoseconds());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
///
/// [`tz-rs`]: tz
/// [`Time`]: https://ruby-doc.org/core-3.1.2/Time.html
#[must_use]
#[derive(Debug, Clone, Copy)]
pub struct Time {
    /// A wrapper around [`tz::datetime::DateTime`] to provide date and time
    /// formatting.
    inner: DateTime,
    /// The offset to used for the provided _time_.
    offset: Offset,
}

impl Hash for Time {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Hash is only based on the nanos since epoch:
        //
        // ```console
        // [3.1.2] > t = Time.now
        // => 2022-06-26 14:41:03.192545 -0700
        // [3.1.2] > t.zone
        // => "PDT"
        // [3.1.2] > t.hash
        // => 3894887943343456722
        // [3.1.2] > u = t.utc
        // => 2022-06-26 21:41:03.192545 UTC
        // [3.1.2] > u.zone
        // => "UTC"
        // [3.1.2] > u.hash
        // => 3894887943343456722
        // ```
        state.write_i128(self.inner.total_nanoseconds());
    }
}

impl PartialEq for Time {
    fn eq(&self, other: &Time) -> bool {
        self.inner.total_nanoseconds() == other.inner.total_nanoseconds()
    }
}

impl Eq for Time {}

impl PartialOrd for Time {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Time {
    fn cmp(&self, other: &Self) -> Ordering {
        self.inner.total_nanoseconds().cmp(&other.inner.total_nanoseconds())
    }
}

// constructors
impl Time {
    /// Returns a new Time from the given values in the provided `offset`.
    ///
    /// Can be used to implement the Ruby method [`Time#new`] (using a
    /// [`Timezone`] Object).
    ///
    /// **Note**: During DST transitions, a specific time can be ambiguous. This
    /// method will always pick the latest date.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_time::tzrs::{Time, Offset, TimeError};
    /// # fn example() -> Result<(), TimeError> {
    /// let offset = Offset::try_from("+1200")?;
    /// let t = Time::new(2022, 9, 25, 1, 30, 0, 0, offset);
    /// # Ok(())
    /// # }
    /// # example().unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Can produce a [`TimeError`], generally when provided values are out of range.
    ///
    /// [`Time#new`]: https://ruby-doc.org/core-3.1.2/Time.html#method-c-new
    /// [`Timezone`]: https://ruby-doc.org/core-3.1.2/Time.html#class-Time-label-Timezone+argument
    #[inline]
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        year: i32,
        month: u8,
        day: u8,
        hour: u8,
        minute: u8,
        second: u8,
        nanoseconds: u32,
        offset: Offset,
    ) -> Result<Self> {
        let tz = offset.time_zone_ref();
        let found_date_times = DateTime::find(year, month, day, hour, minute, second, nanoseconds, tz)?;

        // According to the `tz-rs` author, `FoundDateTimeList::latest` and
        // `FoundDateTimeList::first` can return `None` if the provided time
        // zone has no extra rule and the date time would be located after the
        // last transition.
        //
        // This situation can happen when using a TZif v1 file, which cannot
        // contain a footer with an extra rule definition. If you are using the
        // last version of the Time Zone Database, all TZif v1 files have been
        // replaced by TZif v2 or v3 files, so this error should be uncommon.
        //
        // As of `tzdb` 0.4.0, the Time Zone Database is version 2022a which has
        // this property, which means an `expect` below can never panic, however
        // upstream has provided a test case which means we have a test that
        // simulates this failure condition and requires us to handle it.
        //
        // See: https://github.com/x-hgg-x/tz-rs/issues/34#issuecomment-1206140198
        let dt = found_date_times.latest().ok_or(TimeError::Unknown)?;
        Ok(Self { inner: dt, offset })
    }

    /// Returns a Time with the current time in the System Timezone.
    ///
    /// Can be used to implement the Ruby method [`Time#now`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_time::tzrs::{Time, Offset, TimeError};
    /// # fn example() -> Result<(), TimeError> {
    /// let now = Time::now()?;
    /// # Ok(())
    /// # }
    /// # example().unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Can produce a [`TimeError`], however these should never been seen in regular usage.
    ///
    /// [`Time#now`]: https://ruby-doc.org/core-3.1.2/Time.html#method-c-now
    #[inline]
    pub fn now() -> Result<Self> {
        let offset = Offset::local();
        let time_zone_ref = offset.time_zone_ref();
        let now = DateTime::now(time_zone_ref)?;
        Ok(Self { inner: now, offset })
    }

    /// Returns a Time in the given timezone with the number of `seconds` and
    /// `nanoseconds` since the Epoch in the specified timezone.
    ///
    /// Can be used to implement the Ruby method [`Time#at`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_time::tzrs::{Time, Offset, TimeError};
    /// # fn example() -> Result<(), TimeError> {
    /// let offset = Offset::utc();
    /// let t = Time::with_timespec_and_offset(0, 0, offset)?;
    /// assert_eq!(t.to_int(), 0);
    /// # Ok(())
    /// # }
    /// # example().unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Can produce a [`TimeError`], however these should not be seen during regular usage.
    ///
    /// [`Time#at`]: https://ruby-doc.org/core-3.1.2/Time.html#method-c-at
    #[inline]
    pub fn with_timespec_and_offset(seconds: i64, nanoseconds: u32, offset: Offset) -> Result<Self> {
        let time_zone_ref = offset.time_zone_ref();
        let dt = DateTime::from_timespec(seconds, nanoseconds, time_zone_ref)?;
        Ok(Self { inner: dt, offset })
    }
}

impl TryFrom<ToA> for Time {
    type Error = TimeError;

    /// Create a new Time object base on a `ToA`
    ///
    /// **Note**: This converting from a Time object to a `ToA` and back again
    /// is lossy since `ToA` does not store nanoseconds.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_time::tzrs::{Time, Offset, TimeError};
    /// # fn example() -> Result<(), TimeError> {
    /// let now = Time::local(2022, 7, 8, 12, 34, 56, 1000)?;
    /// let to_a = now.to_array();
    /// let from_to_a = Time::try_from(to_a)?;
    /// assert_eq!(now.second(), from_to_a.second());
    /// assert_ne!(now.nanoseconds(), from_to_a.nanoseconds());
    /// # Ok(())
    /// # }
    /// # example().unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Can produce a [`TimeError`], generally when provided values are out of range.
    #[inline]
    fn try_from(to_a: ToA) -> Result<Self> {
        let offset = Offset::try_from(to_a.zone).unwrap_or_else(|_| Offset::utc());

        Self::new(
            to_a.year, to_a.month, to_a.day, to_a.hour, to_a.min, to_a.sec, 0, offset,
        )
    }
}

// Core
impl Time {
    /// Returns the number of seconds as a signed integer since the Epoch.
    ///
    /// This function can be used to implement the Ruby methods [`Time#to_i`]
    /// and [`Time#tv_sec`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_time::tzrs::{Time, Offset, TimeError};
    /// # fn example() -> Result<(), TimeError> {
    /// let t = Time::utc(1970, 1, 1, 0, 1, 0, 0)?;
    /// assert_eq!(t.to_int(), 60);
    /// # Ok(())
    /// # }
    /// # example().unwrap();
    /// ```
    ///
    /// [`Time#to_i`]: https://ruby-doc.org/core-3.1.2/Time.html#method-i-to_i
    /// [`Time#tv_sec`]: https://ruby-doc.org/core-3.1.2/Time.html#method-i-tv_sec
    #[inline]
    #[must_use]
    pub fn to_int(&self) -> i64 {
        self.inner.unix_time()
    }

    /// Returns the number of seconds since the Epoch with fractional nanos
    /// included at IEEE 754-2008 accuracy.
    ///
    /// This function can be used to implement the Ruby method [`Time#to_f`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_time::tzrs::{Time, Offset, TimeError};
    /// # fn example() -> Result<(), TimeError> {
    /// let now = Time::utc(1970, 1, 1, 0, 1, 0, 1000)?;
    /// assert_eq!(now.to_float(), 60.000001);
    /// # Ok(())
    /// # }
    /// # example().unwrap();
    /// ```
    ///
    /// [`Time#to_f`]: https://ruby-doc.org/core-3.1.2/Time.html#method-i-to_f
    #[inline]
    #[must_use]
    pub fn to_float(&self) -> f64 {
        // A `f64` mantissa is only 52 bits wide, so putting 64 bits in there
        // will result in a rounding issues, however this is expected in the
        // Ruby spec.
        #[allow(clippy::cast_precision_loss)]
        let sec = self.to_int() as f64;
        let nanos_fractional = f64::from(self.inner.nanoseconds()) / f64::from(NANOS_IN_SECOND);
        sec + nanos_fractional
    }

    /// Returns the numerator and denominator for the number of nanoseconds of
    /// the Time struct unsimplified.
    ///
    /// This can be used directly to implement [`Time#subsec`].
    ///
    /// This function can be used in combination with [`to_int`] to implement
    /// [`Time#to_r`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_time::tzrs::{Time, Offset, TimeError};
    /// # fn example() -> Result<(), TimeError> {
    /// let t = Time::utc(1970, 1, 1, 0, 0, 1, 1000)?;
    /// assert_eq!(t.subsec_fractional(), (1000, 1000000000));
    /// # Ok(())
    /// # }
    /// # example().unwrap();
    /// ```
    ///
    /// [`Time#subsec`]: https://ruby-doc.org/core-3.1.2/Time.html#method-i-subsec
    /// [`to_int`]: struct.Time.html#method.to_int
    /// [`Time#to_r`]: https://ruby-doc.org/core-3.1.2/Time.html#method-i-to_r
    #[inline]
    #[must_use]
    pub fn subsec_fractional(&self) -> (u32, u32) {
        (self.inner.nanoseconds(), NANOS_IN_SECOND)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn time_with_fixed_offset(offset: i32) -> Time {
        let offset = Offset::fixed(offset).unwrap();
        Time::with_timespec_and_offset(0, 0, offset).unwrap()
    }

    #[test]
    fn time_zone_fixed_offset() {
        assert_eq!("-0202", time_with_fixed_offset(-7320).time_zone());
        assert_eq!("+0000", time_with_fixed_offset(0).time_zone());
        assert_eq!("+0000", time_with_fixed_offset(59).time_zone());
    }
}