http_types_rs/
extensions.rs

1// Implementation is based on
2// - https://github.com/hyperium/http/blob/master/src/extensions.rs
3// - https://github.com/kardeiz/type-map/blob/master/src/lib.rs
4
5use std::any::{Any, TypeId};
6use std::collections::HashMap;
7use std::fmt;
8use std::hash::{BuildHasherDefault, Hasher};
9
10/// A type to store extra data inside `Request` and `Response`.
11///
12/// Store and retrieve values by
13/// [`TypeId`](https://doc.rust-lang.org/std/any/struct.TypeId.html). This allows
14/// storing arbitrary data that implements `Sync + Send + 'static`. This is
15/// useful when for example implementing middleware that needs to send values.
16#[derive(Default)]
17pub struct Extensions {
18    map: Option<HashMap<TypeId, Box<dyn Any + Send + Sync>, BuildHasherDefault<IdHasher>>>,
19}
20
21impl Extensions {
22    /// Create an empty `Extensions`.
23    #[inline]
24    pub fn new() -> Self {
25        Self { map: None }
26    }
27
28    /// Insert a value into this `Extensions`.
29    ///
30    /// If a value of this type already exists, it will be returned.
31    pub fn insert<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T> {
32        self.map
33            .get_or_insert_with(Default::default)
34            .insert(TypeId::of::<T>(), Box::new(val))
35            .and_then(|boxed| (boxed as Box<dyn Any>).downcast().ok().map(|boxed| *boxed))
36    }
37
38    /// Check if container contains value for type
39    pub fn contains<T: 'static>(&self) -> bool {
40        self.map.as_ref().and_then(|m| m.get(&TypeId::of::<T>())).is_some()
41    }
42
43    /// Get a reference to a value previously inserted on this `Extensions`.
44    pub fn get<T: 'static>(&self) -> Option<&T> {
45        self.map
46            .as_ref()
47            .and_then(|m| m.get(&TypeId::of::<T>()))
48            .and_then(|boxed| (&**boxed as &(dyn Any)).downcast_ref())
49    }
50
51    /// Get a mutable reference to a value previously inserted on this `Extensions`.
52    pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
53        self.map
54            .as_mut()
55            .and_then(|m| m.get_mut(&TypeId::of::<T>()))
56            .and_then(|boxed| (&mut **boxed as &mut (dyn Any)).downcast_mut())
57    }
58
59    /// Remove a value from this `Extensions`.
60    ///
61    /// If a value of this type exists, it will be returned.
62    pub fn remove<T: 'static>(&mut self) -> Option<T> {
63        self.map
64            .as_mut()
65            .and_then(|m| m.remove(&TypeId::of::<T>()))
66            .and_then(|boxed| (boxed as Box<dyn Any>).downcast().ok().map(|boxed| *boxed))
67    }
68
69    /// Clear the `Extensions` of all inserted values.
70    #[inline]
71    pub fn clear(&mut self) {
72        self.map = None;
73    }
74}
75
76impl fmt::Debug for Extensions {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        f.debug_struct("Extensions").finish()
79    }
80}
81
82// With TypeIds as keys, there's no need to hash them. So we simply use an identy hasher.
83#[derive(Default)]
84struct IdHasher(u64);
85
86impl Hasher for IdHasher {
87    fn write(&mut self, _: &[u8]) {
88        unreachable!("TypeId calls write_u64");
89    }
90
91    #[inline]
92    fn write_u64(&mut self, id: u64) {
93        self.0 = id;
94    }
95
96    #[inline]
97    fn finish(&self) -> u64 {
98        self.0
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105    #[test]
106    fn test_extensions() {
107        #[derive(Debug, PartialEq)]
108        struct MyType(i32);
109
110        let mut map = Extensions::new();
111
112        map.insert(5i32);
113        map.insert(MyType(10));
114
115        assert_eq!(map.get(), Some(&5i32));
116        assert_eq!(map.get_mut(), Some(&mut 5i32));
117
118        assert_eq!(map.remove::<i32>(), Some(5i32));
119        assert!(map.get::<i32>().is_none());
120
121        assert_eq!(map.get::<bool>(), None);
122        assert_eq!(map.get(), Some(&MyType(10)));
123    }
124}