Skip to main content

trillium_api/
state.rs

1use crate::FromConn;
2use std::ops::{Deref, DerefMut};
3use trillium::{async_trait, Conn, Handler};
4
5/// State extractor
6#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash)]
7pub struct State<T>(pub T);
8
9impl<T> State<T> {
10    /// construct a new State
11    pub fn new(t: T) -> Self {
12        Self(t)
13    }
14
15    /// Unwrap this State
16    pub fn into_inner(self) -> T {
17        self.0
18    }
19}
20
21impl<T> From<T> for State<T> {
22    fn from(value: T) -> Self {
23        Self(value)
24    }
25}
26
27impl<T> Deref for State<T> {
28    type Target = T;
29
30    fn deref(&self) -> &Self::Target {
31        &self.0
32    }
33}
34
35impl<T> DerefMut for State<T> {
36    fn deref_mut(&mut self) -> &mut Self::Target {
37        &mut self.0
38    }
39}
40
41#[async_trait]
42impl<T> FromConn for State<T>
43where
44    T: Send + Sync + 'static,
45{
46    async fn from_conn(conn: &mut Conn) -> Option<Self> {
47        conn.take_state::<T>().map(Self)
48    }
49}
50
51#[async_trait]
52impl<T> Handler for State<T>
53where
54    T: Clone + Send + Sync + 'static,
55{
56    async fn run(&self, conn: Conn) -> Conn {
57        conn.with_state(self.0.clone())
58    }
59}