prism3_clock/
nano_clock.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025.
4 *    3-Prism Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! High-precision clock trait providing nanosecond accuracy.
10//!
11//! This module defines the [`NanoClock`] trait, which extends [`Clock`] to
12//! provide nanosecond-precision time measurements.
13//!
14//! # Author
15//!
16//! Haixing Hu
17
18use crate::Clock;
19use chrono::{DateTime, Utc};
20
21/// A trait representing a clock with nanosecond precision.
22///
23/// This trait extends [`Clock`] to provide high-precision time measurements
24/// at the nanosecond level. It's useful for performance testing,
25/// microbenchmarking, and scenarios requiring very precise time measurements.
26///
27/// # Note
28///
29/// The nanosecond timestamp is stored as an `i128` to avoid overflow issues.
30///
31/// # Examples
32///
33/// ```
34/// use prism3_clock::{NanoClock, NanoMonotonicClock};
35///
36/// let clock = NanoMonotonicClock::new();
37/// let start = clock.nanos();
38///
39/// // Perform some operation
40/// for _ in 0..1000 {
41///     // Some work
42/// }
43///
44/// let elapsed = clock.nanos() - start;
45/// println!("Elapsed: {} ns", elapsed);
46/// ```
47///
48/// # Author
49///
50/// Haixing Hu
51pub trait NanoClock: Clock {
52    /// Returns the current time as a Unix timestamp in nanoseconds (UTC).
53    ///
54    /// The timestamp represents the number of nanoseconds since the Unix
55    /// epoch (1970-01-01 00:00:00 UTC).
56    ///
57    /// # Returns
58    ///
59    /// The current time as nanoseconds since the Unix epoch.
60    ///
61    /// # Examples
62    ///
63    /// ```
64    /// use prism3_clock::{NanoClock, NanoMonotonicClock};
65    ///
66    /// let clock = NanoMonotonicClock::new();
67    /// let nanos = clock.nanos();
68    /// assert!(nanos > 0);
69    /// ```
70    fn nanos(&self) -> i128;
71
72    /// Returns the current time as a `DateTime<Utc>` with nanosecond
73    /// precision.
74    ///
75    /// This method has a default implementation that constructs a
76    /// `DateTime<Utc>` from the result of [`nanos()`](NanoClock::nanos).
77    ///
78    /// # Returns
79    ///
80    /// The current time as a `DateTime<Utc>` object with nanosecond
81    /// precision.
82    ///
83    /// # Examples
84    ///
85    /// ```
86    /// use prism3_clock::{NanoClock, NanoMonotonicClock};
87    ///
88    /// let clock = NanoMonotonicClock::new();
89    /// let time = clock.time_precise();
90    /// println!("Current time (precise): {}", time);
91    /// ```
92    fn time_precise(&self) -> DateTime<Utc> {
93        let nanos = self.nanos();
94        let secs = (nanos / 1_000_000_000) as i64;
95        let nsecs = (nanos % 1_000_000_000) as u32;
96        DateTime::from_timestamp(secs, nsecs).unwrap_or_else(Utc::now)
97    }
98}