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
45use std::any::{Any, TypeId};
6use std::collections::HashMap;
7use std::fmt;
8use std::hash::{BuildHasherDefault, Hasher};
910/// 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}
2021impl Extensions {
22/// Create an empty `Extensions`.
23#[inline]
24pub(crate) fn new() -> Self {
25Self { map: None }
26 }
2728/// Insert a value into this `Extensions`.
29 ///
30 /// If a value of this type already exists, it will be returned.
31pub fn insert<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T> {
32self.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 }
3738/// Check if container contains value for type
39pub fn contains<T: 'static>(&self) -> bool {
40self.map
41 .as_ref()
42 .and_then(|m| m.get(&TypeId::of::<T>()))
43 .is_some()
44 }
4546/// Get a reference to a value previously inserted on this `Extensions`.
47pub fn get<T: 'static>(&self) -> Option<&T> {
48self.map
49 .as_ref()
50 .and_then(|m| m.get(&TypeId::of::<T>()))
51 .and_then(|boxed| (&**boxed as &(dyn Any)).downcast_ref())
52 }
5354/// Get a mutable reference to a value previously inserted on this `Extensions`.
55pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
56self.map
57 .as_mut()
58 .and_then(|m| m.get_mut(&TypeId::of::<T>()))
59 .and_then(|boxed| (&mut **boxed as &mut (dyn Any)).downcast_mut())
60 }
6162/// Remove a value from this `Extensions`.
63 ///
64 /// If a value of this type exists, it will be returned.
65pub fn remove<T: 'static>(&mut self) -> Option<T> {
66self.map
67 .as_mut()
68 .and_then(|m| m.remove(&TypeId::of::<T>()))
69 .and_then(|boxed| (boxed as Box<dyn Any>).downcast().ok().map(|boxed| *boxed))
70 }
7172/// Clear the `Extensions` of all inserted values.
73#[inline]
74pub fn clear(&mut self) {
75self.map = None;
76 }
77}
7879impl fmt::Debug for Extensions {
80fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 f.debug_struct("Extensions").finish()
82 }
83}
8485// With TypeIds as keys, there's no need to hash them. So we simply use an identy hasher.
86#[derive(Default)]
87struct IdHasher(u64);
8889impl Hasher for IdHasher {
90fn write(&mut self, _: &[u8]) {
91unreachable!("TypeId calls write_u64");
92 }
9394#[inline]
95fn write_u64(&mut self, id: u64) {
96self.0 = id;
97 }
9899#[inline]
100fn finish(&self) -> u64 {
101self.0
102}
103}
104105#[cfg(test)]
106mod tests {
107use super::*;
108#[test]
109fn test_extensions() {
110#[derive(Debug, PartialEq)]
111struct MyType(i32);
112113let mut map = Extensions::new();
114115 map.insert(5i32);
116 map.insert(MyType(10));
117118assert_eq!(map.get(), Some(&5i32));
119assert_eq!(map.get_mut(), Some(&mut 5i32));
120121assert_eq!(map.remove::<i32>(), Some(5i32));
122assert!(map.get::<i32>().is_none());
123124assert_eq!(map.get::<bool>(), None);
125assert_eq!(map.get(), Some(&MyType(10)));
126 }
127}