1use std::ops::Add;
2use std::{
3 sync::RwLock,
4 time::{Duration, SystemTime},
5};
6
7pub trait Clock: Send + Sync {
8 fn now(&self) -> SystemTime;
9}
10
11pub struct SystemClock;
12
13impl Clock for SystemClock {
14 fn now(&self) -> SystemTime {
15 SystemTime::now()
16 }
17}
18
19#[derive(Debug)]
20pub struct MockClock {
21 now: RwLock<SystemTime>,
22}
23
24impl Clock for MockClock {
25 fn now(&self) -> SystemTime {
26 *self.now.read().unwrap()
27 }
28}
29
30impl Default for MockClock {
31 fn default() -> Self {
32 Self::new()
33 }
34}
35
36impl MockClock {
37 pub fn with_time(time: SystemTime) -> Self {
38 Self {
39 now: RwLock::new(time),
40 }
41 }
42
43 pub fn new() -> Self {
44 Self::with_time(SystemTime::now())
45 }
46
47 pub fn advance(&self, duration: Duration) {
48 let mut now = self.now.write().unwrap();
49 *now = now.add(duration);
50 }
51
52 pub fn set_time(&self, time: SystemTime) {
53 *self.now.write().unwrap() = time;
54 }
55}