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,$($init:tt)+) => {
30 pub fn $name() -> &'static $out {
31 static VARBL: std::sync::OnceLock<$out> = std::sync::OnceLock::new();
32 VARBL.get_or_init(|| {
33 $($init)+
34 })
35 }
36 };
37}