atomic_instant/
lib.rs

1use std::{sync::atomic::{AtomicU64, Ordering}, time::Duration};
2use quanta::Instant;
3
4#[derive(Default, Debug)]
5pub struct AtomicInstant(AtomicU64);
6
7impl AtomicInstant {
8    pub const fn empty() -> Self {
9        Self(AtomicU64::new(0))
10    }
11    
12    pub fn now() -> Self {
13        Self(AtomicU64::new(Instant::now().as_unix_duration().as_millis() as u64))
14    }
15
16    pub const fn from_millis(millis: u64) -> Self {
17        Self(AtomicU64::new(millis))
18    }
19
20    pub fn elapsed(&self) -> Duration {
21        Duration::from_millis(Instant::now().as_unix_duration().as_millis() as u64 - self.0.load(Ordering::SeqCst))
22    }
23
24    pub fn as_millis(&self) -> u64 {
25        self.0.load(Ordering::SeqCst)
26    }
27
28    pub fn set_now(&self) {
29        self.0.store(Instant::now().as_unix_duration().as_millis() as u64, Ordering::SeqCst);
30    }
31
32    pub fn set_millis(&self, millis: u64) {
33        self.0.store(millis, Ordering::SeqCst);
34    }
35
36    pub fn is_empty(&self) -> bool {
37        self.as_millis() == 0
38    }
39}