rusty_ems/utils/
time.rs

1//! Time and timestamp utilities shared across exchange implementations
2
3use std::time::{SystemTime, UNIX_EPOCH};
4
5/// Get current timestamp in milliseconds since UNIX epoch
6#[inline]
7#[must_use]
8pub fn timestamp_millis() -> u64 {
9    SystemTime::now()
10        .duration_since(UNIX_EPOCH)
11        .expect("System time before UNIX epoch")
12        .as_millis() as u64
13}
14
15/// Get current timestamp in nanoseconds since UNIX epoch
16#[inline]
17#[must_use]
18pub fn timestamp_nanos() -> u64 {
19    SystemTime::now()
20        .duration_since(UNIX_EPOCH)
21        .expect("System time before UNIX epoch")
22        .as_nanos() as u64
23}
24
25/// Get current timestamp in seconds since UNIX epoch
26#[inline]
27#[must_use]
28pub fn timestamp_secs() -> u64 {
29    SystemTime::now()
30        .duration_since(UNIX_EPOCH)
31        .expect("System time before UNIX epoch")
32        .as_secs()
33}
34
35/// Get current timestamp in microseconds since UNIX epoch
36#[inline]
37#[must_use]
38pub fn timestamp_micros() -> u64 {
39    SystemTime::now()
40        .duration_since(UNIX_EPOCH)
41        .expect("System time before UNIX epoch")
42        .as_micros() as u64
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn test_timestamp_millis() {
51        let ts1 = timestamp_millis();
52        std::thread::sleep(std::time::Duration::from_millis(10));
53        let ts2 = timestamp_millis();
54        assert!(ts2 > ts1);
55        assert!(ts2 - ts1 >= 10);
56    }
57
58    #[test]
59    fn test_timestamp_nanos() {
60        let ts1 = timestamp_nanos();
61        let ts2 = timestamp_nanos();
62        assert!(ts2 >= ts1);
63    }
64
65    #[test]
66    fn test_timestamp_secs() {
67        let ts = timestamp_secs();
68        assert!(ts > 1_600_000_000); // After year 2020
69    }
70
71    #[test]
72    fn test_timestamp_micros() {
73        let ts1 = timestamp_micros();
74        std::thread::sleep(std::time::Duration::from_micros(100));
75        let ts2 = timestamp_micros();
76        assert!(ts2 > ts1);
77    }
78}