nautilus_core/
nanos.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! A `UnixNanos` type for working with timestamps in nanoseconds since the UNIX epoch.
17//!
18//! This module provides a strongly-typed representation of timestamps as nanoseconds
19//! since the UNIX epoch (January 1, 1970, 00:00:00 UTC). The `UnixNanos` type offers
20//! conversion utilities, arithmetic operations, and comparison methods.
21//!
22//! # Features
23//!
24//! - Zero-cost abstraction with appropriate operator implementations.
25//! - Conversion to/from `DateTime<Utc>`.
26//! - RFC 3339 string formatting.
27//! - Duration calculations.
28//! - Flexible parsing and serialization.
29//!
30//! # Parsing and Serialization
31#![allow(
32    clippy::cast_possible_truncation,
33    clippy::cast_sign_loss,
34    clippy::cast_precision_loss,
35    clippy::cast_possible_wrap
36)]
37//!
38//! `UnixNanos` can be created from and serialized to various formats:
39//!
40//! * Integer values are interpreted as nanoseconds since the UNIX epoch.
41//! * Floating-point values are interpreted as seconds since the UNIX epoch (converted to nanoseconds).
42//! * String values may be:
43//!   - A numeric string (interpreted as nanoseconds).
44//!   - A floating-point string (interpreted as seconds, converted to nanoseconds).
45//!   - An RFC 3339 formatted timestamp (ISO 8601 with timezone).
46//!   - A simple date string in YYYY-MM-DD format (interpreted as midnight UTC on that date).
47//!
48//! # Limitations
49//!
50//! * Negative timestamps are invalid and will result in an error.
51//! * Arithmetic operations will panic on overflow/underflow rather than wrapping.
52
53use std::{
54    cmp::Ordering,
55    fmt::Display,
56    ops::{Add, AddAssign, Deref, Sub, SubAssign},
57    str::FromStr,
58};
59
60use chrono::{DateTime, NaiveDate, Utc};
61use serde::{
62    Deserialize, Deserializer, Serialize,
63    de::{self, Visitor},
64};
65
66/// Represents a duration in nanoseconds.
67pub type DurationNanos = u64;
68
69/// Represents a timestamp in nanoseconds since the UNIX epoch.
70#[repr(C)]
71#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
72pub struct UnixNanos(u64);
73
74impl UnixNanos {
75    /// Creates a new [`UnixNanos`] instance.
76    #[must_use]
77    pub const fn new(value: u64) -> Self {
78        Self(value)
79    }
80
81    /// Creates a new [`UnixNanos`] instance with the maximum valid value.
82    #[must_use]
83    pub const fn max() -> Self {
84        Self(u64::MAX)
85    }
86
87    /// Returns `true` if the value of this instance is zero.
88    #[must_use]
89    pub const fn is_zero(&self) -> bool {
90        self.0 == 0
91    }
92
93    /// Returns the underlying value as `u64`.
94    #[must_use]
95    pub const fn as_u64(&self) -> u64 {
96        self.0
97    }
98
99    /// Returns the underlying value as `i64`.
100    ///
101    /// # Panics
102    ///
103    /// Panics if the value exceeds `i64::MAX` (approximately year 2262).
104    #[must_use]
105    pub const fn as_i64(&self) -> i64 {
106        assert!(
107            self.0 <= i64::MAX as u64,
108            "UnixNanos value exceeds i64::MAX"
109        );
110        self.0 as i64
111    }
112
113    /// Returns the underlying value as `f64`.
114    #[must_use]
115    pub const fn as_f64(&self) -> f64 {
116        self.0 as f64
117    }
118
119    /// Converts the underlying value to a datetime (UTC).
120    ///
121    /// # Panics
122    ///
123    /// Panics if the value exceeds `i64::MAX` (approximately year 2262).
124    #[must_use]
125    pub const fn to_datetime_utc(&self) -> DateTime<Utc> {
126        DateTime::from_timestamp_nanos(self.as_i64())
127    }
128
129    /// Converts the underlying value to an ISO 8601 (RFC 3339) string.
130    #[must_use]
131    pub fn to_rfc3339(&self) -> String {
132        self.to_datetime_utc().to_rfc3339()
133    }
134
135    /// Calculates the duration in nanoseconds since another [`UnixNanos`] instance.
136    ///
137    /// Returns `Some(duration)` if `self` is later than `other`, otherwise `None` if `other` is
138    /// greater than `self` (indicating a negative duration is not possible with `DurationNanos`).
139    #[must_use]
140    pub const fn duration_since(&self, other: &Self) -> Option<DurationNanos> {
141        self.0.checked_sub(other.0)
142    }
143
144    fn parse_string(s: &str) -> Result<Self, String> {
145        // Try parsing as an integer (nanoseconds)
146        if let Ok(int_value) = s.parse::<u64>() {
147            return Ok(Self(int_value));
148        }
149
150        // If the string is composed solely of digits but didn't fit in a u64 we
151        // treat that as an overflow error rather than attempting to interpret
152        // it as seconds in floating-point form. This avoids the surprising
153        // situation where a caller provides nanoseconds but gets an out-of-
154        // range float interpretation instead.
155        if s.chars().all(|c| c.is_ascii_digit()) {
156            return Err("Unix timestamp is out of range".into());
157        }
158
159        // Try parsing as a floating point number (seconds)
160        if let Ok(float_value) = s.parse::<f64>() {
161            if !float_value.is_finite() {
162                return Err("Unix timestamp must be finite".into());
163            }
164
165            if float_value < 0.0 {
166                return Err("Unix timestamp cannot be negative".into());
167            }
168
169            // Convert seconds to nanoseconds while checking for overflow
170            // We perform the multiplication in `f64`, then validate the
171            // result fits inside `u64` *before* rounding / casting.
172            const MAX_NS_F64: f64 = u64::MAX as f64;
173            let nanos_f64 = float_value * 1_000_000_000.0;
174
175            if nanos_f64 > MAX_NS_F64 {
176                return Err("Unix timestamp is out of range".into());
177            }
178
179            let nanos = nanos_f64.round() as u64;
180            return Ok(Self(nanos));
181        }
182
183        // Try parsing as an RFC 3339 timestamp
184        if let Ok(datetime) = DateTime::parse_from_rfc3339(s) {
185            let nanos = datetime
186                .timestamp_nanos_opt()
187                .ok_or_else(|| "Timestamp out of range".to_string())?;
188
189            if nanos < 0 {
190                return Err("Unix timestamp cannot be negative".into());
191            }
192
193            // SAFETY: Checked that nanos >= 0, so cast to u64 is safe
194            return Ok(Self(nanos as u64));
195        }
196
197        // Try parsing as a simple date string (YYYY-MM-DD format)
198        if let Ok(datetime) = NaiveDate::parse_from_str(s, "%Y-%m-%d")
199            // SAFETY: unwrap() is safe here because and_hms_opt(0, 0, 0) always succeeds
200            // for valid dates (midnight is always a valid time)
201            .map(|date| date.and_hms_opt(0, 0, 0).unwrap())
202            .map(|naive_dt| DateTime::<Utc>::from_naive_utc_and_offset(naive_dt, Utc))
203        {
204            let nanos = datetime
205                .timestamp_nanos_opt()
206                .ok_or_else(|| "Timestamp out of range".to_string())?;
207            if nanos < 0 {
208                return Err("Unix timestamp cannot be negative".into());
209            }
210            return Ok(Self(nanos as u64));
211        }
212
213        Err(format!("Invalid format: {s}"))
214    }
215
216    /// Returns `Some(self + rhs)` or `None` if the addition would overflow
217    #[must_use]
218    pub fn checked_add<T: Into<u64>>(self, rhs: T) -> Option<Self> {
219        self.0.checked_add(rhs.into()).map(Self)
220    }
221
222    /// Returns `Some(self - rhs)` or `None` if the subtraction would underflow
223    #[must_use]
224    pub fn checked_sub<T: Into<u64>>(self, rhs: T) -> Option<Self> {
225        self.0.checked_sub(rhs.into()).map(Self)
226    }
227
228    /// Saturating addition – if overflow occurs the value is clamped to `u64::MAX`.
229    #[must_use]
230    pub fn saturating_add_ns<T: Into<u64>>(self, rhs: T) -> Self {
231        Self(self.0.saturating_add(rhs.into()))
232    }
233
234    /// Saturating subtraction – if underflow occurs the value is clamped to `0`.
235    #[must_use]
236    pub fn saturating_sub_ns<T: Into<u64>>(self, rhs: T) -> Self {
237        Self(self.0.saturating_sub(rhs.into()))
238    }
239}
240
241impl Deref for UnixNanos {
242    type Target = u64;
243
244    fn deref(&self) -> &Self::Target {
245        &self.0
246    }
247}
248
249impl PartialEq<u64> for UnixNanos {
250    fn eq(&self, other: &u64) -> bool {
251        self.0 == *other
252    }
253}
254
255impl PartialOrd<u64> for UnixNanos {
256    fn partial_cmp(&self, other: &u64) -> Option<Ordering> {
257        self.0.partial_cmp(other)
258    }
259}
260
261impl PartialEq<Option<u64>> for UnixNanos {
262    fn eq(&self, other: &Option<u64>) -> bool {
263        match other {
264            Some(value) => self.0 == *value,
265            None => false,
266        }
267    }
268}
269
270impl PartialOrd<Option<u64>> for UnixNanos {
271    fn partial_cmp(&self, other: &Option<u64>) -> Option<Ordering> {
272        match other {
273            Some(value) => self.0.partial_cmp(value),
274            None => Some(Ordering::Greater),
275        }
276    }
277}
278
279impl PartialEq<UnixNanos> for u64 {
280    fn eq(&self, other: &UnixNanos) -> bool {
281        *self == other.0
282    }
283}
284
285impl PartialOrd<UnixNanos> for u64 {
286    fn partial_cmp(&self, other: &UnixNanos) -> Option<Ordering> {
287        self.partial_cmp(&other.0)
288    }
289}
290
291impl From<u64> for UnixNanos {
292    fn from(value: u64) -> Self {
293        Self(value)
294    }
295}
296
297impl From<UnixNanos> for u64 {
298    fn from(value: UnixNanos) -> Self {
299        value.0
300    }
301}
302
303/// Converts a string slice to [`UnixNanos`].
304///
305/// # Panics
306///
307/// This implementation will panic if the string cannot be parsed into a valid [`UnixNanos`].
308/// This is intentional fail-fast behavior where invalid timestamps indicate a critical
309/// logic error that should halt execution rather than silently propagate incorrect data.
310///
311/// For error handling without panicking, use [`str::parse::<UnixNanos>()`] which returns
312/// a [`Result`].
313///
314/// # Examples
315///
316/// ```
317/// use nautilus_core::UnixNanos;
318///
319/// let nanos = UnixNanos::from("1234567890");
320/// assert_eq!(nanos.as_u64(), 1234567890);
321/// ```
322impl From<&str> for UnixNanos {
323    fn from(value: &str) -> Self {
324        value
325            .parse()
326            .unwrap_or_else(|e| panic!("Failed to parse string '{value}' into UnixNanos: {e}. Use str::parse() for non-panicking error handling."))
327    }
328}
329
330/// Converts a [`String`] to [`UnixNanos`].
331///
332/// # Panics
333///
334/// This implementation will panic if the string cannot be parsed into a valid [`UnixNanos`].
335/// This is intentional fail-fast behavior where invalid timestamps indicate a critical
336/// logic error that should halt execution rather than silently propagate incorrect data.
337///
338/// For error handling without panicking, use [`str::parse::<UnixNanos>()`] which returns
339/// a [`Result`].
340impl From<String> for UnixNanos {
341    fn from(value: String) -> Self {
342        value
343            .parse()
344            .unwrap_or_else(|e| panic!("Failed to parse string '{value}' into UnixNanos: {e}. Use str::parse() for non-panicking error handling."))
345    }
346}
347
348impl From<DateTime<Utc>> for UnixNanos {
349    fn from(value: DateTime<Utc>) -> Self {
350        let nanos = value
351            .timestamp_nanos_opt()
352            .expect("DateTime timestamp out of range for UnixNanos");
353
354        assert!(nanos >= 0, "DateTime timestamp cannot be negative: {nanos}");
355
356        Self::from(nanos as u64)
357    }
358}
359
360impl FromStr for UnixNanos {
361    type Err = Box<dyn std::error::Error>;
362
363    fn from_str(s: &str) -> Result<Self, Self::Err> {
364        Self::parse_string(s).map_err(std::convert::Into::into)
365    }
366}
367
368/// Adds two [`UnixNanos`] values.
369///
370/// # Panics
371///
372/// Panics on overflow. This is intentional fail-fast behavior: overflow in timestamp
373/// arithmetic indicates a logic error in calculations that would corrupt data.
374/// Use [`UnixNanos::checked_add()`] or [`UnixNanos::saturating_add_ns()`] if you need
375/// explicit overflow handling.
376impl Add for UnixNanos {
377    type Output = Self;
378
379    fn add(self, rhs: Self) -> Self::Output {
380        Self(
381            self.0
382                .checked_add(rhs.0)
383                .expect("UnixNanos overflow in addition - invalid timestamp calculation"),
384        )
385    }
386}
387
388/// Subtracts one [`UnixNanos`] from another.
389///
390/// # Panics
391///
392/// Panics on underflow. This is intentional fail-fast behavior: underflow in timestamp
393/// arithmetic indicates a logic error in calculations that would corrupt data.
394/// Use [`UnixNanos::checked_sub()`] or [`UnixNanos::saturating_sub_ns()`] if you need
395/// explicit underflow handling.
396impl Sub for UnixNanos {
397    type Output = Self;
398
399    fn sub(self, rhs: Self) -> Self::Output {
400        Self(
401            self.0
402                .checked_sub(rhs.0)
403                .expect("UnixNanos underflow in subtraction - invalid timestamp calculation"),
404        )
405    }
406}
407
408/// Adds a `u64` nanosecond value to [`UnixNanos`].
409///
410/// # Panics
411///
412/// Panics on overflow. This is intentional fail-fast behavior for timestamp arithmetic.
413/// Use [`UnixNanos::checked_add()`] for explicit overflow handling.
414impl Add<u64> for UnixNanos {
415    type Output = Self;
416
417    fn add(self, rhs: u64) -> Self::Output {
418        Self(
419            self.0
420                .checked_add(rhs)
421                .expect("UnixNanos overflow in addition"),
422        )
423    }
424}
425
426/// Subtracts a `u64` nanosecond value from [`UnixNanos`].
427///
428/// # Panics
429///
430/// Panics on underflow. This is intentional fail-fast behavior for timestamp arithmetic.
431/// Use [`UnixNanos::checked_sub()`] for explicit underflow handling.
432impl Sub<u64> for UnixNanos {
433    type Output = Self;
434
435    fn sub(self, rhs: u64) -> Self::Output {
436        Self(
437            self.0
438                .checked_sub(rhs)
439                .expect("UnixNanos underflow in subtraction"),
440        )
441    }
442}
443
444/// Add-assigns a value to [`UnixNanos`].
445///
446/// # Panics
447///
448/// Panics on overflow. This is intentional fail-fast behavior for timestamp arithmetic.
449impl<T: Into<u64>> AddAssign<T> for UnixNanos {
450    fn add_assign(&mut self, other: T) {
451        let other_u64 = other.into();
452        self.0 = self
453            .0
454            .checked_add(other_u64)
455            .expect("UnixNanos overflow in add_assign");
456    }
457}
458
459/// Sub-assigns a value from [`UnixNanos`].
460///
461/// # Panics
462///
463/// Panics on underflow. This is intentional fail-fast behavior for timestamp arithmetic.
464impl<T: Into<u64>> SubAssign<T> for UnixNanos {
465    fn sub_assign(&mut self, other: T) {
466        let other_u64 = other.into();
467        self.0 = self
468            .0
469            .checked_sub(other_u64)
470            .expect("UnixNanos underflow in sub_assign");
471    }
472}
473
474impl Display for UnixNanos {
475    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476        write!(f, "{}", self.0)
477    }
478}
479
480impl From<UnixNanos> for DateTime<Utc> {
481    fn from(value: UnixNanos) -> Self {
482        value.to_datetime_utc()
483    }
484}
485
486impl<'de> Deserialize<'de> for UnixNanos {
487    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
488    where
489        D: Deserializer<'de>,
490    {
491        struct UnixNanosVisitor;
492
493        impl Visitor<'_> for UnixNanosVisitor {
494            type Value = UnixNanos;
495
496            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
497                formatter.write_str("an integer, a string integer, or an RFC 3339 timestamp")
498            }
499
500            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
501            where
502                E: de::Error,
503            {
504                Ok(UnixNanos(value))
505            }
506
507            fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
508            where
509                E: de::Error,
510            {
511                if value < 0 {
512                    return Err(E::custom("Unix timestamp cannot be negative"));
513                }
514                Ok(UnixNanos(value as u64))
515            }
516
517            fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
518            where
519                E: de::Error,
520            {
521                if !value.is_finite() {
522                    return Err(E::custom(format!(
523                        "Unix timestamp must be finite, got {value}"
524                    )));
525                }
526                if value < 0.0 {
527                    return Err(E::custom("Unix timestamp cannot be negative"));
528                }
529                // Convert from seconds to nanoseconds with overflow check
530                const MAX_NS_F64: f64 = u64::MAX as f64;
531                let nanos_f64 = value * 1_000_000_000.0;
532                if nanos_f64 > MAX_NS_F64 {
533                    return Err(E::custom(format!(
534                        "Unix timestamp {value} seconds is out of range"
535                    )));
536                }
537                let nanos = nanos_f64.round() as u64;
538                Ok(UnixNanos(nanos))
539            }
540
541            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
542            where
543                E: de::Error,
544            {
545                UnixNanos::parse_string(value).map_err(E::custom)
546            }
547        }
548
549        deserializer.deserialize_any(UnixNanosVisitor)
550    }
551}
552
553////////////////////////////////////////////////////////////////////////////////
554// Tests
555////////////////////////////////////////////////////////////////////////////////
556#[cfg(test)]
557mod tests {
558    use chrono::{Duration, TimeZone};
559    use rstest::rstest;
560
561    use super::*;
562
563    #[rstest]
564    fn test_new() {
565        let nanos = UnixNanos::new(123);
566        assert_eq!(nanos.as_u64(), 123);
567        assert_eq!(nanos.as_i64(), 123);
568    }
569
570    #[rstest]
571    fn test_max() {
572        let nanos = UnixNanos::max();
573        assert_eq!(nanos.as_u64(), u64::MAX);
574    }
575
576    #[rstest]
577    fn test_is_zero() {
578        assert!(UnixNanos::default().is_zero());
579        assert!(!UnixNanos::max().is_zero());
580    }
581
582    #[rstest]
583    fn test_from_u64() {
584        let nanos = UnixNanos::from(123);
585        assert_eq!(nanos.as_u64(), 123);
586        assert_eq!(nanos.as_i64(), 123);
587    }
588
589    #[rstest]
590    fn test_default() {
591        let nanos = UnixNanos::default();
592        assert_eq!(nanos.as_u64(), 0);
593        assert_eq!(nanos.as_i64(), 0);
594    }
595
596    #[rstest]
597    fn test_into_from() {
598        let nanos: UnixNanos = 456.into();
599        let value: u64 = nanos.into();
600        assert_eq!(value, 456);
601    }
602
603    #[rstest]
604    #[case(0, "1970-01-01T00:00:00+00:00")]
605    #[case(1_000_000_000, "1970-01-01T00:00:01+00:00")]
606    #[case(1_000_000_000_000_000_000, "2001-09-09T01:46:40+00:00")]
607    #[case(1_500_000_000_000_000_000, "2017-07-14T02:40:00+00:00")]
608    #[case(1_707_577_123_456_789_000, "2024-02-10T14:58:43.456789+00:00")]
609    fn test_to_datetime_utc(#[case] nanos: u64, #[case] expected: &str) {
610        let nanos = UnixNanos::from(nanos);
611        let datetime = nanos.to_datetime_utc();
612        assert_eq!(datetime.to_rfc3339(), expected);
613    }
614
615    #[rstest]
616    #[case(0, "1970-01-01T00:00:00+00:00")]
617    #[case(1_000_000_000, "1970-01-01T00:00:01+00:00")]
618    #[case(1_000_000_000_000_000_000, "2001-09-09T01:46:40+00:00")]
619    #[case(1_500_000_000_000_000_000, "2017-07-14T02:40:00+00:00")]
620    #[case(1_707_577_123_456_789_000, "2024-02-10T14:58:43.456789+00:00")]
621    fn test_to_rfc3339(#[case] nanos: u64, #[case] expected: &str) {
622        let nanos = UnixNanos::from(nanos);
623        assert_eq!(nanos.to_rfc3339(), expected);
624    }
625
626    #[rstest]
627    fn test_from_str() {
628        let nanos: UnixNanos = "123".parse().unwrap();
629        assert_eq!(nanos.as_u64(), 123);
630    }
631
632    #[rstest]
633    fn test_from_str_invalid() {
634        let result = "abc".parse::<UnixNanos>();
635        assert!(result.is_err());
636    }
637
638    #[rstest]
639    fn test_from_str_pre_epoch_date() {
640        let err = "1969-12-31".parse::<UnixNanos>().unwrap_err();
641        assert_eq!(err.to_string(), "Unix timestamp cannot be negative");
642    }
643
644    #[rstest]
645    fn test_from_str_pre_epoch_rfc3339() {
646        let err = "1969-12-31T23:59:59Z".parse::<UnixNanos>().unwrap_err();
647        assert_eq!(err.to_string(), "Unix timestamp cannot be negative");
648    }
649
650    #[rstest]
651    fn test_try_from_datetime_valid() {
652        use chrono::TimeZone;
653        let datetime = Utc.timestamp_opt(1_000_000_000, 0).unwrap(); // 1 billion seconds since epoch
654        let nanos = UnixNanos::from(datetime);
655        assert_eq!(nanos.as_u64(), 1_000_000_000_000_000_000);
656    }
657
658    #[rstest]
659    fn test_eq() {
660        let nanos = UnixNanos::from(100);
661        assert_eq!(nanos, 100);
662        assert_eq!(nanos, Some(100));
663        assert_ne!(nanos, 200);
664        assert_ne!(nanos, Some(200));
665        assert_ne!(nanos, None);
666    }
667
668    #[rstest]
669    fn test_partial_cmp() {
670        let nanos = UnixNanos::from(100);
671        assert_eq!(nanos.partial_cmp(&100), Some(Ordering::Equal));
672        assert_eq!(nanos.partial_cmp(&200), Some(Ordering::Less));
673        assert_eq!(nanos.partial_cmp(&50), Some(Ordering::Greater));
674        assert_eq!(nanos.partial_cmp(&None), Some(Ordering::Greater));
675    }
676
677    #[rstest]
678    fn test_edge_case_max_value() {
679        let nanos = UnixNanos::from(u64::MAX);
680        assert_eq!(format!("{nanos}"), format!("{}", u64::MAX));
681    }
682
683    #[rstest]
684    fn test_display() {
685        let nanos = UnixNanos::from(123);
686        assert_eq!(format!("{nanos}"), "123");
687    }
688
689    #[rstest]
690    fn test_addition() {
691        let nanos1 = UnixNanos::from(100);
692        let nanos2 = UnixNanos::from(200);
693        let result = nanos1 + nanos2;
694        assert_eq!(result.as_u64(), 300);
695    }
696
697    #[rstest]
698    fn test_add_assign() {
699        let mut nanos = UnixNanos::from(100);
700        nanos += 50_u64;
701        assert_eq!(nanos.as_u64(), 150);
702    }
703
704    #[rstest]
705    fn test_subtraction() {
706        let nanos1 = UnixNanos::from(200);
707        let nanos2 = UnixNanos::from(100);
708        let result = nanos1 - nanos2;
709        assert_eq!(result.as_u64(), 100);
710    }
711
712    #[rstest]
713    fn test_sub_assign() {
714        let mut nanos = UnixNanos::from(200);
715        nanos -= 50_u64;
716        assert_eq!(nanos.as_u64(), 150);
717    }
718
719    #[rstest]
720    #[should_panic(expected = "UnixNanos overflow")]
721    fn test_overflow_add() {
722        let nanos = UnixNanos::from(u64::MAX);
723        let _ = nanos + UnixNanos::from(1); // This should panic due to overflow
724    }
725
726    #[rstest]
727    #[should_panic(expected = "UnixNanos overflow")]
728    fn test_overflow_add_u64() {
729        let nanos = UnixNanos::from(u64::MAX);
730        let _ = nanos + 1_u64; // This should panic due to overflow
731    }
732
733    #[rstest]
734    #[should_panic(expected = "UnixNanos underflow")]
735    fn test_overflow_sub() {
736        let _ = UnixNanos::default() - UnixNanos::from(1); // This should panic due to underflow
737    }
738
739    #[rstest]
740    #[should_panic(expected = "UnixNanos underflow")]
741    fn test_overflow_sub_u64() {
742        let _ = UnixNanos::default() - 1_u64; // This should panic due to underflow
743    }
744
745    #[rstest]
746    #[case(100, 50, Some(50))]
747    #[case(1_000_000_000, 500_000_000, Some(500_000_000))]
748    #[case(u64::MAX, u64::MAX - 1, Some(1))]
749    #[case(50, 50, Some(0))]
750    #[case(50, 100, None)]
751    #[case(0, 1, None)]
752    fn test_duration_since(
753        #[case] time1: u64,
754        #[case] time2: u64,
755        #[case] expected: Option<DurationNanos>,
756    ) {
757        let nanos1 = UnixNanos::from(time1);
758        let nanos2 = UnixNanos::from(time2);
759        assert_eq!(nanos1.duration_since(&nanos2), expected);
760    }
761
762    #[rstest]
763    fn test_duration_since_same_moment() {
764        let moment = UnixNanos::from(1_707_577_123_456_789_000);
765        assert_eq!(moment.duration_since(&moment), Some(0));
766    }
767
768    #[rstest]
769    fn test_duration_since_chronological() {
770        // Create a reference time (Feb 10, 2024)
771        let earlier = Utc.with_ymd_and_hms(2024, 2, 10, 12, 0, 0).unwrap();
772
773        // Create a time 1 hour, 30 minutes, and 45 seconds later (with nanoseconds)
774        let later = earlier
775            + Duration::hours(1)
776            + Duration::minutes(30)
777            + Duration::seconds(45)
778            + Duration::nanoseconds(500_000_000);
779
780        let earlier_nanos = UnixNanos::from(earlier);
781        let later_nanos = UnixNanos::from(later);
782
783        // Calculate expected duration in nanoseconds
784        let expected_duration = 60 * 60 * 1_000_000_000 + // 1 hour
785        30 * 60 * 1_000_000_000 + // 30 minutes
786        45 * 1_000_000_000 + // 45 seconds
787        500_000_000; // 500 million nanoseconds
788
789        assert_eq!(
790            later_nanos.duration_since(&earlier_nanos),
791            Some(expected_duration)
792        );
793        assert_eq!(earlier_nanos.duration_since(&later_nanos), None);
794    }
795
796    #[rstest]
797    fn test_duration_since_with_edge_cases() {
798        // Test with maximum value
799        let max = UnixNanos::from(u64::MAX);
800        let smaller = UnixNanos::from(u64::MAX - 1000);
801
802        assert_eq!(max.duration_since(&smaller), Some(1000));
803        assert_eq!(smaller.duration_since(&max), None);
804
805        // Test with minimum value
806        let min = UnixNanos::default(); // Zero timestamp
807        let larger = UnixNanos::from(1000);
808
809        assert_eq!(min.duration_since(&min), Some(0));
810        assert_eq!(larger.duration_since(&min), Some(1000));
811        assert_eq!(min.duration_since(&larger), None);
812    }
813
814    #[rstest]
815    fn test_serde_json() {
816        let nanos = UnixNanos::from(123);
817        let json = serde_json::to_string(&nanos).unwrap();
818        let deserialized: UnixNanos = serde_json::from_str(&json).unwrap();
819        assert_eq!(deserialized, nanos);
820    }
821
822    #[rstest]
823    fn test_serde_edge_cases() {
824        let nanos = UnixNanos::from(u64::MAX);
825        let json = serde_json::to_string(&nanos).unwrap();
826        let deserialized: UnixNanos = serde_json::from_str(&json).unwrap();
827        assert_eq!(deserialized, nanos);
828    }
829
830    #[rstest]
831    #[case("123", 123)] // Integer string
832    #[case("1234.567", 1_234_567_000_000)] // Float string (seconds to nanos)
833    #[case("2024-02-10", 1_707_523_200_000_000_000)] // Simple date (midnight UTC)
834    #[case("2024-02-10T14:58:43Z", 1_707_577_123_000_000_000)] // RFC3339 without fractions
835    #[case("2024-02-10T14:58:43.456789Z", 1_707_577_123_456_789_000)] // RFC3339 with fractions
836    fn test_from_str_formats(#[case] input: &str, #[case] expected: u64) {
837        let parsed: UnixNanos = input.parse().unwrap();
838        assert_eq!(parsed.as_u64(), expected);
839    }
840
841    #[rstest]
842    #[case("abc")] // Random string
843    #[case("not a timestamp")] // Non-timestamp string
844    #[case("2024-02-10 14:58:43")] // Space-separated format (not RFC3339)
845    fn test_from_str_invalid_formats(#[case] input: &str) {
846        let result = input.parse::<UnixNanos>();
847        assert!(result.is_err());
848    }
849
850    #[rstest]
851    fn test_from_str_integer_overflow() {
852        // One more digit than u64::MAX (20 digits) so definitely overflows
853        let input = "184467440737095516160";
854        let result = input.parse::<UnixNanos>();
855        assert!(result.is_err());
856    }
857
858    // ---------- checked / saturating arithmetic ----------
859
860    #[rstest]
861    fn test_checked_add_overflow_returns_none() {
862        let max = UnixNanos::from(u64::MAX);
863        assert_eq!(max.checked_add(1_u64), None);
864    }
865
866    #[rstest]
867    fn test_checked_sub_underflow_returns_none() {
868        let zero = UnixNanos::default();
869        assert_eq!(zero.checked_sub(1_u64), None);
870    }
871
872    #[rstest]
873    fn test_saturating_add_overflow() {
874        let max = UnixNanos::from(u64::MAX);
875        let result = max.saturating_add_ns(1_u64);
876        assert_eq!(result, UnixNanos::from(u64::MAX));
877    }
878
879    #[rstest]
880    fn test_saturating_sub_underflow() {
881        let zero = UnixNanos::default();
882        let result = zero.saturating_sub_ns(1_u64);
883        assert_eq!(result, UnixNanos::default());
884    }
885
886    #[rstest]
887    fn test_from_str_float_overflow() {
888        // Use scientific notation so we take the floating-point parsing path.
889        let input = "2e10"; // 20 billion seconds ~ 634 years (> u64::MAX nanoseconds)
890        let result = input.parse::<UnixNanos>();
891        assert!(result.is_err());
892    }
893
894    #[rstest]
895    fn test_deserialize_u64() {
896        let json = "123456789";
897        let deserialized: UnixNanos = serde_json::from_str(json).unwrap();
898        assert_eq!(deserialized.as_u64(), 123_456_789);
899    }
900
901    #[rstest]
902    fn test_deserialize_string_with_int() {
903        let json = "\"123456789\"";
904        let deserialized: UnixNanos = serde_json::from_str(json).unwrap();
905        assert_eq!(deserialized.as_u64(), 123_456_789);
906    }
907
908    #[rstest]
909    fn test_deserialize_float() {
910        let json = "1234.567";
911        let deserialized: UnixNanos = serde_json::from_str(json).unwrap();
912        assert_eq!(deserialized.as_u64(), 1_234_567_000_000);
913    }
914
915    #[rstest]
916    fn test_deserialize_string_with_float() {
917        let json = "\"1234.567\"";
918        let deserialized: UnixNanos = serde_json::from_str(json).unwrap();
919        assert_eq!(deserialized.as_u64(), 1_234_567_000_000);
920    }
921
922    #[rstest]
923    #[case("\"2024-02-10T14:58:43.456789Z\"", 1_707_577_123_456_789_000)]
924    #[case("\"2024-02-10T14:58:43Z\"", 1_707_577_123_000_000_000)]
925    fn test_deserialize_timestamp_strings(#[case] input: &str, #[case] expected: u64) {
926        let deserialized: UnixNanos = serde_json::from_str(input).unwrap();
927        assert_eq!(deserialized.as_u64(), expected);
928    }
929
930    #[rstest]
931    fn test_deserialize_negative_int_fails() {
932        let json = "-123456789";
933        let result: Result<UnixNanos, _> = serde_json::from_str(json);
934        assert!(result.is_err());
935    }
936
937    #[rstest]
938    fn test_deserialize_negative_float_fails() {
939        let json = "-1234.567";
940        let result: Result<UnixNanos, _> = serde_json::from_str(json);
941        assert!(result.is_err());
942    }
943
944    #[rstest]
945    fn test_deserialize_nan_fails() {
946        // JSON doesn't support NaN directly, test the internal deserializer
947        use serde::de::{
948            IntoDeserializer,
949            value::{Error as ValueError, F64Deserializer},
950        };
951        let deserializer: F64Deserializer<ValueError> = f64::NAN.into_deserializer();
952        let result: Result<UnixNanos, _> = UnixNanos::deserialize(deserializer);
953        assert!(result.is_err());
954        assert!(result.unwrap_err().to_string().contains("must be finite"));
955    }
956
957    #[rstest]
958    fn test_deserialize_infinity_fails() {
959        use serde::de::{
960            IntoDeserializer,
961            value::{Error as ValueError, F64Deserializer},
962        };
963        let deserializer: F64Deserializer<ValueError> = f64::INFINITY.into_deserializer();
964        let result: Result<UnixNanos, _> = UnixNanos::deserialize(deserializer);
965        assert!(result.is_err());
966        assert!(result.unwrap_err().to_string().contains("must be finite"));
967    }
968
969    #[rstest]
970    fn test_deserialize_negative_infinity_fails() {
971        use serde::de::{
972            IntoDeserializer,
973            value::{Error as ValueError, F64Deserializer},
974        };
975        let deserializer: F64Deserializer<ValueError> = f64::NEG_INFINITY.into_deserializer();
976        let result: Result<UnixNanos, _> = UnixNanos::deserialize(deserializer);
977        assert!(result.is_err());
978        assert!(result.unwrap_err().to_string().contains("must be finite"));
979    }
980
981    #[rstest]
982    fn test_deserialize_overflow_float_fails() {
983        // Test a float that would overflow u64 when converted to nanoseconds
984        // u64::MAX is ~18.4e18, so u64::MAX / 1e9 = ~18.4e9 seconds
985        let result: Result<UnixNanos, _> = serde_json::from_str("1e20");
986        assert!(result.is_err());
987        assert!(result.unwrap_err().to_string().contains("out of range"));
988    }
989
990    #[rstest]
991    fn test_deserialize_invalid_string_fails() {
992        let json = "\"not a timestamp\"";
993        let result: Result<UnixNanos, _> = serde_json::from_str(json);
994        assert!(result.is_err());
995    }
996
997    #[rstest]
998    fn test_deserialize_edge_cases() {
999        // Test zero
1000        let json = "0";
1001        let deserialized: UnixNanos = serde_json::from_str(json).unwrap();
1002        assert_eq!(deserialized.as_u64(), 0);
1003
1004        // Test large value
1005        let json = "18446744073709551615"; // u64::MAX
1006        let deserialized: UnixNanos = serde_json::from_str(json).unwrap();
1007        assert_eq!(deserialized.as_u64(), u64::MAX);
1008    }
1009
1010    #[rstest]
1011    #[should_panic(expected = "UnixNanos value exceeds i64::MAX")]
1012    fn test_as_i64_overflow_panics() {
1013        let nanos = UnixNanos::from(u64::MAX);
1014        let _ = nanos.as_i64(); // Should panic
1015    }
1016
1017    ////////////////////////////////////////////////////////////////////////////////
1018    // Property-based testing
1019    ////////////////////////////////////////////////////////////////////////////////
1020
1021    use proptest::prelude::*;
1022
1023    fn unix_nanos_strategy() -> impl Strategy<Value = UnixNanos> {
1024        prop_oneof![
1025            // Small values
1026            0u64..1_000_000u64,
1027            // Medium values (microseconds range)
1028            1_000_000u64..1_000_000_000_000u64,
1029            // Large values (nanoseconds since 1970, but safe for arithmetic)
1030            1_000_000_000_000u64..=i64::MAX as u64,
1031            // Edge cases
1032            Just(0u64),
1033            Just(1u64),
1034            Just(1_000_000_000u64),             // 1 second in nanos
1035            Just(1_000_000_000_000u64),         // ~2001 timestamp
1036            Just(1_700_000_000_000_000_000u64), // ~2023 timestamp
1037            Just((i64::MAX / 2) as u64),        // Safe for doubling
1038        ]
1039        .prop_map(UnixNanos::from)
1040    }
1041
1042    fn unix_nanos_pair_strategy() -> impl Strategy<Value = (UnixNanos, UnixNanos)> {
1043        (unix_nanos_strategy(), unix_nanos_strategy())
1044    }
1045
1046    proptest! {
1047        #[rstest]
1048        fn prop_unix_nanos_construction_roundtrip(value in 0u64..=i64::MAX as u64) {
1049            let nanos = UnixNanos::from(value);
1050            prop_assert_eq!(nanos.as_u64(), value);
1051            prop_assert_eq!(nanos.as_f64(), value as f64);
1052
1053            // Test i64 conversion only for values within i64 range
1054            if i64::try_from(value).is_ok() {
1055                prop_assert_eq!(nanos.as_i64(), value as i64);
1056            }
1057        }
1058
1059        #[rstest]
1060        fn prop_unix_nanos_addition_commutative(
1061            (nanos1, nanos2) in unix_nanos_pair_strategy()
1062        ) {
1063            // Addition should be commutative when no overflow occurs
1064            if let (Some(sum1), Some(sum2)) = (
1065                nanos1.checked_add(nanos2.as_u64()),
1066                nanos2.checked_add(nanos1.as_u64())
1067            ) {
1068                prop_assert_eq!(sum1, sum2, "Addition should be commutative");
1069            }
1070        }
1071
1072        #[rstest]
1073        fn prop_unix_nanos_addition_associative(
1074            nanos1 in unix_nanos_strategy(),
1075            nanos2 in unix_nanos_strategy(),
1076            nanos3 in unix_nanos_strategy(),
1077        ) {
1078            // Addition should be associative when no overflow occurs
1079            if let (Some(sum1), Some(sum2)) = (
1080                nanos1.as_u64().checked_add(nanos2.as_u64()),
1081                nanos2.as_u64().checked_add(nanos3.as_u64())
1082            )
1083                && let (Some(left), Some(right)) = (
1084                    sum1.checked_add(nanos3.as_u64()),
1085                    nanos1.as_u64().checked_add(sum2)
1086                ) {
1087                    let left_result = UnixNanos::from(left);
1088                    let right_result = UnixNanos::from(right);
1089                    prop_assert_eq!(left_result, right_result, "Addition should be associative");
1090                }
1091        }
1092
1093        #[rstest]
1094        fn prop_unix_nanos_subtraction_inverse(
1095            (nanos1, nanos2) in unix_nanos_pair_strategy()
1096        ) {
1097            // Subtraction should be the inverse of addition when no underflow occurs
1098            if let Some(sum) = nanos1.checked_add(nanos2.as_u64()) {
1099                let diff = sum - nanos2;
1100                prop_assert_eq!(diff, nanos1, "Subtraction should be inverse of addition");
1101            }
1102        }
1103
1104        #[rstest]
1105        fn prop_unix_nanos_zero_identity(nanos in unix_nanos_strategy()) {
1106            // Zero should be additive identity
1107            let zero = UnixNanos::default();
1108            prop_assert_eq!(nanos + zero, nanos, "Zero should be additive identity");
1109            prop_assert_eq!(zero + nanos, nanos, "Zero should be additive identity (commutative)");
1110            prop_assert!(zero.is_zero(), "Zero should be recognized as zero");
1111        }
1112
1113        #[rstest]
1114        fn prop_unix_nanos_ordering_consistency(
1115            (nanos1, nanos2) in unix_nanos_pair_strategy()
1116        ) {
1117            // Ordering operations should be consistent
1118            let eq = nanos1 == nanos2;
1119            let lt = nanos1 < nanos2;
1120            let gt = nanos1 > nanos2;
1121            let le = nanos1 <= nanos2;
1122            let ge = nanos1 >= nanos2;
1123
1124            // Exactly one of eq, lt, gt should be true
1125            let exclusive_count = [eq, lt, gt].iter().filter(|&&x| x).count();
1126            prop_assert_eq!(exclusive_count, 1, "Exactly one of ==, <, > should be true");
1127
1128            // Consistency checks
1129            prop_assert_eq!(le, eq || lt, "<= should equal == || <");
1130            prop_assert_eq!(ge, eq || gt, ">= should equal == || >");
1131            prop_assert_eq!(lt, nanos2 > nanos1, "< should be symmetric with >");
1132            prop_assert_eq!(le, nanos2 >= nanos1, "<= should be symmetric with >=");
1133        }
1134
1135        #[rstest]
1136        fn prop_unix_nanos_string_roundtrip(nanos in unix_nanos_strategy()) {
1137            // String serialization should round-trip correctly
1138            let string_repr = nanos.to_string();
1139            let parsed = UnixNanos::from_str(&string_repr);
1140            prop_assert!(parsed.is_ok(), "String parsing should succeed for valid UnixNanos");
1141            if let Ok(parsed_nanos) = parsed {
1142                prop_assert_eq!(parsed_nanos, nanos, "String should round-trip exactly");
1143            }
1144        }
1145
1146        #[rstest]
1147        fn prop_unix_nanos_datetime_conversion(nanos in unix_nanos_strategy()) {
1148            // DateTime conversion should be consistent (only test values within i64 range)
1149            if i64::try_from(nanos.as_u64()).is_ok() {
1150                let datetime = nanos.to_datetime_utc();
1151                let converted_back = UnixNanos::from(datetime);
1152                prop_assert_eq!(converted_back, nanos, "DateTime conversion should round-trip");
1153
1154                // RFC3339 string should also round-trip for valid dates
1155                let rfc3339 = nanos.to_rfc3339();
1156                if let Ok(parsed_from_rfc3339) = UnixNanos::from_str(&rfc3339) {
1157                    prop_assert_eq!(parsed_from_rfc3339, nanos, "RFC3339 string should round-trip");
1158                }
1159            }
1160        }
1161
1162        #[rstest]
1163        fn prop_unix_nanos_duration_since(
1164            (nanos1, nanos2) in unix_nanos_pair_strategy()
1165        ) {
1166            // duration_since should be consistent with comparison and arithmetic
1167            let duration = nanos1.duration_since(&nanos2);
1168
1169            if nanos1 >= nanos2 {
1170                // If nanos1 >= nanos2, duration should be Some and equal to difference
1171                prop_assert!(duration.is_some(), "Duration should be Some when first >= second");
1172                if let Some(dur) = duration {
1173                    prop_assert_eq!(dur, nanos1.as_u64() - nanos2.as_u64(),
1174                        "Duration should equal the difference");
1175                    prop_assert_eq!(nanos2 + dur, nanos1.as_u64(),
1176                        "second + duration should equal first");
1177                }
1178            } else {
1179                // If nanos1 < nanos2, duration should be None
1180                prop_assert!(duration.is_none(), "Duration should be None when first < second");
1181            }
1182        }
1183
1184        #[rstest]
1185        fn prop_unix_nanos_checked_arithmetic(
1186            (nanos1, nanos2) in unix_nanos_pair_strategy()
1187        ) {
1188            // Checked arithmetic should be consistent with regular arithmetic when no overflow/underflow
1189            let checked_add = nanos1.checked_add(nanos2.as_u64());
1190            let checked_sub = nanos1.checked_sub(nanos2.as_u64());
1191
1192            // If checked_add succeeds, regular addition should produce the same result
1193            if let Some(sum) = checked_add
1194                && nanos1.as_u64().checked_add(nanos2.as_u64()).is_some() {
1195                    prop_assert_eq!(sum, nanos1 + nanos2, "Checked add should match regular add when no overflow");
1196                }
1197
1198            // If checked_sub succeeds, regular subtraction should produce the same result
1199            if let Some(diff) = checked_sub
1200                && nanos1.as_u64() >= nanos2.as_u64() {
1201                    prop_assert_eq!(diff, nanos1 - nanos2, "Checked sub should match regular sub when no underflow");
1202                }
1203        }
1204
1205        #[rstest]
1206        fn prop_unix_nanos_saturating_arithmetic(
1207            (nanos1, nanos2) in unix_nanos_pair_strategy()
1208        ) {
1209            // Saturating arithmetic should never panic and produce reasonable results
1210            let sat_add = nanos1.saturating_add_ns(nanos2.as_u64());
1211            let sat_sub = nanos1.saturating_sub_ns(nanos2.as_u64());
1212
1213            // Saturating add should be >= both operands
1214            prop_assert!(sat_add >= nanos1, "Saturating add result should be >= first operand");
1215            prop_assert!(sat_add.as_u64() >= nanos2.as_u64(), "Saturating add result should be >= second operand");
1216
1217            // Saturating sub should be <= first operand
1218            prop_assert!(sat_sub <= nanos1, "Saturating sub result should be <= first operand");
1219
1220            // If no overflow/underflow would occur, saturating should match checked
1221            if let Some(checked_sum) = nanos1.checked_add(nanos2.as_u64()) {
1222                prop_assert_eq!(sat_add, checked_sum, "Saturating add should match checked add when no overflow");
1223            } else {
1224                prop_assert_eq!(sat_add, UnixNanos::from(u64::MAX), "Saturating add should be MAX on overflow");
1225            }
1226
1227            if let Some(checked_diff) = nanos1.checked_sub(nanos2.as_u64()) {
1228                prop_assert_eq!(sat_sub, checked_diff, "Saturating sub should match checked sub when no underflow");
1229            } else {
1230                prop_assert_eq!(sat_sub, UnixNanos::default(), "Saturating sub should be zero on underflow");
1231            }
1232        }
1233    }
1234}