Skip to main content

salvo_core/
depot.rs

1use std::any::{Any, TypeId};
2use std::collections::HashMap;
3use std::fmt::{self, Debug, Formatter};
4
5/// Store temp data for current request.
6///
7/// A `Depot` created when server process a request from client. It will dropped when all process
8/// for this request done.
9///
10/// # Example
11/// We set `current_user` value in function `set_user` , and then use this value in the following
12/// middlewares and handlers.
13///
14/// ```no_run
15/// use salvo_core::prelude::*;
16///
17/// #[handler]
18/// async fn set_user(depot: &mut Depot) {
19///     depot.insert("user", "client");
20/// }
21/// #[handler]
22/// async fn hello(depot: &mut Depot) -> String {
23///     format!(
24///         "Hello {}",
25///         depot.get::<&str>("user").copied().unwrap_or_default()
26///     )
27/// }
28///
29/// #[tokio::main]
30/// async fn main() {
31///     let router = Router::new().hoop(set_user).goal(hello);
32///     let acceptor = TcpListener::new("0.0.0.0:8698").bind().await;
33///     Server::new(acceptor).serve(router).await;
34/// }
35/// ```
36
37#[derive(Default)]
38pub struct Depot {
39    map: HashMap<String, Box<dyn Any + Send + Sync>>,
40}
41
42#[inline]
43fn type_key<T: 'static>() -> String {
44    format!("{:?}", TypeId::of::<T>())
45}
46
47impl Depot {
48    /// Creates an empty `Depot`.
49    ///
50    /// The depot is initially created with a capacity of 0, so it will not allocate until it is
51    /// first inserted into.
52    #[inline]
53    #[must_use]
54    pub fn new() -> Self {
55        Self {
56            map: HashMap::new(),
57        }
58    }
59
60    /// Get reference to depot inner map.
61    #[inline]
62    #[must_use]
63    pub fn inner(&self) -> &HashMap<String, Box<dyn Any + Send + Sync>> {
64        &self.map
65    }
66
67    /// Creates an empty `Depot` with the specified capacity.
68    ///
69    /// The depot will be able to hold at least capacity elements without reallocating. If capacity
70    /// is 0, the depot will not allocate.
71    #[inline]
72    #[must_use]
73    pub fn with_capacity(capacity: usize) -> Self {
74        Self {
75            map: HashMap::with_capacity(capacity),
76        }
77    }
78    /// Returns the number of elements the depot can hold without reallocating.
79    #[inline]
80    #[must_use]
81    pub fn capacity(&self) -> usize {
82        self.map.capacity()
83    }
84
85    /// Inject a value into the depot.
86    #[inline]
87    pub fn inject<V: Any + Send + Sync>(&mut self, value: V) -> &mut Self {
88        self.map.insert(type_key::<V>(), Box::new(value));
89        self
90    }
91
92    /// Obtain a reference to a value previous inject to the depot.
93    ///
94    /// Returns `Err(None)` if value is not present in depot.
95    /// Returns `Err(Some(Box<dyn Any + Send + Sync>))` if value is present in depot but downcasting
96    /// failed.
97    #[inline]
98    pub fn obtain<T: Any + Send + Sync>(&self) -> Result<&T, Option<&Box<dyn Any + Send + Sync>>> {
99        self.get(&type_key::<T>())
100    }
101
102    /// Obtain a mutable reference to a value previous inject to the depot.
103    ///
104    /// Returns `Err(None)` if value is not present in depot.
105    /// Returns `Err(Some(Box<dyn Any + Send + Sync>))` if value is present in depot but downcasting
106    /// failed.
107    #[inline]
108    pub fn obtain_mut<T: Any + Send + Sync>(
109        &mut self,
110    ) -> Result<&mut T, Option<&mut Box<dyn Any + Send + Sync>>> {
111        self.get_mut(&type_key::<T>())
112    }
113
114    /// Inserts a key-value pair into the depot.
115    #[inline]
116    pub fn insert<K, V>(&mut self, key: K, value: V) -> &mut Self
117    where
118        K: Into<String>,
119        V: Any + Send + Sync,
120    {
121        self.map.insert(key.into(), Box::new(value));
122        self
123    }
124
125    /// Check is there a value stored in depot with this key.
126    #[inline]
127    #[must_use]
128    pub fn contains_key(&self, key: &str) -> bool {
129        self.map.contains_key(key)
130    }
131    /// Check is there a value is injected to the depot.
132    ///
133    /// **Note**: This is only check injected value.
134    #[inline]
135    #[must_use]
136    pub fn contains<T: Any + Send + Sync>(&self) -> bool {
137        self.map.contains_key(&type_key::<T>())
138    }
139
140    /// Immutably borrows value from depot.
141    ///
142    /// Returns `Err(None)` if value is not present in depot.
143    /// Returns `Err(Some(Box<dyn Any + Send + Sync>))` if value is present in depot but downcasting
144    /// failed.
145    #[inline]
146    pub fn get<V: Any + Send + Sync>(
147        &self,
148        key: &str,
149    ) -> Result<&V, Option<&Box<dyn Any + Send + Sync>>> {
150        if let Some(value) = self.map.get(key) {
151            value.downcast_ref::<V>().ok_or(Some(value))
152        } else {
153            Err(None)
154        }
155    }
156
157    /// Mutably borrows value from depot.
158    ///
159    /// Returns `Err(None)` if value is not present in depot.
160    /// Returns `Err(Some(Box<dyn Any + Send + Sync>))` if value is present in depot but downcasting
161    /// failed.
162    pub fn get_mut<V: Any + Send + Sync>(
163        &mut self,
164        key: &str,
165    ) -> Result<&mut V, Option<&mut Box<dyn Any + Send + Sync>>> {
166        if let Some(value) = self.map.get_mut(key) {
167            if value.downcast_mut::<V>().is_some() {
168                Ok(value
169                    .downcast_mut::<V>()
170                    .expect("downcast_mut should not be failed"))
171            } else {
172                Err(Some(value))
173            }
174        } else {
175            Err(None)
176        }
177    }
178
179    /// Remove value from depot and returning the value at the key if the key was previously in the
180    /// depot.
181    #[inline]
182    pub fn remove<V: Any + Send + Sync>(
183        &mut self,
184        key: &str,
185    ) -> Result<V, Option<Box<dyn Any + Send + Sync>>> {
186        if let Some(value) = self.map.remove(key) {
187            value.downcast::<V>().map(|b| *b).map_err(Some)
188        } else {
189            Err(None)
190        }
191    }
192
193    /// Delete the key from depot, if the key is not present, return `false`.
194    #[inline]
195    pub fn delete(&mut self, key: &str) -> bool {
196        self.map.remove(key).is_some()
197    }
198
199    /// Remove value from depot and returning the value if the type was previously in the depot.
200    #[inline]
201    pub fn scrape<T: Any + Send + Sync>(
202        &mut self,
203    ) -> Result<T, Option<Box<dyn Any + Send + Sync>>> {
204        self.remove(&type_key::<T>())
205    }
206}
207
208impl Debug for Depot {
209    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
210        f.debug_struct("Depot")
211            .field("keys", &self.map.keys())
212            .finish()
213    }
214}
215
216#[cfg(test)]
217mod test {
218    use super::*;
219    use crate::prelude::*;
220    use crate::test::{ResponseExt, TestClient};
221
222    #[test]
223    fn test_depot() {
224        let mut depot = Depot::with_capacity(6);
225        assert!(depot.capacity() >= 6);
226
227        depot.insert("one", "ONE".to_owned());
228        assert!(depot.contains_key("one"));
229
230        assert_eq!(depot.get::<String>("one").unwrap(), &"ONE".to_owned());
231        assert_eq!(
232            depot.get_mut::<String>("one").unwrap(),
233            &mut "ONE".to_owned()
234        );
235    }
236
237    #[tokio::test]
238    async fn test_middleware_use_depot() {
239        #[handler]
240        async fn set_user(
241            req: &mut Request,
242            depot: &mut Depot,
243            res: &mut Response,
244            ctrl: &mut FlowCtrl,
245        ) {
246            depot.insert("user", "client");
247            ctrl.call_next(req, depot, res).await;
248        }
249        #[handler]
250        async fn hello(depot: &mut Depot) -> String {
251            format!(
252                "Hello {}",
253                depot.get::<&str>("user").copied().unwrap_or_default()
254            )
255        }
256        let router = Router::new().hoop(set_user).goal(hello);
257        let service = Service::new(router);
258
259        let content = TestClient::get("http://127.0.0.1:8698")
260            .send(&service)
261            .await
262            .take_string()
263            .await
264            .unwrap();
265        assert_eq!(content, "Hello client");
266    }
267}