cuprated/
statics.rs

1//! Global `static`s used throughout `cuprated`.
2
3use std::{
4    sync::LazyLock,
5    time::{SystemTime, UNIX_EPOCH},
6};
7
8/// Define all the `static`s that should be always be initialized early on.
9///
10/// This wraps all `static`s inside a `LazyLock` and generates
11/// a [`init_lazylock_statics`] function that must/should be
12/// used by `main()` early on.
13macro_rules! define_init_lazylock_statics {
14    ($(
15        $( #[$attr:meta] )*
16        $name:ident: $t:ty = $init_fn:expr_2021;
17    )*) => {
18        /// Initialize global static `LazyLock` data.
19        pub fn init_lazylock_statics() {
20            $(
21                LazyLock::force(&$name);
22            )*
23        }
24
25        $(
26            $(#[$attr])*
27            pub static $name: LazyLock<$t> = LazyLock::new(|| $init_fn);
28        )*
29    };
30}
31
32define_init_lazylock_statics! {
33    /// The start time of `cuprated`.
34    START_INSTANT: SystemTime = SystemTime::now();
35
36    /// Start time of `cuprated` as a UNIX timestamp.
37    START_INSTANT_UNIX: u64 = START_INSTANT
38        .duration_since(UNIX_EPOCH)
39        .expect("Failed to set `cuprated` startup time.")
40        .as_secs();
41}
42
43#[cfg(test)]
44mod test {
45    use super::*;
46
47    /// Sanity check for startup UNIX time.
48    #[test]
49    fn start_instant_unix() {
50        // Fri Sep 27 01:07:13 AM UTC 2024
51        assert!(*START_INSTANT_UNIX > 1727399233);
52    }
53}