Skip to main content

parley/utils/
time.rs

1//! Time utility functions for Parley.
2//!
3//! Provides shared timestamp utilities used across the codebase.
4
5use crate::utils::cast::u128_to_u64_saturating;
6use anyhow::{Context, Result};
7use std::time::{SystemTime, UNIX_EPOCH};
8
9/// Returns the current Unix timestamp in milliseconds.
10///
11/// # Errors
12/// Returns an error if the system clock is before the Unix epoch.
13pub fn now_ms() -> Result<u64> {
14    let elapsed = SystemTime::now()
15        .duration_since(UNIX_EPOCH)
16        .context("system clock is before unix epoch")?;
17    Ok(u128_to_u64_saturating(elapsed.as_millis()))
18}
19
20/// Returns the current Unix timestamp in milliseconds, or 0 if the clock is invalid.
21///
22/// This is a fallback variant that never fails, useful for UI rendering and logging.
23#[must_use]
24pub fn now_ms_utc() -> u64 {
25    SystemTime::now()
26        .duration_since(UNIX_EPOCH)
27        .map(|elapsed| u128_to_u64_saturating(elapsed.as_millis()))
28        .unwrap_or(0)
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34    use anyhow::Result;
35
36    #[test]
37    fn now_ms_returns_valid_timestamp() -> Result<()> {
38        let ts = now_ms()?;
39        assert!(ts > 0, "timestamp should be positive");
40        Ok(())
41    }
42
43    #[test]
44    fn now_ms_utc_returns_valid_timestamp() {
45        let ts = now_ms_utc();
46        assert!(ts > 0, "timestamp should be positive");
47    }
48
49    #[test]
50    fn now_ms_utc_never_fails() {
51        // This function should never panic even with invalid clock
52        let _ = now_ms_utc();
53    }
54}