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
48
49
use once_cell::sync::OnceCell;

use parking_lot::Mutex;

use crate::{Config, XMT};

static INSTANCE: OnceCell<Mutex<XMT>> = OnceCell::new();

/// Initialize the global XMT instance with the provided configuration.
#[allow(unused_must_use)]
pub fn init(cfg: Config) {
    let mut instance = XMT::new(cfg);
    let mtx = get_instance();
    let mut guard = mtx.lock();
    std::mem::swap(&mut *guard, &mut instance);
}

/// Initialize the global XMT instance with the default configuration.
pub fn init_default() {
    init(Config::default())
}

pub fn get_instance() -> &'static Mutex<XMT> {
    INSTANCE.get_or_init(|| Mutex::new(XMT::default()))
}

#[allow(unused_must_use)]
pub fn nest<T, F: FnOnce() -> T>(message: &str, func: F) -> T {
    let mtx = get_instance();

    let orig = {
        let mut guard = mtx.lock();
        let orig = guard.clone();
        orig.print(message);

        let nested = orig.nest();
        *guard = nested;
        orig
    };

    let ret_val = func();

    {
        let mut guard = mtx.lock();
        *guard = orig;
    }

    ret_val
}