symqtt 0.1.1

Synchronous MQTT 3.1.1/5.0 client — blocking API, no async runtime
Documentation
//! Process-level relative timestamps for lock-free timing.
//!
//! A lazily-initialized epoch provides the reference point. All timestamps
//! are millisecond offsets from that epoch, fitting in a `u64` / `AtomicU64`.

use std::sync::OnceLock;
use std::time::Instant;

static EPOCH: OnceLock<Instant> = OnceLock::new();

fn epoch() -> &'static Instant {
    EPOCH.get_or_init(Instant::now)
}

/// Returns the current relative timestamp in milliseconds since process epoch.
#[inline]
pub fn now_ms() -> u64 {
    epoch().elapsed().as_millis() as u64
}

#[cfg(test)]
mod tests {
    use std::thread;
    use std::time::Duration;

    use super::*;

    fn elapsed_ms(since: u64) -> u64 {
        now_ms().saturating_sub(since)
    }

    #[test]
    fn now_ms_returns_non_zero_after_small_delay() {
        // Ensure epoch is initialized
        let _ = now_ms();
        thread::sleep(Duration::from_millis(5));
        assert!(now_ms() >= 5);
    }

    #[test]
    fn now_ms_is_monotonically_increasing() {
        let t1 = now_ms();
        thread::sleep(Duration::from_millis(2));
        let t2 = now_ms();
        assert!(t2 >= t1);
    }

    #[test]
    fn elapsed_ms_measures_duration() {
        let start = now_ms();
        thread::sleep(Duration::from_millis(10));
        let elapsed = elapsed_ms(start);
        assert!(elapsed >= 10);
    }

    #[test]
    fn elapsed_ms_saturates_on_future_timestamp() {
        // A timestamp far in the "future" should yield 0 via saturating_sub
        let future = now_ms() + 999_999;
        assert_eq!(elapsed_ms(future), 0);
    }
}