Skip to main content

irox_tools/sync/
once.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2023 IROX Contributors
3//
4
5//!
6//! Static Initialization Primitives
7//!
8
9///
10/// Creates a static lazy initialization variable function.
11///
12/// ```no_run
13/// # use irox_tools::static_init;
14/// static_init!(get_data, String, {
15///     "This could be an expensive operation!".to_string()
16/// });
17/// ```
18/// expands to:
19/// ```no_run
20/// pub fn get_data() -> &'static String {
21///     static VARBL: std::sync::OnceLock<String> = std::sync::OnceLock::new();
22///     VARBL.get_or_init(|| {
23///         "This could be an expensive operation!".to_string()
24///     })
25/// }
26/// ```
27#[macro_export]
28macro_rules! static_init {
29    ($name:ident,$out:ty,$docs:expr,$($init:tt)+) => {
30        #[doc = $docs]       
31        pub fn $name() -> &'static $out {
32            static VARBL: std::sync::OnceLock<$out> = std::sync::OnceLock::new();
33            VARBL.get_or_init(|| {
34                $($init)+
35            })
36        }
37    };
38    ($name:ident,$out:ty,$($init:tt)+) => {
39        pub fn $name() -> &'static $out {
40            static VARBL: std::sync::OnceLock<$out> = std::sync::OnceLock::new();
41            VARBL.get_or_init(|| {
42                $($init)+
43            })
44        }
45    };
46}