elfo_utils/
lib.rs

1//! A collection of utilities to share among elfo-* crates.
2
3pub use self::{
4    likely::*,
5    rate_limiter::{RateLimit, RateLimiter},
6};
7
8mod likely;
9mod rate_limiter;
10pub mod time;
11
12pub use crossbeam_utils::CachePadded;
13
14/// Returns the contents of a `Option<T>`'s `Some(T)`, otherwise it returns
15/// early from the function. Can alternatively have an `else` branch, or an
16/// alternative "early return" statement, like `break` or `continue` for loops.
17#[macro_export]
18macro_rules! ward {
19    ($o:expr) => {
20        // Do not reuse `ward!` here, because it confuses rust-analyzer for now.
21        match $o {
22            Some(x) => x,
23            None => return,
24        }
25    };
26    ($o:expr, else $body:block) => {
27        match $o {
28            Some(x) => x,
29            None => $body,
30        }
31    };
32    ($o:expr, $early:stmt) => {
33        // Do not reuse `ward!` here, because it confuses rust-analyzer for now.
34        match $o {
35            Some(x) => x,
36            None => ({ $early }),
37        }
38    };
39}
40
41/// A simple macro to check if a cooldown period has passed since the last time.
42#[macro_export]
43macro_rules! cooldown {
44    ($period:expr) => {{
45        use ::std::{
46            sync::atomic::{AtomicU64, Ordering},
47            time::UNIX_EPOCH,
48        };
49
50        static LOGGED_TIME: AtomicU64 = AtomicU64::new(0);
51
52        let period = $period.as_nanos() as u64;
53        let res = LOGGED_TIME.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |logged_time| {
54            let now = UNIX_EPOCH.elapsed().unwrap_or_default().as_nanos() as u64;
55            if logged_time + period <= now {
56                Some(now)
57            } else {
58                None
59            }
60        });
61
62        res.is_ok()
63    }};
64    ($period:expr, $body:expr) => {{
65        #[deprecated(note = "use `if cooldown!(duration) { .. }` instead")]
66        fn deprecation() {}
67
68        if $crate::cooldown!($period) {
69            deprecation();
70            $body
71        }
72    }};
73}