qubit_clock/lib.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10//! Thread-safe clock abstractions for Rust.
11//!
12//! This crate provides a flexible and type-safe clock abstraction system with
13//! support for:
14//!
15//! - **Basic time access**: Get current UTC time
16//! - **High precision**: Nanosecond-level time measurements
17//! - **Timezone support**: Convert to local time in any timezone
18//! - **Monotonic time**: Time that never goes backwards
19//! - **Testing support**: Shared mock timelines for clocks and sleepers
20//! - **Mockable sleeps**: Relative sleep abstractions with real and mock implementations
21//!
22//! # Architecture
23//!
24//! The crate is built around several orthogonal traits:
25//!
26//! - [`Clock`]: Base trait providing UTC time
27//! - [`NanoClock`]: Extension for nanosecond precision
28//! - [`ZonedClock`]: Extension for timezone support
29//! - [`ControllableClock`]: Extension for time control (testing)
30//! - [`sleep::Sleeper`]: Relative blocking sleep abstraction
31//! - `sleep::AsyncSleeper`: Tokio async relative sleep abstraction enabled by
32//! the `tokio` feature
33//! - [`MockTimeline`]: Shared monotonic mock time source for deterministic tests
34//!
35//! # Implementations
36//!
37//! Several clock implementations are provided:
38//!
39//! - [`SystemClock`]: Uses system wall clock time
40//! - [`MonotonicClock`]: Monotonic time (unaffected by system time changes)
41//! - [`NanoMonotonicClock`]: Monotonic time with nanosecond precision
42//! - [`MockClock`]: UTC and nanosecond clock backed by a mock timeline
43//! - [`MockTime`]: Convenience facade bundling one timeline, clock, and sleeper
44//! - [`Zoned<C>`](Zoned): Wrapper that adds timezone support to any clock
45//! - [`sleep::SystemSleeper`]: Real relative sleeper, with async support when
46//! the `tokio` feature is enabled
47//! - [`sleep::MockSleeper`]: Timeline-backed relative sleeper for tests,
48//! with async support when the `tokio` feature is enabled
49//!
50//! # Examples
51//!
52//! ## Basic Usage
53//!
54//! ```
55//! use qubit_clock::{Clock, SystemClock};
56//!
57//! let clock = SystemClock::new();
58//! let timestamp = clock.millis();
59//! let time = clock.time();
60//! println!("Current time: {}", time);
61//! ```
62//!
63//! ## With Timezone
64//!
65//! ```
66//! use qubit_clock::{Clock, ZonedClock, SystemClock, Zoned};
67//! use chrono_tz::Asia::Shanghai;
68//!
69//! let clock = Zoned::new(SystemClock::new(), Shanghai);
70//! let local = clock.local_time();
71//! println!("Local time in Shanghai: {}", local);
72//! ```
73//!
74//! ## Monotonic Time for Performance Measurement
75//!
76//! ```
77//! use qubit_clock::{Clock, MonotonicClock};
78//! use std::thread;
79//! use std::time::Duration;
80//!
81//! let clock = MonotonicClock::new();
82//! let start = clock.millis();
83//!
84//! thread::sleep(Duration::from_millis(100));
85//!
86//! let elapsed = clock.millis() - start;
87//! println!("Elapsed: {} ms", elapsed);
88//! ```
89//!
90//! ## Testing with MockClock
91//!
92//! ```
93//! use qubit_clock::{Clock, ControllableClock, MockClock};
94//! use chrono::{DateTime, Duration, Utc};
95//!
96//! let clock = MockClock::new();
97//!
98//! // Set to a specific time
99//! let fixed_time = DateTime::parse_from_rfc3339(
100//! "2024-01-01T00:00:00Z"
101//! ).unwrap().with_timezone(&Utc);
102//! clock.set_time(fixed_time);
103//!
104//! assert_eq!(clock.time(), fixed_time);
105//!
106//! // Advance time
107//! clock.add_duration(Duration::hours(1));
108//! assert_eq!(clock.time(), fixed_time + Duration::hours(1));
109//! ```
110//!
111//! ## High-Precision Measurements
112//!
113//! ```
114//! use qubit_clock::{NanoClock, NanoMonotonicClock};
115//!
116//! let clock = NanoMonotonicClock::new();
117//! let start = clock.nanos();
118//!
119//! // Perform some operation
120//! for _ in 0..1000 {
121//! // Some work
122//! }
123//!
124//! let elapsed = clock.nanos() - start;
125//! println!("Elapsed: {} ns", elapsed);
126//! ```
127//!
128//! ## Time Meters for Elapsed Time Measurement
129//!
130//! ```
131//! use qubit_clock::meter::TimeMeter;
132//! use std::thread;
133//! use std::time::Duration;
134//!
135//! let mut meter = TimeMeter::new();
136//! meter.start();
137//! thread::sleep(Duration::from_millis(100));
138//! meter.stop();
139//! println!("Elapsed: {}", meter.readable_duration());
140//! ```
141//!
142//! # Design Principles
143//!
144//! - **Interface Segregation**: Don't force implementations to provide
145//! features they don't need
146//! - **Single Responsibility**: Each trait and type has one clear purpose
147//! - **Composition over Inheritance**: Extend functionality through wrappers
148//! - **Zero-Cost Abstractions**: Pay only for what you use
149//!
150
151// Re-export chrono types for convenience
152pub use chrono::{
153 DateTime,
154 Duration,
155 Utc,
156};
157pub use chrono_tz::Tz;
158
159// Clock traits and implementations
160pub mod clock;
161
162pub use clock::{
163 Clock,
164 ControllableClock,
165 MonotonicClock,
166 NanoClock,
167 NanoMonotonicClock,
168 SystemClock,
169 Zoned,
170 ZonedClock,
171};
172
173// Unified mock time runtime
174pub mod mock;
175
176pub use mock::{
177 MockClock,
178 MockInstant,
179 MockTime,
180 MockTimeError,
181 MockTimeline,
182 MockWaiterKind,
183};
184
185// Time meters
186pub mod meter;
187
188// Relative sleep abstractions
189pub mod sleep;