atomic_state/state/
state.rs

1use crate::prelude::*;
2use super::*;
3
4/// The atomic state
5#[derive(Clone)]
6pub struct State<T: Clone> {
7    rw_lock: Arc<RwLock<Arc<T>>>,
8    arc_swap: Arc<ArcSwapAny<Arc<T>>>,
9}
10
11impl<T: Clone> State<T> {
12    /// Creates a new state
13    pub fn new(value: T) -> Self {
14        let arc_val = Arc::new(value);
15        
16        Self {
17            rw_lock: Arc::new(RwLock::new(arc_val.clone())),
18            arc_swap: Arc::new(ArcSwapAny::from(arc_val)),
19        }
20    }
21
22    /// Returns a locked state guard
23    pub fn lock(&self) -> StateGuard<'_, T> {
24        let rw_lock = self.rw_lock.write().expect(ERR_MSG);
25        let data = (**rw_lock).clone();
26        
27        StateGuard {
28            rw_lock,
29            arc_swap: self.arc_swap.clone(),
30            data,
31        }
32    }
33
34    /// Returns a state value
35    pub fn get(&self) -> Arc<T> {
36        self.arc_swap.load_full()
37    }
38
39    /// Returns a clone of state value
40    pub fn get_cloned(&self) -> T {
41        self.arc_swap.load_full().as_ref().clone()
42    }
43
44    /// Sets a new value to state
45    pub fn set(&self, value: T) {
46        *self.lock() = value;
47    }
48
49    /// Writes data directly
50    pub fn map(&self, f: impl FnOnce(&mut T)) {
51        let mut rw_lock = self.lock();
52        let mut data = (*rw_lock).clone();
53
54        f(&mut data);
55        *rw_lock = data;
56    }
57}
58
59impl<T: Clone + Default> ::std::default::Default for State<T> {
60    fn default() -> Self {
61        Self::new(Default::default())
62    }
63}
64
65impl<T: Clone + Debugging> ::std::fmt::Debug for State<T> {
66    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
67        write!(f, "{:?}", &self.get())
68    }
69}