1use std::sync::Arc;
9use std::sync::OnceLock;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::time::{Duration, Instant};
12
13#[cfg(test)]
14mod tests;
15
16const NEVER: u64 = u64::MAX;
18
19#[derive(Debug, Clone)]
21pub struct Beat {
22 last: Arc<AtomicU64>,
24}
25
26impl Default for Beat {
27 fn default() -> Self {
28 origin();
30 Self {
31 last: Arc::new(AtomicU64::new(NEVER)),
32 }
33 }
34}
35
36fn origin() -> Instant {
38 static ORIGIN: OnceLock<Instant> = OnceLock::new();
39 *ORIGIN.get_or_init(Instant::now)
40}
41
42fn millis(at: Instant) -> u64 {
43 u64::try_from(at.saturating_duration_since(origin()).as_millis()).unwrap_or(NEVER - 1)
44}
45
46impl Beat {
47 pub fn beat(&self) {
49 self.beat_at(Instant::now());
50 }
51
52 pub fn beat_at(&self, at: Instant) {
54 self.last.store(millis(at), Ordering::Relaxed);
55 }
56
57 #[must_use]
59 pub fn since(&self, now: Instant) -> Option<Duration> {
60 let last = self.last.load(Ordering::Relaxed);
61 (last != NEVER).then(|| Duration::from_millis(millis(now).saturating_sub(last)))
62 }
63}