app_state/states/
mut_app_state_lock.rs

1use crate::MutAppState;
2use std::ops::{Deref, DerefMut};
3use std::sync::MutexGuard;
4
5/// The lock guard for a mutable app state.
6/// This is a wrapper around `MutexGuard`.
7/// When this guard is dropped, the lock will be released.
8/// As this locks the state, no other thread can access the state until this guard is dropped.
9///
10/// # Examples
11/// ```rust
12/// use app_state::{MutAppState, MutAppStateLock, AppStateTrait, stateful};
13///
14/// struct MyState {
15///   counter: u32,
16/// }
17///
18/// #[stateful]
19/// fn func(mut state: MutAppStateLock<MyState>) {
20///   state.counter += 1;
21/// }
22/// ```
23pub struct MutAppStateLock<'a, T: ?Sized>(MutexGuard<'a, T>);
24
25impl<'a, T: 'static + Send> MutAppStateLock<'a, T> {
26    pub fn new(inner: &'a MutAppState<T>) -> MutAppStateLock<'a, T> {
27        MutAppStateLock(inner.lock().unwrap())
28    }
29}
30
31impl<'a, T: ?Sized> MutAppStateLock<'a, T> {
32    /// Returns reference to inner `T`.
33    pub fn get_ref(&self) -> &MutexGuard<'a, T> {
34        &self.0
35    }
36
37    /// Unwraps to the internal `Arc<T>`
38    pub fn into_inner(self) -> MutexGuard<'a, T> {
39        self.0
40    }
41}
42
43impl<'a, T: ?Sized> Deref for MutAppStateLock<'a, T> {
44    type Target = T;
45
46    fn deref(&self) -> &T {
47        &self.0
48    }
49}
50
51impl<'a, T: ?Sized> DerefMut for MutAppStateLock<'a, T> {
52    fn deref_mut(&mut self) -> &mut T {
53        &mut self.0
54    }
55}