Skip to main content

jiff_core/
timestamp.rs

1use crate::{
2    bounds::{self as b, RangeError},
3    civil::DateTime,
4    constants as c,
5    macros::{rbail, rtry, unwrapr},
6    tz::Offset,
7};
8
9/// An instant in time represented as the number of nanoseconds since the Unix
10/// epoch.
11///
12/// A timestamp is always in the Unix timescale with a UTC offset of zero.
13#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Timestamp {
}
#[automatically_derived]impl ::core::clone::Clone for Timestamp {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<i64>;
        let _: ::core::clone::AssertParamIsClone<i32>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Timestamp { }Copy, #[automatically_derived]impl ::core::cmp::Eq for Timestamp {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<i64>;
        let _: ::core::cmp::AssertParamIsEq<i32>;
    }
}Eq, #[automatically_derived]impl ::core::hash::Hash for Timestamp {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.second, state);
        ::core::hash::Hash::hash(&self.nanosecond, state)
    }
}Hash, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Timestamp
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Timestamp {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.second == other.second && self.nanosecond == other.nanosecond
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::PartialOrd for Timestamp {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]impl ::core::cmp::Ord for Timestamp {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.second, &other.second) {
            ::core::cmp::Ordering::Equal =>
                ::core::cmp::Ord::cmp(&self.nanosecond, &other.nanosecond),
            cmp => cmp,
        }
    }
}Ord)]
14#[cfg_attr(feature = "defmt", derive(defmt::Format))]
15pub struct Timestamp {
16    second: i64,
17    nanosecond: i32,
18}
19
20impl Timestamp {
21    /// The minimum allow Unix timestamp.
22    pub const MIN: Timestamp = Timestamp {
23        second: b::UnixEpochSeconds::MIN,
24        nanosecond: b::SubsecNanosecond::MIN,
25    };
26
27    /// The maximum allow Unix timestamp.
28    pub const MAX: Timestamp = Timestamp {
29        second: b::UnixEpochSeconds::MAX,
30        nanosecond: b::SubsecNanosecond::MAX,
31    };
32
33    /// The Unix epoch represented as a timestamp.
34    pub const UNIX_EPOCH: Timestamp = Timestamp { second: 0, nanosecond: 0 };
35
36    /// Create a new timestamp from the given number of seconds and its
37    /// sub-second component.
38    ///
39    /// This returns an error if `nanos` is not in the range specified by
40    /// [`SignedSubsecNanosecond`](b::SignedSubsecNanosecond). An error
41    /// is also returned when `secs` is not in the range specified by
42    /// [`UnixEpochSeconds`](b::UnixEpochSeconds).
43    #[inline]
44    pub const fn new(secs: i64, nanos: i32) -> Result<Timestamp, RangeError> {
45        let mut secs = match b::UnixEpochSeconds::checkc(secs) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::UnixEpochSeconds::checkc(secs));
46        let mut nanos = match b::SignedSubsecNanosecond::checkc(nanos as i64) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::SignedSubsecNanosecond::checkc(nanos as i64));
47        if secs == b::UnixEpochSeconds::MIN && nanos < 0 {
48            return Err(b::UnixEpochSeconds::error().into_range_error());rbail!(b::UnixEpochSeconds::error());
49        }
50        // At this point, we're done if either unit is zero or if they have the
51        // same sign.
52        if nanos == 0 || secs == 0 || secs.signum() == (nanos.signum() as i64)
53        {
54            return Ok(Timestamp::new_unchecked(secs, nanos));
55        }
56        // Otherwise, the only work we have to do is to balance negative nanos
57        // into positive seconds, or positive nanos into negative seconds.
58        if secs < 0 {
59            if true {
    if !(nanos > 0) {
        ::core::panicking::panic("assertion failed: nanos > 0")
    };
};debug_assert!(nanos > 0);
60            // Never wraps because adding +1 to a negative i64 never overflows.
61            //
62            // MSRV(1.79): Consider using `unchecked_add` here.
63            secs += 1;
64            // Never wraps because subtracting +1_000_000_000 from a positive
65            // i32 never overflows.
66            //
67            // MSRV(1.79): Consider using `unchecked_sub` here.
68            nanos -= c::NANOS_PER_SEC_32;
69        } else {
70            if true {
    if !(secs > 0) { ::core::panicking::panic("assertion failed: secs > 0") };
};debug_assert!(secs > 0);
71            if true {
    if !(nanos < 0) {
        ::core::panicking::panic("assertion failed: nanos < 0")
    };
};debug_assert!(nanos < 0);
72            // Never wraps because subtracting +1 from a positive i64 never
73            // overflows.
74            //
75            // MSRV(1.79): Consider using `unchecked_add` here.
76            secs -= 1;
77            // Never wraps because adding +1_000_000_000 to a negative i32
78            // never overflows.
79            //
80            // MSRV(1.79): Consider using `unchecked_add` here.
81            nanos += c::NANOS_PER_SEC_32;
82        }
83        Ok(Timestamp::new_unchecked(secs, nanos))
84    }
85
86    /// Creates a new `Timestamp` value in a `const` context.
87    ///
88    /// This is identical to [`Timestamp::new`], except that it panics when
89    /// `Timestamp::new` would return an error. This can be more convenient in
90    /// a `const` context where unwrapping a `Result` is not ergonomic.
91    #[inline]
92    pub const fn constant(second: i64, nanosecond: i32) -> Timestamp {
93        match Timestamp::new(second, nanosecond) {
    Ok(val) => val,
    Err(_) => {
        ::core::panicking::panic_fmt(format_args!("invalid timestamp"));
    }
}unwrapr!(Timestamp::new(second, nanosecond), "invalid timestamp")
94    }
95
96    /// Creates a new `Timestamp` without bounds checks.
97    ///
98    /// Note that this should not be made public *and* safe.
99    #[inline]
100    pub(crate) const fn new_unchecked(secs: i64, nanos: i32) -> Timestamp {
101        if true {
    if !b::UnixEpochSeconds::checkc(secs).is_ok() {
        ::core::panicking::panic("assertion failed: b::UnixEpochSeconds::checkc(secs).is_ok()")
    };
};debug_assert!(b::UnixEpochSeconds::checkc(secs).is_ok());
102        if true {
    if !b::SignedSubsecNanosecond::checkc(nanos as i64).is_ok() {
        ::core::panicking::panic("assertion failed: b::SignedSubsecNanosecond::checkc(nanos as i64).is_ok()")
    };
};debug_assert!(b::SignedSubsecNanosecond::checkc(nanos as i64).is_ok());
103        if true {
    if !(secs != b::UnixEpochSeconds::MIN || nanos >= 0) {
        ::core::panicking::panic("assertion failed: secs != b::UnixEpochSeconds::MIN || nanos >= 0")
    };
};debug_assert!(secs != b::UnixEpochSeconds::MIN || nanos >= 0);
104        if true {
    if !(nanos == 0 || secs == 0 || secs.signum() == (nanos.signum() as i64))
        {
        ::core::panicking::panic("assertion failed: nanos == 0 || secs == 0 || secs.signum() == (nanos.signum() as i64)")
    };
};debug_assert!(
105            nanos == 0
106                || secs == 0
107                || secs.signum() == (nanos.signum() as i64)
108        );
109        Timestamp { second: secs, nanosecond: nanos }
110    }
111
112    /// Constructs a timestamp from seconds since the Unix epoch.
113    ///
114    /// This is preferred to [`Timestamp::new`] when it is known that the
115    /// sub-second component is always `0`. In particular, this generates
116    /// less code and is likely to be faster.
117    ///
118    /// An error is returned when `second` is not in the range specified by
119    /// [`UnixEpochSeconds`](b::UnixEpochSeconds).
120    #[inline]
121    pub const fn from_second(second: i64) -> Result<Timestamp, RangeError> {
122        let second = match b::UnixEpochSeconds::checkc(second) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::UnixEpochSeconds::checkc(second));
123        Ok(Timestamp::new_unchecked(second, 0))
124    }
125
126    /// Constructs a timestamp from milliseconds since the Unix epoch.
127    ///
128    /// An error is returned when `millisecond` is not in the range specified by
129    /// [`UnixEpochMilliseconds`](b::UnixEpochMilliseconds).
130    #[inline]
131    pub const fn from_millisecond(
132        millisecond: i64,
133    ) -> Result<Timestamp, RangeError> {
134        let millisecond = match b::UnixEpochMilliseconds::checkc(millisecond) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::UnixEpochMilliseconds::checkc(millisecond));
135        // OK because MILLIS_PER_SEC!={-1,0}.
136        let secs = millisecond / c::MILLIS_PER_SEC;
137        // OK because MILLIS_PER_SEC!={-1,0} and because
138        // millis % MILLIS_PER_SEC can be at most 999, and 999 * 1_000_000
139        // never overflows i32.
140        let nanos =
141            (millisecond % c::MILLIS_PER_SEC) as i32 * c::NANOS_PER_MILLI_32;
142        // OK because we've already verified that `millisecond` is in range.
143        Ok(Timestamp::new_unchecked(secs, nanos))
144    }
145
146    /// Constructs a timestamp from microseconds since the Unix epoch.
147    ///
148    /// An error is returned when `microsecond` is not in the range specified
149    /// by [`UnixEpochMicroseconds`](b::UnixEpochMicroseconds).
150    #[inline]
151    pub const fn from_microsecond(
152        microsecond: i64,
153    ) -> Result<Timestamp, RangeError> {
154        let microsecond = match b::UnixEpochMicroseconds::checkc(microsecond) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::UnixEpochMicroseconds::checkc(microsecond));
155        // OK because MILLIS_PER_SEC!={-1,0}.
156        let secs = microsecond / c::MICROS_PER_SEC;
157        // OK because MILLIS_PER_SEC!={-1,0} and because
158        // millis % MILLIS_PER_SEC can be at most 999, and 999 * 1_000_000
159        // never overflows i32.
160        let nanos =
161            (microsecond % c::MICROS_PER_SEC) as i32 * c::NANOS_PER_MICRO_32;
162        // OK because we've already verified that `millisecond` is in range.
163        Ok(Timestamp::new_unchecked(secs, nanos))
164    }
165
166    /// Constructs a timestamp from nanoseconds since the Unix epoch.
167    ///
168    /// An error is returned when `nanosecond` refers to a timestamp outside
169    /// of the range [`Timestamp::MIN`] to [`Timestamp::MAX`].
170    #[inline]
171    pub const fn from_nanosecond(
172        nanosecond: i128,
173    ) -> Result<Timestamp, RangeError> {
174        const NANOS_PER_SEC: i128 = c::NANOS_PER_SEC as i128;
175        // OK because NANOS_PER_SEC!={-1,0}.
176        let secs = nanosecond / NANOS_PER_SEC;
177        // RUST: Use `i64::try_from` when available in `const`.
178        if !(i64::MIN as i128 <= secs && secs <= i64::MAX as i128) {
179            return Err(b::SpecialBoundsError::UnixEpochNanoseconds.into_range_error());rbail!(b::SpecialBoundsError::UnixEpochNanoseconds);
180        }
181        let secs64 = match b::UnixEpochSeconds::checkc(secs as i64) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::UnixEpochSeconds::checkc(secs as i64));
182        // OK because NANOS_PER_SEC!={-1,0}.
183        let nanosecond = (nanosecond % NANOS_PER_SEC) as i32;
184        if secs64 == b::UnixEpochSeconds::MIN && nanosecond < 0 {
185            return Err(b::UnixEpochSeconds::error().into_range_error());rbail!(b::UnixEpochSeconds::error());
186        }
187        Ok(Timestamp::new_unchecked(secs64, nanosecond))
188    }
189
190    /// Returns this timestamp as a number of seconds since the Unix epoch.
191    ///
192    /// This only returns the number of whole seconds. That is, if there are
193    /// any fractional seconds in this timestamp, then they are truncated.
194    #[inline]
195    pub const fn as_second(self) -> i64 {
196        self.second
197    }
198
199    /// Returns this timestamp as a number of milliseconds since the Unix
200    /// epoch.
201    ///
202    /// This only returns the number of whole milliseconds. That is, if there
203    /// are any fractional milliseconds in this timestamp, then they are
204    /// truncated.
205    #[inline]
206    pub const fn as_millisecond(self) -> i64 {
207        // OK because the range of `Timestamp` guarantees that its
208        // representation as milliseconds fits into an i64.
209        let millis = self.as_second() * c::MILLIS_PER_SEC;
210        // OK because subsec_millis maxes out at 999, and adding that to
211        // b::UnixSeconds::MAX*1_000 will never overflow an i64.
212        millis + (self.subsec_millisecond() as i64)
213    }
214
215    /// Returns this timestamp as a number of microseconds since the Unix
216    /// epoch.
217    ///
218    /// This only returns the number of whole microseconds. That is, if there
219    /// are any fractional microseconds in this timestamp, then they are
220    /// truncated.
221    #[inline]
222    pub const fn as_microsecond(self) -> i64 {
223        // OK because the range of `Timestamp` guarantees that its
224        // representation as microseconds fits into an i64.
225        let micros = self.as_second() * c::MICROS_PER_SEC;
226        // OK because subsec_micros maxes out at 999_999, and adding that to
227        // b::UnixSeconds::MAX*1_000_000 will never overflow an i64.
228        micros + (self.subsec_microsecond() as i64)
229    }
230
231    /// Returns this timestamp as a number of nanoseconds since the Unix
232    /// epoch.
233    #[inline]
234    pub const fn as_nanosecond(self) -> i128 {
235        // OK because 1_000_000_000 times any i64 will never overflow i128.
236        let nanos = (self.second as i128) * (c::NANOS_PER_SEC as i128);
237        // OK because nanosecond maxes out at 999_999_999, and adding that to
238        // i64::MAX*1_000_000_000 will never overflow a i128.
239        nanos + (self.nanosecond as i128)
240    }
241
242    /// Returns the fractional second component of this timestamp in units of
243    /// milliseconds.
244    ///
245    /// The value returned is negative when the timestamp is negative. It is
246    /// guaranteed that the range of the value returned is in the inclusive
247    /// range `-999..=999`.
248    #[inline]
249    pub const fn subsec_millisecond(&self) -> i32 {
250        // OK because NANOS_PER_MILLI!={-1,0}.
251        self.nanosecond / c::NANOS_PER_MILLI_32
252    }
253
254    /// Returns the fractional second component of this timestamp in units of
255    /// microseconds.
256    ///
257    /// The value returned is negative when the timestamp is negative. It is
258    /// guaranteed that the range of the value returned is in the inclusive
259    /// range `-999_999..=999_999`.
260    #[inline]
261    pub const fn subsec_microsecond(&self) -> i32 {
262        // OK because NANOS_PER_MICRO!={-1,0}.
263        self.nanosecond / c::NANOS_PER_MICRO_32
264    }
265
266    /// Returns the fractional second component of this timestamp in units of
267    /// nanoseconds.
268    ///
269    /// The value returned is negative when the timestamp is negative. It is
270    /// guaranteed that the range of the value returned is in the inclusive
271    /// range `-999,999,999..=999,999,999`.
272    #[inline]
273    pub const fn subsec_nanosecond(&self) -> i32 {
274        self.nanosecond
275    }
276
277    /// Returns a number that represents the sign of this timestamp.
278    ///
279    /// * When [`Timestamp::is_zero`] is true, this returns `0`.
280    /// * When [`Timestamp::is_positive`] is true, this returns `1`.
281    /// * When [`Timestamp::is_negative`] is true, this returns `-1`.
282    ///
283    /// The above cases are mutually exclusive.
284    ///
285    /// # Example
286    ///
287    /// ```
288    /// use jiff_core::Timestamp;
289    ///
290    /// assert_eq!(0, Timestamp::UNIX_EPOCH.signum());
291    ///
292    /// let ts = Timestamp::new(5, -999_999_999).unwrap();
293    /// assert_eq!(ts.signum(), 1);
294    /// // The mixed signs were normalized away!
295    /// assert_eq!(ts.as_second(), 4);
296    /// assert_eq!(ts.subsec_nanosecond(), 1);
297    ///
298    /// // The same applies for negative timestamps.
299    /// let ts = Timestamp::new(-5, 999_999_999).unwrap();
300    /// assert_eq!(ts.signum(), -1);
301    /// assert_eq!(ts.as_second(), -4);
302    /// assert_eq!(ts.subsec_nanosecond(), -1);
303    /// ```
304    #[inline]
305    pub const fn signum(self) -> i8 {
306        if self.is_zero() {
307            0
308        } else if self.is_positive() {
309            1
310        } else {
311            if true {
    if !self.is_negative() {
        ::core::panicking::panic("assertion failed: self.is_negative()")
    };
};debug_assert!(self.is_negative());
312            -1
313        }
314    }
315
316    /// Returns true if and only if this timestamp corresponds to the instant
317    /// in time known as the Unix epoch.
318    ///
319    /// # Example
320    ///
321    /// ```
322    /// use jiff_core::Timestamp;
323    ///
324    /// assert!(Timestamp::UNIX_EPOCH.is_zero());
325    /// ```
326    #[inline]
327    pub const fn is_zero(self) -> bool {
328        self.second == 0 && self.nanosecond == 0
329    }
330
331    /// Returns true when this timestamp is positive. That is, after the Unix
332    /// epoch.
333    ///
334    /// # Example
335    ///
336    /// ```
337    /// use jiff_core::Timestamp;
338    ///
339    /// let ts = Timestamp::new(0, 1).unwrap();
340    /// assert!(ts.is_positive());
341    /// ```
342    #[inline]
343    pub const fn is_positive(&self) -> bool {
344        self.second.is_positive() || self.nanosecond.is_positive()
345    }
346
347    /// Returns true when this timestamp is negative. That is, before the Unix
348    /// epoch.
349    ///
350    /// # Example
351    ///
352    /// ```
353    /// use jiff_core::Timestamp;
354    ///
355    /// let ts = Timestamp::new(0, -1).unwrap();
356    /// assert!(ts.is_negative());
357    /// ```
358    #[inline]
359    pub const fn is_negative(&self) -> bool {
360        self.second.is_negative() || self.nanosecond.is_negative()
361    }
362
363    /// Converts a Unix timestamp with an offset to a Gregorian datetime.
364    ///
365    /// The offset should correspond to the number of seconds required to
366    /// add to this timestamp to get the local time.
367    #[inline]
368    pub const fn to_datetime(&self, offset: Offset) -> DateTime {
369        offset.to_datetime(*self)
370    }
371
372    /// Add the given number of seconds and nanoseconds to this timestamp.
373    ///
374    /// If this would result in a timestamp outside of its boundaries, then
375    /// this returns an error.
376    ///
377    /// # Examples
378    ///
379    /// ```
380    /// use jiff_core::Timestamp;
381    ///
382    /// let mkts = |sec, nano| Timestamp::new(sec, nano).unwrap();
383    /// let ts = mkts(123, 0);
384    ///
385    /// assert_eq!(ts.checked_add(1, 0), Ok(mkts(124, 0)));
386    /// assert_eq!(ts.checked_add(1, 1), Ok(mkts(124, 1)));
387    /// assert_eq!(ts.checked_add(1, -1), Ok(mkts(123, 999_999_999)));
388    /// assert_eq!(ts.checked_add(0, 1), Ok(mkts(123, 1)));
389    /// assert_eq!(ts.checked_add(0, -1), Ok(mkts(122, 999_999_999)));
390    /// assert_eq!(ts.checked_add(-1, 0), Ok(mkts(122, 0)));
391    /// assert_eq!(ts.checked_add(-1, 1), Ok(mkts(122, 1)));
392    /// assert_eq!(ts.checked_add(-1, -1), Ok(mkts(121, 999_999_999)));
393    ///
394    /// assert_eq!(ts.checked_add(0, i32::MIN), Ok(mkts(121, -147_483_648)));
395    /// assert_eq!(ts.checked_add(1, i32::MIN), Ok(mkts(122, -147_483_648)));
396    /// assert_eq!(ts.checked_add(-1, i32::MIN), Ok(mkts(120, -147_483_648)));
397    /// assert_eq!(ts.checked_add(0, i32::MAX), Ok(mkts(125, 147_483_647)));
398    /// assert_eq!(ts.checked_add(1, i32::MAX), Ok(mkts(126, 147_483_647)));
399    /// assert_eq!(ts.checked_add(-1, i32::MAX), Ok(mkts(124, 147_483_647)));
400    ///
401    /// assert!(ts.checked_add(i64::MAX, 0).is_err());
402    /// assert!(ts.checked_add(i64::MIN, 0).is_err());
403    ///
404    /// let ts = Timestamp::UNIX_EPOCH;
405    /// let max = Timestamp::MAX.as_second();
406    /// assert!(ts.checked_add(max, 0).is_ok());
407    /// assert!(ts.checked_add(max + 1, 0).is_err());
408    /// assert!(ts.checked_add(max, 999_999_999).is_ok());
409    /// assert!(ts.checked_add(max, 1_000_000_000).is_err());
410    /// ```
411    #[inline]
412    pub const fn checked_add(
413        self,
414        mut seconds: i64,
415        mut nanos: i32,
416    ) -> Result<Timestamp, RangeError> {
417        // When |nanos| exceeds 1 second, we balance the excess up to seconds.
418        if !(-c::NANOS_PER_SEC_32 < nanos && nanos < c::NANOS_PER_SEC_32) {
419            // Never wraps or panics because NANOS_PER_SEC!={0,-1}.
420            let addsecs = nanos / c::NANOS_PER_SEC_32;
421            seconds = match seconds.checked_add(addsecs as i64) {
422                Some(secs) => secs,
423                None => return Err(b::UnixEpochSeconds::error().into_range_error())rbail!(b::UnixEpochSeconds::error()),
424            };
425            // Never wraps or panics because NANOS_PER_SEC!={0,-1}.
426            nanos = nanos % c::NANOS_PER_SEC_32;
427        }
428
429        self.checked_add_sensible(seconds, nanos)
430    }
431
432    /// Subtracts the given number of seconds and nanoseconds from this
433    /// timestamp.
434    ///
435    /// # Examples
436    ///
437    /// ```
438    /// use jiff_core::Timestamp;
439    ///
440    /// let mkts = |sec, nano| Timestamp::new(sec, nano).unwrap();
441    /// let ts = mkts(123, 0);
442    ///
443    /// assert_eq!(ts.checked_sub(1, 0), Ok(mkts(122, 0)));
444    /// assert_eq!(ts.checked_sub(1, 1), Ok(mkts(121, 999_999_999)));
445    /// assert_eq!(ts.checked_sub(1, -1), Ok(mkts(122, 1)));
446    /// assert_eq!(ts.checked_sub(0, 1), Ok(mkts(122, 999_999_999)));
447    /// assert_eq!(ts.checked_sub(0, -1), Ok(mkts(123, 1)));
448    /// assert_eq!(ts.checked_sub(-1, 0), Ok(mkts(124, 0)));
449    /// assert_eq!(ts.checked_sub(-1, 1), Ok(mkts(123, 999_999_999)));
450    /// assert_eq!(ts.checked_sub(-1, -1), Ok(mkts(124, 1)));
451    ///
452    /// assert_eq!(ts.checked_sub(0, i32::MIN), Ok(mkts(125, 147_483_648)));
453    /// assert_eq!(ts.checked_sub(1, i32::MIN), Ok(mkts(124, 147_483_648)));
454    /// assert_eq!(ts.checked_sub(-1, i32::MIN), Ok(mkts(126, 147_483_648)));
455    /// assert_eq!(ts.checked_sub(0, i32::MAX), Ok(mkts(121, -147_483_647)));
456    /// assert_eq!(ts.checked_sub(1, i32::MAX), Ok(mkts(120, -147_483_647)));
457    /// assert_eq!(ts.checked_sub(-1, i32::MAX), Ok(mkts(122, -147_483_647)));
458    ///
459    /// assert!(ts.checked_sub(i64::MAX, 0).is_err());
460    /// assert!(ts.checked_sub(i64::MIN, 0).is_err());
461    ///
462    /// let ts = Timestamp::UNIX_EPOCH;
463    /// let min = Timestamp::MIN.as_second();
464    /// assert!(ts.checked_sub(-min, 0).is_ok());
465    /// assert!(ts.checked_sub(-(min - 1), 0).is_err());
466    /// assert!(ts.checked_sub(-min, -999_999_999).is_ok());
467    /// assert!(ts.checked_sub(-min, 1).is_err());
468    /// assert!(ts.checked_sub(-min, 999_999_999).is_err());
469    /// assert!(ts.checked_sub(-min, 1_000_000_000).is_err());
470    /// ```
471    #[inline]
472    pub const fn checked_sub(
473        self,
474        seconds: i64,
475        mut nanos: i32,
476    ) -> Result<Timestamp, RangeError> {
477        let Some(mut seconds) = seconds.checked_neg() else {
478            return Err(b::UnixEpochSeconds::error().into_range_error())rbail!(b::UnixEpochSeconds::error())
479        };
480
481        // When |nanos| exceeds 1 second, we balance the excess up to seconds.
482        if !(-c::NANOS_PER_SEC_32 < nanos && nanos < c::NANOS_PER_SEC_32) {
483            // Never wraps or panics because NANOS_PER_SEC!={0,-1}.
484            let addsecs = nanos / c::NANOS_PER_SEC_32;
485            seconds = match seconds.checked_sub(addsecs as i64) {
486                Some(secs) => secs,
487                None => return Err(b::UnixEpochSeconds::error().into_range_error())rbail!(b::UnixEpochSeconds::error()),
488            };
489            // Never wraps or panics because NANOS_PER_SEC!={0,-1}.
490            nanos = nanos % c::NANOS_PER_SEC_32;
491        }
492        // Negating `nanos` here is OK because the above guarantees that it's
493        // in the inclusive range `[-999_999_999, 999_999_999]`.
494        self.checked_add(seconds, -nanos)
495    }
496
497    /// Implementation of `checked_add` that assumes `|nanos| < 1 second`.
498    #[inline]
499    const fn checked_add_sensible(
500        self,
501        seconds: i64,
502        nanos: i32,
503    ) -> Result<Timestamp, RangeError> {
504        if true {
    if !(-c::NANOS_PER_SEC_32 < nanos && nanos < c::NANOS_PER_SEC_32) {
        ::core::panicking::panic("assertion failed: -c::NANOS_PER_SEC_32 < nanos && nanos < c::NANOS_PER_SEC_32")
    };
};debug_assert!(
505            -c::NANOS_PER_SEC_32 < nanos && nanos < c::NANOS_PER_SEC_32
506        );
507
508        // Delay the timestamp bounds check until after balancing nanoseconds,
509        // which can bring an out-of-range second back into range.
510        let Some(mut second) = self.as_second().checked_add(seconds) else {
511            return Err(b::UnixEpochSeconds::error().into_range_error());rbail!(b::UnixEpochSeconds::error());
512        };
513        // OK because we know both are in the inclusive range
514        // [-999_999_999, 999_999_999] per above math.
515        let mut nanosecond = self.nanosecond + nanos;
516        // When the nanosecond component is zero, we can ignore it and just
517        // return seconds as-is.
518        if nanosecond == 0 {
519            return Timestamp::from_second(second);
520        }
521
522        if nanosecond >= c::NANOS_PER_SEC_32 {
523            nanosecond -= c::NANOS_PER_SEC_32;
524            second = match second.checked_add(1) {
525                Some(secs) => secs,
526                None => return Err(b::UnixEpochSeconds::error().into_range_error())rbail!(b::UnixEpochSeconds::error()),
527            };
528        } else if nanosecond <= -c::NANOS_PER_SEC_32 {
529            nanosecond += c::NANOS_PER_SEC_32;
530            second = match second.checked_sub(1) {
531                Some(secs) => secs,
532                None => return Err(b::UnixEpochSeconds::error().into_range_error())rbail!(b::UnixEpochSeconds::error()),
533            };
534        }
535        if second != 0
536            && nanosecond != 0
537            && second.signum() != (nanosecond.signum() as i64)
538        {
539            if second < 0 {
540                if true {
    if !(nanosecond > 0) {
        ::core::panicking::panic("assertion failed: nanosecond > 0")
    };
};debug_assert!(nanosecond > 0);
541                // OK because second<0.
542                second += 1;
543                // OK because nanosecond>0.
544                nanosecond -= c::NANOS_PER_SEC_32;
545            } else {
546                if true {
    if !(second > 0) {
        ::core::panicking::panic("assertion failed: second > 0")
    };
};debug_assert!(second > 0);
547                if true {
    if !(nanosecond < 0) {
        ::core::panicking::panic("assertion failed: nanosecond < 0")
    };
};debug_assert!(nanosecond < 0);
548                // OK because second>0.
549                second -= 1;
550                // OK because nanosecond<0.
551                nanosecond += c::NANOS_PER_SEC_32;
552            }
553        }
554        let second = match b::UnixEpochSeconds::checkc(second) {
    Ok(val) => val,
    Err(err) => return Err(err.into_range_error()),
}rtry!(b::UnixEpochSeconds::checkc(second));
555        if second == b::UnixEpochSeconds::MIN && nanosecond < 0 {
556            return Err(b::UnixEpochSeconds::error().into_range_error());rbail!(b::UnixEpochSeconds::error());
557        }
558        Ok(Timestamp::new_unchecked(second, nanosecond))
559    }
560
561    /// Add the given number of seconds to this timestamp.
562    ///
563    /// If this would result in a timestamp outside of its boundaries, then
564    /// this returns an error.
565    ///
566    /// The result is normalized so that its non-zero seconds and nanoseconds
567    /// have the same sign. Crossing the Unix epoch may therefore change the
568    /// nanosecond component.
569    ///
570    /// # Examples
571    ///
572    /// ```
573    /// use jiff_core::Timestamp;
574    ///
575    /// let mkts = |sec, nano| Timestamp::new(sec, nano).unwrap();
576    ///
577    /// let ts = mkts(123, 0);
578    /// assert_eq!(ts.checked_add_seconds(0), Ok(mkts(123, 0)));
579    /// assert_eq!(ts.checked_add_seconds(1), Ok(mkts(124, 0)));
580    /// assert_eq!(ts.checked_add_seconds(-1), Ok(mkts(122, 0)));
581    ///
582    /// let ts = mkts(123, 999_999_999);
583    /// assert_eq!(ts.checked_add_seconds(0), Ok(mkts(123, 999_999_999)));
584    /// assert_eq!(ts.checked_add_seconds(1), Ok(mkts(124, 999_999_999)));
585    /// assert_eq!(ts.checked_add_seconds(-1), Ok(mkts(122, 999_999_999)));
586    ///
587    /// let ts = mkts(-1, -500_000_000);
588    /// assert_eq!(ts.checked_add_seconds(2), Ok(mkts(0, 500_000_000)));
589    /// let ts = mkts(1, 500_000_000);
590    /// assert_eq!(ts.checked_add_seconds(-2), Ok(mkts(0, -500_000_000)));
591    ///
592    /// assert!(ts.checked_add_seconds(i64::MIN).is_err());
593    /// assert!(ts.checked_add_seconds(i64::MAX).is_err());
594    /// ```
595    #[inline]
596    pub const fn checked_add_seconds(
597        self,
598        seconds: i64,
599    ) -> Result<Timestamp, RangeError> {
600        self.checked_add(seconds, 0)
601    }
602
603    /// Subtracts the given number of seconds from this timestamp.
604    #[inline]
605    pub const fn checked_sub_seconds(
606        self,
607        seconds: i64,
608    ) -> Result<Timestamp, RangeError> {
609        let Some(seconds) = seconds.checked_neg() else {
610            return Err(b::UnixEpochSeconds::error().into_range_error())rbail!(b::UnixEpochSeconds::error())
611        };
612        self.checked_add_seconds(seconds)
613    }
614}
615
616impl core::fmt::Debug for Timestamp {
617    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
618        let dt = self.to_datetime(Offset::UTC);
619        core::fmt::Debug::fmt(&dt, f)?;
620        f.write_str("Z")
621    }
622}
623
624impl Default for Timestamp {
625    #[inline]
626    fn default() -> Timestamp {
627        Timestamp::UNIX_EPOCH
628    }
629}
630
631/// Adds a number of seconds to a `Timestamp`.
632///
633/// # Panics
634///
635/// When adding would result in a value outside the boundaries of a
636/// `Timestamp`.
637///
638/// # Example
639///
640/// ```
641/// use jiff_core::Timestamp;
642///
643/// let ts = Timestamp::new(123, 999_999_999).unwrap();;
644/// assert_eq!(ts + 400, Timestamp::new(523, 999_999_999).unwrap());
645/// ```
646impl core::ops::Add<i64> for Timestamp {
647    type Output = Timestamp;
648
649    fn add(self, seconds: i64) -> Timestamp {
650        self.checked_add_seconds(seconds).unwrap()
651    }
652}
653
654/// Adds a number of seconds and nanoseconds to a `Timestamp`.
655///
656/// # Panics
657///
658/// When adding would result in a value outside the boundaries of a
659/// `Timestamp`.
660///
661/// # Example
662///
663/// ```
664/// use jiff_core::Timestamp;
665///
666/// let ts = Timestamp::new(123, 999_999_999).unwrap();;
667/// assert_eq!(ts + (400, 1), Timestamp::new(524, 0).unwrap());
668/// ```
669impl core::ops::Add<(i64, i32)> for Timestamp {
670    type Output = Timestamp;
671
672    fn add(self, (seconds, nanoseconds): (i64, i32)) -> Timestamp {
673        self.checked_add(seconds, nanoseconds).unwrap()
674    }
675}
676
677/// Adds a number of seconds to a `Timestamp`.
678///
679/// # Panics
680///
681/// When adding would result in a value outside the boundaries of a
682/// `Timestamp`.
683impl core::ops::AddAssign<i64> for Timestamp {
684    #[inline]
685    fn add_assign(&mut self, rhs: i64) {
686        *self = *self + rhs;
687    }
688}
689
690/// Adds a number of seconds and nanoseconds to a `Timestamp`.
691///
692/// # Panics
693///
694/// When adding would result in a value outside the boundaries of a
695/// `Timestamp`.
696impl core::ops::AddAssign<(i64, i32)> for Timestamp {
697    #[inline]
698    fn add_assign(&mut self, rhs: (i64, i32)) {
699        *self = *self + rhs;
700    }
701}
702
703/// Subtracts a number of seconds from a `Timestamp`.
704///
705/// # Panics
706///
707/// When adding would result in a value outside the boundaries of a
708/// `Timestamp`.
709///
710/// # Example
711///
712/// ```
713/// use jiff_core::Timestamp;
714///
715/// let ts = Timestamp::new(523, 999_999_999).unwrap();;
716/// assert_eq!(ts - 400, Timestamp::new(123, 999_999_999).unwrap());
717/// ```
718impl core::ops::Sub<i64> for Timestamp {
719    type Output = Timestamp;
720
721    fn sub(self, seconds: i64) -> Timestamp {
722        self.checked_sub_seconds(seconds).unwrap()
723    }
724}
725
726/// Subtracts a number of seconds and nanoseconds from a `Timestamp`.
727///
728/// # Panics
729///
730/// When subtracting would result in a value outside the boundaries of a
731/// `Timestamp`.
732///
733/// # Example
734///
735/// ```
736/// use jiff_core::Timestamp;
737///
738/// let ts = Timestamp::new(523, 999_999_999).unwrap();;
739/// assert_eq!(ts - (400, 1), Timestamp::new(123, 999_999_998).unwrap());
740/// ```
741impl core::ops::Sub<(i64, i32)> for Timestamp {
742    type Output = Timestamp;
743
744    fn sub(self, (seconds, nanoseconds): (i64, i32)) -> Timestamp {
745        self.checked_sub(seconds, nanoseconds).unwrap()
746    }
747}
748
749/// Subtracts a number of seconds from a `Timestamp`.
750///
751/// # Panics
752///
753/// When subtracting would result in a value outside the boundaries of a
754/// `Timestamp`.
755impl core::ops::SubAssign<i64> for Timestamp {
756    #[inline]
757    fn sub_assign(&mut self, rhs: i64) {
758        *self = *self - rhs;
759    }
760}
761
762/// Subtracts a number of seconds and nanoseconds from a `Timestamp`.
763///
764/// # Panics
765///
766/// When subtracting would result in a value outside the boundaries of a
767/// `Timestamp`.
768impl core::ops::SubAssign<(i64, i32)> for Timestamp {
769    #[inline]
770    fn sub_assign(&mut self, rhs: (i64, i32)) {
771        *self = *self - rhs;
772    }
773}
774
775#[cfg(feature = "arbitrary")]
776impl<'a> arbitrary::Arbitrary<'a> for Timestamp {
777    fn arbitrary(
778        u: &mut arbitrary::Unstructured<'a>,
779    ) -> arbitrary::Result<Timestamp> {
780        let secs = u.int_in_range(
781            b::UnixEpochSeconds::MIN..=b::UnixEpochSeconds::MAX,
782        )?;
783        let mut nanos = u.int_in_range(
784            b::SignedSubsecNanosecond::MIN..=b::SignedSubsecNanosecond::MAX,
785        )?;
786        // nanoseconds must be zero for the minimum second value,
787        // so just clamp it to 0.
788        if secs == b::UnixEpochSeconds::MIN && nanos < 0 {
789            nanos = 0;
790        }
791        Ok(Timestamp::new(secs, nanos).unwrap_or(Timestamp::UNIX_EPOCH))
792    }
793
794    fn size_hint(depth: usize) -> (usize, Option<usize>) {
795        arbitrary::size_hint::and(
796            <i64 as arbitrary::Arbitrary>::size_hint(depth),
797            <i32 as arbitrary::Arbitrary>::size_hint(depth),
798        )
799    }
800}
801
802#[cfg(test)]
803impl quickcheck::Arbitrary for Timestamp {
804    fn arbitrary(g: &mut quickcheck::Gen) -> Timestamp {
805        let secs = b::UnixEpochSeconds::arbitrary(g);
806        let mut nanos = b::SignedSubsecNanosecond::arbitrary(g);
807        // nanoseconds must be zero for the minimum second value,
808        // so just clamp it to 0.
809        if secs == b::UnixEpochSeconds::MIN && nanos < 0 {
810            nanos = 0;
811        }
812        Timestamp::new(secs, nanos).unwrap_or(Timestamp::UNIX_EPOCH)
813    }
814
815    fn shrink(&self) -> alloc::boxed::Box<dyn Iterator<Item = Self>> {
816        let secs = self.as_second();
817        let nanos = self.subsec_nanosecond();
818        alloc::boxed::Box::new((secs, nanos).shrink().filter_map(
819            |(secs, nanos)| {
820                let secs = b::UnixEpochSeconds::check(secs).ok()?;
821                let nanos = b::SignedSubsecNanosecond::check(nanos).ok()?;
822                if secs == b::UnixEpochSeconds::MIN && nanos > 0 {
823                    None
824                } else {
825                    Timestamp::new(secs, nanos).ok()
826                }
827            },
828        ))
829    }
830}
831
832#[cfg(test)]
833mod tests {
834    use super::*;
835
836    #[track_caller]
837    fn datetime(
838        year: i16,
839        month: i8,
840        day: i8,
841        hour: i8,
842        minute: i8,
843        second: i8,
844        subsec_nanosecond: i32,
845    ) -> DateTime {
846        DateTime::new(
847            year,
848            month,
849            day,
850            hour,
851            minute,
852            second,
853            subsec_nanosecond,
854        )
855        .unwrap()
856    }
857
858    #[track_caller]
859    fn stamp(second: i64, subsec: i32) -> Timestamp {
860        Timestamp::new(second, subsec).unwrap()
861    }
862
863    #[track_caller]
864    fn offset(second: i32) -> Offset {
865        Offset::from_seconds(second).unwrap()
866    }
867
868    // Regression test for: https://github.com/BurntSushi/jiff/pull/695
869    #[test]
870    fn sub_assign() {
871        for (rhs, expected) in [(400, 600), (-400, 1400), (0, 1000)] {
872            let mut ts = stamp(1000, 0);
873            ts -= rhs;
874            assert_eq!(ts, stamp(expected, 0));
875        }
876
877        for (rhs, expected) in [
878            ((400, 1), stamp(599, 999_999_999)),
879            ((-400, -1), stamp(1400, 1)),
880            ((0, 0), stamp(1000, 0)),
881        ] {
882            let mut ts = stamp(1000, 0);
883            ts -= rhs;
884            assert_eq!(ts, expected);
885        }
886    }
887
888    #[test]
889    fn new_ok() {
890        let ts = stamp(0, 0);
891        assert_eq!(ts, Timestamp::UNIX_EPOCH);
892
893        let ts = stamp(0, 123_000_000);
894        assert_eq!(ts.as_second(), 0);
895        assert_eq!(ts.subsec_nanosecond(), 123_000_000);
896
897        let ts = stamp(0, -123_000_000);
898        assert_eq!(ts.as_second(), 0);
899        assert_eq!(ts.subsec_nanosecond(), -123_000_000);
900
901        let ts = stamp(1, 0);
902        assert_eq!(ts.as_second(), 1);
903        assert_eq!(ts.subsec_nanosecond(), 0);
904
905        let ts = stamp(-1, 0);
906        assert_eq!(ts.as_second(), -1);
907        assert_eq!(ts.subsec_nanosecond(), 0);
908
909        let ts = stamp(1, 123_000_000);
910        assert_eq!(ts.as_second(), 1);
911        assert_eq!(ts.subsec_nanosecond(), 123_000_000);
912
913        let ts = stamp(-1, -123_000_000);
914        assert_eq!(ts.as_second(), -1);
915        assert_eq!(ts.subsec_nanosecond(), -123_000_000);
916
917        let ts = stamp(1, -123_000_000);
918        assert_eq!(ts.as_second(), 0);
919        assert_eq!(ts.subsec_nanosecond(), 877_000_000);
920
921        let ts = stamp(-1, 123_000_000);
922        assert_eq!(ts.as_second(), 0);
923        assert_eq!(ts.subsec_nanosecond(), -877_000_000);
924
925        let ts = stamp(-377705023201, 0);
926        assert_eq!(ts, Timestamp::MIN);
927
928        let ts = stamp(253402207200, 999_999_999);
929        assert_eq!(ts, Timestamp::MAX);
930    }
931
932    #[test]
933    fn new_err() {
934        assert!(Timestamp::new(0, 1_000_000_000).is_err());
935        assert!(Timestamp::new(0, -1_000_000_000).is_err());
936        assert!(Timestamp::new(1, 1_000_000_000).is_err());
937        assert!(Timestamp::new(1, -1_000_000_000).is_err());
938        assert!(Timestamp::new(-1, 1_000_000_000).is_err());
939        assert!(Timestamp::new(-1, -1_000_000_000).is_err());
940        assert!(Timestamp::new(0, i32::MAX).is_err());
941        assert!(Timestamp::new(0, i32::MIN).is_err());
942        assert!(Timestamp::new(-377705023201, -1).is_err());
943        assert!(Timestamp::new(253402207201, 0).is_err());
944    }
945
946    // Regression test for #645: `Timestamp::from_nanosecond` panicked
947    // instead of returning an error when the given nanosecond count fell
948    // just outside of `Timestamp::MIN..=Timestamp::MAX`, even though its
949    // signature (and docs) promise a `Result`.
950    #[test]
951    fn from_nanosecond_err() {
952        let min = Timestamp::MIN.as_nanosecond();
953        assert_eq!(Timestamp::from_nanosecond(min).unwrap(), Timestamp::MIN);
954        assert!(Timestamp::from_nanosecond(min - 1).is_err());
955
956        let max = Timestamp::MAX.as_nanosecond();
957        assert_eq!(Timestamp::from_nanosecond(max).unwrap(), Timestamp::MAX);
958        assert!(Timestamp::from_nanosecond(max + 1).is_err());
959
960        assert!(Timestamp::from_nanosecond(i128::MIN).is_err());
961        assert!(Timestamp::from_nanosecond(i128::MAX).is_err());
962    }
963
964    // Regression tests for #696.
965    #[test]
966    fn checked_arithmetic_below_min() {
967        assert!(Timestamp::MIN.checked_add(0, -1).is_err());
968        assert!(Timestamp::MIN.checked_sub(0, 1).is_err());
969    }
970
971    #[test]
972    fn checked_arithmetic_overflow() {
973        for ts in [Timestamp::MIN, Timestamp::UNIX_EPOCH, Timestamp::MAX] {
974            for seconds in [i64::MIN, i64::MIN + 1, i64::MAX - 1, i64::MAX] {
975                for nanos in [i32::MIN, -1, 0, 1, i32::MAX] {
976                    assert!(ts.checked_add(seconds, nanos).is_err());
977                    assert!(ts.checked_sub(seconds, nanos).is_err());
978                }
979            }
980        }
981    }
982
983    #[test]
984    fn checked_arithmetic_at_max() {
985        let ts = stamp(1, 0);
986        let seconds = Timestamp::MAX.as_second();
987        assert_eq!(ts.checked_add(seconds, -1), Ok(Timestamp::MAX));
988        assert_eq!(ts.checked_sub(-seconds, 1), Ok(Timestamp::MAX));
989        assert_eq!(ts + (seconds, -1), Timestamp::MAX);
990        assert_eq!(ts - (-seconds, 1), Timestamp::MAX);
991    }
992
993    // Regression tests for #703.
994    #[test]
995    fn checked_seconds_across_epoch() {
996        for (ts, seconds, expected) in [
997            (stamp(-1, -500_000_000), 2, stamp(0, 500_000_000)),
998            (stamp(1, 500_000_000), -2, stamp(0, -500_000_000)),
999            (stamp(-1, -1), 3, stamp(1, 999_999_999)),
1000            (stamp(1, 1), -3, stamp(-1, -999_999_999)),
1001            (stamp(0, -1), 1, stamp(0, 999_999_999)),
1002            (stamp(0, 1), -1, stamp(0, -999_999_999)),
1003        ] {
1004            assert_eq!(ts.checked_add_seconds(seconds), Ok(expected));
1005            assert_eq!(ts.checked_sub_seconds(-seconds), Ok(expected));
1006            assert_eq!(ts + seconds, expected);
1007            assert_eq!(ts - -seconds, expected);
1008        }
1009    }
1010
1011    #[test]
1012    fn checked_arithmetic_boundaries() {
1013        let min = Timestamp::MIN.as_second();
1014        let max = Timestamp::MAX.as_second();
1015        let timestamps = [
1016            Timestamp::MIN,
1017            stamp(min + 1, -999_999_999),
1018            stamp(-1, -999_999_999),
1019            stamp(-1, 0),
1020            stamp(0, -1),
1021            Timestamp::UNIX_EPOCH,
1022            stamp(0, 1),
1023            stamp(1, 0),
1024            stamp(1, 999_999_999),
1025            stamp(max, 999_999_998),
1026            Timestamp::MAX,
1027        ];
1028        let seconds = [
1029            i64::MIN,
1030            min - max - 1,
1031            min - max,
1032            min - 1,
1033            min,
1034            min + 1,
1035            -1,
1036            0,
1037            1,
1038            max - 1,
1039            max,
1040            max + 1,
1041            max - min,
1042            max - min + 1,
1043            i64::MAX,
1044        ];
1045        let nanos = [
1046            i32::MIN,
1047            -1_000_000_000,
1048            -999_999_999,
1049            -1,
1050            0,
1051            1,
1052            999_999_999,
1053            1_000_000_000,
1054            i32::MAX,
1055        ];
1056        for ts in timestamps {
1057            for seconds in seconds {
1058                let delta = (seconds as i128) * (c::NANOS_PER_SEC as i128);
1059                assert_eq!(
1060                    ts.checked_add_seconds(seconds).ok(),
1061                    Timestamp::from_nanosecond(ts.as_nanosecond() + delta)
1062                        .ok(),
1063                    "{ts:?} + {seconds}",
1064                );
1065                assert_eq!(
1066                    ts.checked_sub_seconds(seconds).ok(),
1067                    Timestamp::from_nanosecond(ts.as_nanosecond() - delta)
1068                        .ok(),
1069                    "{ts:?} - {seconds}",
1070                );
1071                for nanos in nanos {
1072                    let delta = delta + (nanos as i128);
1073                    let sum = ts.as_nanosecond() + delta;
1074                    let difference = ts.as_nanosecond() - delta;
1075                    assert_eq!(
1076                        ts.checked_add(seconds, nanos).ok(),
1077                        Timestamp::from_nanosecond(sum).ok(),
1078                        "{ts:?} + ({seconds}, {nanos})",
1079                    );
1080                    assert_eq!(
1081                        ts.checked_sub(seconds, nanos).ok(),
1082                        Timestamp::from_nanosecond(difference).ok(),
1083                        "{ts:?} - ({seconds}, {nanos})",
1084                    );
1085                }
1086            }
1087        }
1088    }
1089
1090    #[test]
1091    fn to_datetime_no_subsec() {
1092        let dt = datetime(1970, 1, 1, 0, 0, 0, 0);
1093        assert_eq!(stamp(0, 0).to_datetime(offset(0)), dt);
1094        assert_eq!(stamp(-3600, 0).to_datetime(offset(3600)), dt);
1095        assert_eq!(stamp(3600, 0).to_datetime(offset(-3600)), dt);
1096
1097        let dt = datetime(1969, 12, 31, 23, 30, 0, 0);
1098        assert_eq!(stamp(-1800, 0).to_datetime(offset(0)), dt);
1099        assert_eq!(stamp(-5400, 0).to_datetime(offset(3600)), dt);
1100        assert_eq!(stamp(1800, 0).to_datetime(offset(-3600)), dt);
1101
1102        let dt = datetime(1970, 1, 1, 0, 30, 0, 0);
1103        assert_eq!(stamp(1800, 0).to_datetime(offset(0)), dt);
1104        assert_eq!(stamp(-1800, 0).to_datetime(offset(3600)), dt);
1105        assert_eq!(stamp(5400, 0).to_datetime(offset(-3600)), dt);
1106    }
1107
1108    #[test]
1109    fn to_datetime_with_subsec() {
1110        let dt = datetime(1970, 1, 1, 0, 0, 0, 123);
1111        assert_eq!(stamp(0, 123).to_datetime(offset(0)), dt);
1112        assert_eq!(stamp(-3599, -999_999_877).to_datetime(offset(3600)), dt);
1113        assert_eq!(stamp(3600, 123).to_datetime(offset(-3600)), dt);
1114
1115        let dt = datetime(1969, 12, 31, 23, 30, 0, 123);
1116        assert_eq!(stamp(-1799, -999_999_877).to_datetime(offset(0)), dt);
1117        assert_eq!(stamp(-5399, -999_999_877).to_datetime(offset(3600)), dt);
1118        assert_eq!(stamp(1800, 123).to_datetime(offset(-3600)), dt);
1119
1120        let dt = datetime(1970, 1, 1, 0, 30, 0, 123);
1121        assert_eq!(stamp(1800, 123).to_datetime(offset(0)), dt);
1122        assert_eq!(stamp(-1799, -999_999_877).to_datetime(offset(3600)), dt);
1123        assert_eq!(stamp(5400, 123).to_datetime(offset(-3600)), dt);
1124    }
1125
1126    #[test]
1127    fn to_datetime_limits() {
1128        assert_eq!(Timestamp::MIN.to_datetime(Offset::MIN), DateTime::MIN);
1129        assert_eq!(Timestamp::MAX.to_datetime(Offset::MAX), DateTime::MAX);
1130    }
1131
1132    quickcheck::quickcheck! {
1133        fn prop_timestamp_datetime_roundtrip(
1134            ts: Timestamp,
1135            offset: Offset
1136        ) -> bool {
1137            let dt = ts.to_datetime(offset);
1138            let got = dt.to_timestamp(offset).unwrap();
1139            got == ts
1140        }
1141    }
1142}