Skip to main content

reddb_server/utils/
time.rs

1//! Time helpers used across the engine. Centralised so the same
2//! `SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default()`
3//! incantation doesn't get re-typed at 20+ call sites.
4
5use std::time::{SystemTime, UNIX_EPOCH};
6
7/// Current wall-clock unix milliseconds. `0` if the system clock is
8/// before the epoch (impossible on real hardware, but the API
9/// returns a `Result` so we degrade gracefully instead of panicking).
10#[inline]
11pub fn now_unix_millis() -> u64 {
12    SystemTime::now()
13        .duration_since(UNIX_EPOCH)
14        .map(|d| d.as_millis() as u64)
15        .unwrap_or(0)
16}
17
18/// Current wall-clock unix nanoseconds.
19#[inline]
20pub fn now_unix_nanos() -> u128 {
21    SystemTime::now()
22        .duration_since(UNIX_EPOCH)
23        .map(|d| d.as_nanos())
24        .unwrap_or(0)
25}
26
27/// Current wall-clock unix seconds.
28#[inline]
29pub fn now_unix_secs() -> u64 {
30    SystemTime::now()
31        .duration_since(UNIX_EPOCH)
32        .map(|d| d.as_secs())
33        .unwrap_or(0)
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn now_returns_positive_values() {
42        let ms = now_unix_millis();
43        let ns = now_unix_nanos();
44        let s = now_unix_secs();
45        assert!(ms > 1_700_000_000_000, "ms must be after 2023");
46        assert!(ns > 1_700_000_000_000_000_000, "ns must be after 2023");
47        assert!(s > 1_700_000_000, "s must be after 2023");
48    }
49}