task_local_extensions/
extensions.rs

1// Implementation is based on
2// - https://github.com/http-rs/http-types/blob/master/src/extensions.rs
3
4use std::any::{Any, TypeId};
5use std::collections::HashMap;
6use std::fmt;
7
8/// `Extensions` is a type map: values are stored and retrieved using their
9/// [`TypeId`](https://doc.rust-lang.org/std/any/struct.TypeId.html).
10///
11/// This allows storing arbitrary data that implements `Sync + Send + 'static`. This is
12/// useful when you need to share data between different middlewares in the middleware chain
13/// or make some values available from the handler to middlewares
14/// on the outgoing path (e.g. error class).
15#[derive(Default)]
16pub struct Extensions {
17    map: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
18}
19
20impl Extensions {
21    /// Create an empty `Extensions`.
22    pub fn new() -> Self {
23        Self {
24            map: HashMap::default(),
25        }
26    }
27
28    /// Insert a value ino this [`Extensions`], returning self instead of any pre-inserted values.
29    ///
30    /// This is useful for any builder style patterns
31    ///
32    /// ```
33    /// # use task_local_extensions::Extensions;
34    /// let ext = Extensions::new().with(true).with(5_i32);
35    /// assert_eq!(ext.get(), Some(&true));
36    /// assert_eq!(ext.get(), Some(&5_i32));
37    /// ```
38    pub fn with<T: Send + Sync + 'static>(mut self, val: T) -> Self {
39        self.insert(val);
40        self
41    }
42
43    /// Removes the values from `other` and inserts them into `self`.
44    pub fn append(&mut self, other: &mut Self) {
45        self.map.extend(other.map.drain())
46    }
47
48    /// Insert a value into this `Extensions`.
49    ///
50    /// If a value of this type already exists, it will be returned.
51    pub fn insert<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T> {
52        self.map
53            .insert(TypeId::of::<T>(), Box::new(val))
54            .and_then(|boxed| (boxed as Box<dyn Any>).downcast().ok().map(|boxed| *boxed))
55    }
56
57    /// Check if container contains value for type
58    pub fn contains<T: 'static>(&self) -> bool {
59        self.map.get(&TypeId::of::<T>()).is_some()
60    }
61
62    /// Get a reference to a value previously inserted on this `Extensions`.
63    pub fn get<T: 'static>(&self) -> Option<&T> {
64        self.map
65            .get(&TypeId::of::<T>())
66            .and_then(|boxed| (&**boxed as &(dyn Any)).downcast_ref())
67    }
68
69    /// Get a mutable reference to a value previously inserted on this `Extensions`.
70    pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
71        self.map
72            .get_mut(&TypeId::of::<T>())
73            .and_then(|boxed| (&mut **boxed as &mut (dyn Any)).downcast_mut())
74    }
75
76    /// Remove a value from this `Extensions`.
77    ///
78    /// If a value of this type exists, it will be returned.
79    pub fn remove<T: 'static>(&mut self) -> Option<T> {
80        self.map
81            .remove(&TypeId::of::<T>())
82            .and_then(|boxed| (boxed as Box<dyn Any>).downcast().ok().map(|boxed| *boxed))
83    }
84
85    /// Clear the `Extensions` of all inserted values.
86    #[inline]
87    pub fn clear(&mut self) {
88        self.map.clear();
89    }
90}
91
92impl fmt::Debug for Extensions {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.debug_struct("Extensions").finish()
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    #[test]
102    fn test_extensions() {
103        #[derive(Debug, PartialEq)]
104        struct MyType(i32);
105
106        let mut map = Extensions::new();
107
108        map.insert(5i32);
109        map.insert(MyType(10));
110
111        assert_eq!(map.get(), Some(&5i32));
112        assert_eq!(map.get_mut(), Some(&mut 5i32));
113
114        assert_eq!(map.remove::<i32>(), Some(5i32));
115        assert!(map.get::<i32>().is_none());
116
117        assert_eq!(map.get::<bool>(), None);
118        assert_eq!(map.get(), Some(&MyType(10)));
119    }
120}