1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use std::sync::{Once, Mutex};
use paste::paste;

use super::{Function, FunctionsStore};

/// A macro that declares a function at compile time.
#[macro_export]
macro_rules! function_constant {
    ($const_name:ident, $value:expr, $name:expr) => {
        paste! {
            pub const [<$const_name _VALUE>]: u64 = $value;
        }
        pub const $const_name: Function = Function::new_with_static_name($value, $name);
    };
}

function_constant!(ADD, 1, "add");
function_constant!(SUB, 2, "sub");
function_constant!(MUL, 3, "mul");
function_constant!(DIV, 4, "div");

#[doc(hidden)]
pub struct LazyFunctions {
    init: Once,
    data: Mutex<Option<FunctionsStore>>,
}

impl LazyFunctions {
    pub fn get(&self) -> std::sync::MutexGuard<'_, Option<FunctionsStore>> {
        self.init.call_once(|| {
            let m = FunctionsStore::new([
                ADD,
                SUB,
                MUL,
                DIV,
            ]);
            *self.data.lock().unwrap() = Some(m);
        });
        self.data.lock().unwrap()
    }
}

/// The global shared store of known functions.
pub static GLOBAL_FUNCTIONS: LazyFunctions = LazyFunctions {
    init: Once::new(),
    data: Mutex::new(None),
};