app_state/states/
app_state.rs

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