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
mod test_faketime;
mod test_realtime;
#[cfg(feature = "enable_faketime")]
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
#[cfg(feature = "enable_faketime")]
static FAKETIME: AtomicU64 = AtomicU64::new(0);
#[cfg(feature = "enable_faketime")]
static FAKETIME_ENABLED: AtomicBool = AtomicBool::new(false);
fn system_time_as_millis() -> u64 {
let duration = std::time::SystemTime::now()
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.expect("SystemTime before UNIX EPOCH!");
duration.as_secs() * 1000 + u64::from(duration.subsec_millis())
}
#[cfg(not(feature = "enable_faketime"))]
pub fn unix_time_as_millis() -> u64 {
system_time_as_millis()
}
#[cfg(feature = "enable_faketime")]
pub fn faketime() -> FaketimeGuard {
FaketimeGuard {}
}
#[cfg(feature = "enable_faketime")]
pub fn unix_time_as_millis() -> u64 {
if FAKETIME_ENABLED.load(Ordering::SeqCst) {
return FAKETIME.load(Ordering::SeqCst);
}
system_time_as_millis()
}
pub fn unix_time() -> Duration {
Duration::from_millis(unix_time_as_millis())
}
#[cfg(feature = "enable_faketime")]
pub struct FaketimeGuard {}
#[cfg(feature = "enable_faketime")]
impl FaketimeGuard {
#[cfg(feature = "enable_faketime")]
pub fn set_faketime(&self, time: u64) {
FAKETIME.store(time, Ordering::Relaxed);
FAKETIME_ENABLED.store(true, Ordering::SeqCst);
}
#[cfg(feature = "enable_faketime")]
pub fn disable_faketime(&self) {
FAKETIME_ENABLED.store(false, Ordering::Relaxed);
}
}
#[cfg(feature = "enable_faketime")]
impl Drop for FaketimeGuard {
fn drop(&mut self) {
self.disable_faketime()
}
}