bc_envelope/extension/expressions/
functions.rs

1use std::sync::{Once, Mutex};
2use paste::paste;
3
4use super::{Function, FunctionsStore};
5
6/// A macro that declares a function at compile time.
7#[macro_export]
8macro_rules! function_constant {
9    ($const_name:ident, $value:expr, $name:expr) => {
10        paste! {
11            pub const [<$const_name _VALUE>]: u64 = $value;
12        }
13        pub const $const_name: Function = Function::new_with_static_name($value, $name);
14    };
15}
16
17function_constant!(ADD, 1, "add"); // addition
18function_constant!(SUB, 2, "sub"); // subtraction
19function_constant!(MUL, 3, "mul"); // multiplication
20function_constant!(DIV, 4, "div"); // division
21function_constant!(NEG, 5, "neg"); // unary negation
22function_constant!(LT, 6, "lt"); // less than
23function_constant!(LE, 7, "le"); // less than or equal to
24function_constant!(GT, 8, "gt"); // greater than
25function_constant!(GE, 9, "ge"); // greater than or equal to
26function_constant!(EQ, 10, "eq"); // equal to
27function_constant!(NE, 11, "ne"); // not equal to
28function_constant!(AND, 12, "and"); // logical and
29function_constant!(OR, 13, "or"); // logical or
30function_constant!(XOR, 14, "xor"); // logical exclusive or
31function_constant!(NOT, 15, "not"); // logical not
32
33#[doc(hidden)]
34#[derive(Debug)]
35pub struct LazyFunctions {
36    init: Once,
37    data: Mutex<Option<FunctionsStore>>,
38}
39
40impl LazyFunctions {
41    pub fn get(&self) -> std::sync::MutexGuard<'_, Option<FunctionsStore>> {
42        self.init.call_once(|| {
43            let m = FunctionsStore::new([
44                ADD,
45                SUB,
46                MUL,
47                DIV,
48            ]);
49            *self.data.lock().unwrap() = Some(m);
50        });
51        self.data.lock().unwrap()
52    }
53}
54
55/// The global shared store of known functions.
56pub static GLOBAL_FUNCTIONS: LazyFunctions = LazyFunctions {
57    init: Once::new(),
58    data: Mutex::new(None),
59};