prism3_clock/clock.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025.
4 * 3-Prism Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! The base clock trait providing UTC time.
10//!
11//! This module defines the [`Clock`] trait, which is the foundation of the
12//! clock abstraction. All clock implementations must implement this trait.
13//!
14//! # Author
15//!
16//! Haixing Hu
17
18use chrono::{DateTime, Utc};
19
20/// A trait representing a clock that provides UTC time.
21///
22/// This is the base trait for all clock implementations. It provides methods
23/// to get the current time as a Unix timestamp (milliseconds) or as a
24/// `DateTime<Utc>` object.
25///
26/// All methods return **UTC time** only. For timezone support, see
27/// [`ZonedClock`](crate::ZonedClock).
28///
29/// # Thread Safety
30///
31/// All implementations must be `Send + Sync` to ensure thread safety.
32///
33/// # Examples
34///
35/// ```
36/// use prism3_clock::{Clock, SystemClock};
37///
38/// let clock = SystemClock::new();
39/// let timestamp = clock.millis();
40/// let time = clock.time();
41/// println!("Current time: {}", time);
42/// ```
43///
44/// # Author
45///
46/// Haixing Hu
47pub trait Clock: Send + Sync {
48 /// Returns the current time as a Unix timestamp in milliseconds (UTC).
49 ///
50 /// The timestamp represents the number of milliseconds since the Unix
51 /// epoch (1970-01-01 00:00:00 UTC).
52 ///
53 /// # Returns
54 ///
55 /// The current time as milliseconds since the Unix epoch.
56 ///
57 /// # Examples
58 ///
59 /// ```
60 /// use prism3_clock::{Clock, SystemClock};
61 ///
62 /// let clock = SystemClock::new();
63 /// let millis = clock.millis();
64 /// assert!(millis > 0);
65 /// ```
66 fn millis(&self) -> i64;
67
68 /// Returns the current time as a `DateTime<Utc>`.
69 ///
70 /// This method has a default implementation that constructs a
71 /// `DateTime<Utc>` from the result of [`millis()`](Clock::millis).
72 ///
73 /// # Returns
74 ///
75 /// The current time as a `DateTime<Utc>` object.
76 ///
77 /// # Examples
78 ///
79 /// ```
80 /// use prism3_clock::{Clock, SystemClock};
81 ///
82 /// let clock = SystemClock::new();
83 /// let time = clock.time();
84 /// println!("Current time: {}", time);
85 /// ```
86 fn time(&self) -> DateTime<Utc> {
87 DateTime::from_timestamp_millis(self.millis()).unwrap_or_else(Utc::now)
88 }
89}