rustflexstack/security/
time_service.rs1use std::time::{SystemTime, UNIX_EPOCH};
8
9pub const ITS_EPOCH: u64 = 1_072_915_200;
11
12pub const ITS_EPOCH_MS: u64 = ITS_EPOCH * 1_000;
14
15pub const ELAPSED_SECONDS: u64 = 5;
19
20pub const ELAPSED_MILLISECONDS: u64 = ELAPSED_SECONDS * 1_000;
22
23pub fn unix_ms_to_its_ms(unix_ms: u64) -> u64 {
26 (unix_ms + ELAPSED_MILLISECONDS).saturating_sub(ITS_EPOCH_MS)
27}
28
29pub fn unix_time_secs() -> f64 {
31 SystemTime::now()
32 .duration_since(UNIX_EPOCH)
33 .expect("system clock before Unix epoch")
34 .as_secs_f64()
35}
36
37pub fn time() -> f64 {
39 unix_time_secs()
40}
41
42pub fn timestamp_its_microseconds() -> u64 {
47 let now = SystemTime::now()
48 .duration_since(UNIX_EPOCH)
49 .expect("system clock before Unix epoch");
50 let its_secs = now.as_secs() - ITS_EPOCH + ELAPSED_SECONDS;
51 its_secs * 1_000_000 + u64::from(now.subsec_micros())
52}
53
54pub fn timestamp_its() -> u64 {
56 timestamp_its_microseconds() / 1_000
57}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62
63 #[test]
64 fn unix_time_secs_positive() {
65 let t = unix_time_secs();
66 assert!(t > ITS_EPOCH as f64);
68 }
69
70 #[test]
71 fn timestamp_its_microseconds_positive() {
72 let t = timestamp_its_microseconds();
73 assert!(t > 0);
74 }
75
76 #[test]
77 fn timestamp_its_microseconds_monotonic() {
78 let t1 = timestamp_its_microseconds();
79 std::thread::sleep(std::time::Duration::from_millis(1));
80 let t2 = timestamp_its_microseconds();
81 assert!(t2 > t1);
82 }
83
84 #[test]
85 fn its_epoch_constant() {
86 assert_eq!(ITS_EPOCH, 1_072_915_200);
87 }
88
89 #[test]
90 fn elapsed_seconds_constant() {
91 assert_eq!(ELAPSED_SECONDS, 5);
92 }
93}