Skip to main content

rialo_s_time_utils/
lib.rs

1//! `std::time` utility functions.
2use std::{
3    sync::atomic::{AtomicU64, Ordering},
4    time::{Duration, SystemTime, UNIX_EPOCH},
5};
6
7#[deprecated(since = "2.1.0", note = "Use `Duration::as_nanos()` directly")]
8pub fn duration_as_ns(d: &Duration) -> u64 {
9    d.as_nanos() as u64
10}
11
12#[deprecated(since = "2.1.0", note = "Use `Duration::as_micros()` directly")]
13pub fn duration_as_us(d: &Duration) -> u64 {
14    d.as_micros() as u64
15}
16
17#[deprecated(since = "2.1.0", note = "Use `Duration::as_millis()` directly")]
18pub fn duration_as_ms(d: &Duration) -> u64 {
19    d.as_millis() as u64
20}
21
22#[deprecated(since = "2.1.0", note = "Use `Duration::as_secs_f32()` directly")]
23pub fn duration_as_s(d: &Duration) -> f32 {
24    d.as_secs_f32()
25}
26
27/// return timestamp as ms
28pub fn timestamp() -> u64 {
29    SystemTime::now()
30        .duration_since(UNIX_EPOCH)
31        .expect("create timestamp in timing")
32        .as_millis() as u64
33}
34
35pub const SECONDS_PER_YEAR: f64 = 365.242_199 * 24.0 * 60.0 * 60.0;
36
37/// From slots per year to slot duration
38pub fn slot_duration_from_slots_per_year(slots_per_year: f64) -> Duration {
39    // Recently, rust changed from infinity as usize being zero to 2^64-1; ensure it's zero here
40    let slot_in_ns = if slots_per_year != 0.0 {
41        (SECONDS_PER_YEAR * 1_000_000_000.0) / slots_per_year
42    } else {
43        0.0
44    };
45    Duration::from_nanos(slot_in_ns as u64)
46}
47
48#[derive(Debug, Default)]
49pub struct AtomicInterval {
50    last_update: AtomicU64,
51}
52
53impl AtomicInterval {
54    /// true if 'interval_time_ms' has elapsed since last time we returned true as long as it has been 'interval_time_ms' since this struct was created
55    #[inline(always)]
56    pub fn should_update(&self, interval_time_ms: u64) -> bool {
57        self.should_update_ext(interval_time_ms, true)
58    }
59
60    /// a primary use case is periodic metric reporting, potentially from different threads
61    /// true if 'interval_time_ms' has elapsed since last time we returned true
62    /// except, if skip_first=false, false until 'interval_time_ms' has elapsed since this struct was created
63    #[inline(always)]
64    pub fn should_update_ext(&self, interval_time_ms: u64, skip_first: bool) -> bool {
65        let now = timestamp();
66        let last = self.last_update.load(Ordering::Relaxed);
67        now.saturating_sub(last) > interval_time_ms
68            && self
69                .last_update
70                .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
71                == Ok(last)
72            && !(skip_first && last == 0)
73    }
74
75    /// return ms elapsed since the last time the time was set
76    pub fn elapsed_ms(&self) -> u64 {
77        let now = timestamp();
78        let last = self.last_update.load(Ordering::Relaxed);
79        now.saturating_sub(last) // wrapping somehow?
80    }
81
82    /// return ms until the interval_time will have elapsed
83    pub fn remaining_until_next_interval(&self, interval_time: u64) -> u64 {
84        interval_time.saturating_sub(self.elapsed_ms())
85    }
86}
87
88#[cfg(test)]
89mod test {
90    use super::*;
91
92    #[test]
93    fn test_interval_update() {
94        let i = AtomicInterval::default();
95        assert!(!i.should_update(1000));
96
97        let i = AtomicInterval::default();
98        assert!(i.should_update_ext(1000, false));
99
100        std::thread::sleep(Duration::from_millis(10));
101        assert!(i.elapsed_ms() > 9 && i.elapsed_ms() < 1000);
102        assert!(
103            i.remaining_until_next_interval(1000) > 9
104                && i.remaining_until_next_interval(1000) < 991
105        );
106        assert!(i.should_update(9));
107        assert!(!i.should_update(100));
108    }
109
110    #[test]
111    fn test_slot_duration_from_slots_per_year() {
112        let slots_per_year = 1_262_277_039.0;
113        let ticks_per_slot = 4;
114
115        assert_eq!(
116            slot_duration_from_slots_per_year(slots_per_year),
117            Duration::from_micros(1000 * 1000 / 160) * ticks_per_slot
118        );
119        assert_eq!(
120            slot_duration_from_slots_per_year(0.0),
121            Duration::from_micros(0) * ticks_per_slot
122        );
123
124        let slots_per_year = SECONDS_PER_YEAR;
125        let ticks_per_slot = 1;
126        assert_eq!(
127            slot_duration_from_slots_per_year(slots_per_year),
128            Duration::from_millis(1000) * ticks_per_slot
129        );
130    }
131}