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
use std::fmt;
use std::ops::Deref;
use std::sync::Arc;
use std::time::SystemTime;
use lazy_static::lazy_static;
#[cfg(feature = "chrono")]
use chrono::{DateTime, TimeZone, Utc};
pub type EpochMillis = u64;
#[cfg(feature = "chrono")]
pub fn to_datetime(millis: EpochMillis) -> DateTime<Utc> {
let dur = std::time::Duration::from_millis(millis);
Utc.timestamp(dur.as_secs() as i64, dur.subsec_nanos())
}
#[derive(Clone)]
pub struct NowFn(Arc<dyn Fn() -> EpochMillis + Send + Sync>);
impl fmt::Debug for NowFn {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("<now_fn>")
}
}
impl Deref for NowFn {
type Target = dyn Fn() -> EpochMillis;
fn deref(&self) -> &Self::Target {
&(*self.0)
}
}
impl<F> From<F> for NowFn
where
F: Fn() -> EpochMillis + Send + Sync + 'static,
{
fn from(f: F) -> NowFn {
NowFn(Arc::new(f))
}
}
fn system_time() -> EpochMillis {
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("failed to get millis since epoch")
.as_millis()
.try_into()
.expect("current time did not fit into u64")
}
fn now_zero() -> EpochMillis {
0
}
lazy_static! {
pub static ref SYSTEM_TIME: NowFn = NowFn::from(system_time);
pub static ref NOW_ZERO: NowFn = NowFn::from(now_zero);
}