app_state/states/
mutable_app_state.rs

1use crate::states::traits::CreateAppState;
2use crate::{AppStateTrait, MutAppStateLock};
3use std::ops::Deref;
4use std::sync::{Arc, Mutex};
5
6/// A mutable app state.
7///
8/// # Examples
9/// ```rust
10/// use app_state::{MutAppState, AppStateTrait, stateful};
11///
12/// struct MyState {
13///   counter: u32,
14/// }
15///
16/// #[stateful]
17/// fn func(state: MutAppState<MyState>) {
18///   let mut state = state.get_mut();
19///   state.counter += 1;
20/// }
21/// ```
22#[derive(Debug)]
23pub struct MutAppState<T: ?Sized>(Arc<Mutex<T>>);
24
25impl<T: 'static + Send> MutAppState<T> {
26    /// Returns reference to inner `T`.
27    pub fn get_mut(&self) -> MutAppStateLock<T> {
28        MutAppStateLock::new(&self)
29    }
30}
31
32impl<T: 'static + Send> CreateAppState<T> for MutAppState<T> {
33    fn new(state: T) -> MutAppState<T> {
34        MutAppState(Arc::new(Mutex::new(state)))
35    }
36}
37
38impl<T: 'static + Send> AppStateTrait<T, MutAppState<T>> for MutAppState<T> {}
39
40impl<T: ?Sized> MutAppState<T> {
41    /// Unwraps to the internal `Arc<T>`
42    pub fn into_inner(self) -> Arc<Mutex<T>> {
43        self.0
44    }
45}
46
47impl<T: ?Sized> Deref for MutAppState<T> {
48    type Target = Arc<Mutex<T>>;
49
50    fn deref(&self) -> &Arc<Mutex<T>> {
51        &self.0
52    }
53}
54
55impl<T: ?Sized> Clone for MutAppState<T> {
56    fn clone(&self) -> MutAppState<T> {
57        MutAppState(self.0.clone())
58    }
59}
60
61impl<T: ?Sized> From<Arc<Mutex<T>>> for MutAppState<T> {
62    fn from(arc: Arc<Mutex<T>>) -> Self {
63        MutAppState(arc)
64    }
65}