time_source/lib.rs
1//! Time source abstraction for obtaining the current time in milliseconds.
2//!
3//! This module defines a `TimeSource` trait and two implementations:
4//! - [`SystemTimeSource`]: system-clock based implementation
5//! - [`MockedTimeSource`]: mock implementation for testing purposes
6//!
7//! # Example
8//!
9//! ```
10//! use time_source::*;
11//! let system_time = SystemTimeSource;
12//! let now = system_time.get_current_time_millis();
13//! println!("Current time: {now} ms since epoch");
14//! ```
15
16use std::time::SystemTime;
17
18/// A trait representing a source of time that can provide the current time in milliseconds.
19pub trait TimeSource {
20 /// Returns the current time in milliseconds since Unix epoch.
21 fn get_current_time_millis(&self) -> u64;
22}
23
24/// A system clock based time source
25pub struct SystemTimeSource;
26
27impl TimeSource for SystemTimeSource {
28 fn get_current_time_millis(&self) -> u64 {
29 u64::try_from(
30 SystemTime::now()
31 .duration_since(SystemTime::UNIX_EPOCH)
32 .expect("Current time is always after unix epoch; qed")
33 .as_millis(),
34 )
35 .expect("Current time in millis should fit in 64 bits")
36 }
37}
38
39#[cfg(feature = "mock")]
40/// A mock implementation of `TimeSource` for testing purposes.
41pub struct MockedTimeSource {
42 /// The mocked current time in milliseconds since Unix epoch
43 ///
44 /// This value will be returned on all `get_current_time_millis` calls
45 pub current_time_millis: u64,
46}
47#[cfg(feature = "mock")]
48impl TimeSource for MockedTimeSource {
49 fn get_current_time_millis(&self) -> u64 {
50 self.current_time_millis
51 }
52}