goon/
lib.rs

1pub use lazy_static;
2use std::sync::{Arc, Mutex};
3pub use serde::{self,Deserialize, Serialize};
4pub use serde_json;
5pub use goon_proc_macros::{global, goon_init, declare_global, goon_update};
6pub struct Global<T> {
7    inner: Arc<Mutex<T>>,
8}
9impl<T> Global<T> {
10    pub fn new(initial_value: T) -> Self {
11        Global {
12            inner: Arc::new(Mutex::new(initial_value)),
13        }
14    }
15
16    pub fn clone(&self) -> Self {
17        Global {
18            inner: self.inner.clone(),
19        }
20    }
21
22    pub fn lock(&self) -> Result<std::sync::MutexGuard<'_, T>, std::sync::PoisonError<std::sync::MutexGuard<'_, T>>> {
23        self.inner.lock()
24    }
25
26    pub fn try_lock(&self) -> Result<std::sync::MutexGuard<'_, T>, std::sync::TryLockError<std::sync::MutexGuard<'_, T>>>{
27        self.inner.try_lock()
28    }
29}
30
31
32#[macro_export]
33macro_rules! lock_globals {
34    ( $node:ident; $mutex:ident ; $code:block ) => {
35        if let Ok(mut $mutex) = $mutex.lock() {
36            let ret = {$code};
37
38            $node.update(stringify!($mutex).to_string(), &*$mutex);
39            Some(ret)
40        } else {
41            None
42        }
43    };
44    ( |$($tail:ident),* | =>  $code:block ) => {
45        if let Ok(node) = NODE.clone().lock() {
46            lock_globals!(node; $($tail),* ; $code)
47        } else {
48            None
49        }
50    };
51    ($node:ident; $head:ident, $($tail:ident),* ; $code:block ) => {
52        if let Ok(mut $head) = $head.lock() {
53            $node.update(stringify!($head).to_string(), &*$head);
54            lock_globals!($node; $($tail),* ; $code)
55        } else {
56            None
57        }
58    };
59}
60#[macro_export]
61macro_rules! read_globals {
62    ( $mutex:ident ; $code:block ) => {
63        if let Ok($mutex) = $mutex.lock() {
64            let ret = {$code};
65            Some(ret)
66        } else {
67            None
68        }
69    };
70    ( | $($tail:ident),* | => $code:block ) => {
71        read_globals!($($tail),* ; $code)
72    };
73    ( $head:ident, $($tail:ident),* ; $code:block ) => {
74        if let Ok($head) = $head.lock() {
75            read_globals!($($tail),* ; $code)
76        } else {
77            None
78        }
79    };
80}
81
82
83
84
85