1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
use core::sync::atomic::{AtomicUsize, Ordering};
pub trait Clock: Sync {
fn now(&self) -> u64;
}
pub struct MockClock {
now: core::sync::atomic::AtomicUsize,
}
impl core::fmt::Debug for MockClock {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
let now = self.now();
f.debug_struct("MockClock").field("now", &now).finish()
}
}
impl MockClock {
pub const fn new() -> MockClock {
MockClock {
now: AtomicUsize::new(0),
}
}
pub fn set_time(&self, timestamp: u64) {
if timestamp > (core::usize::MAX as u64) {
panic!("timestamps bigger than usize::MAX are not supported")
}
let to_set = timestamp as usize;
self.now.store(to_set, Ordering::Release);
}
}
impl Clock for MockClock {
fn now(&self) -> u64 {
self.now.load(Ordering::Relaxed) as u64
}
}
#[cfg(feature = "std")]
mod if_std {
use super::*;
use std::time::Instant;
pub struct StdClock {
start: Instant,
}
impl core::fmt::Debug for StdClock {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("StdClock").finish()
}
}
impl StdClock {
pub fn new() -> StdClock {
StdClock {
start: Instant::now(),
}
}
}
impl Clock for StdClock {
fn now(&self) -> u64 {
let elapsed = Instant::now() - self.start;
elapsed.as_millis() as u64
}
}
}
#[cfg(feature = "std")]
pub use self::if_std::*;