1// Implementation is based on
2// - https://github.com/http-rs/http-types/blob/master/src/extensions.rs
34use std::any::{Any, TypeId};
5use std::collections::HashMap;
6use std::fmt;
78/// `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}
1920impl Extensions {
21/// Create an empty `Extensions`.
22pub fn new() -> Self {
23Self {
24 map: HashMap::default(),
25 }
26 }
2728/// 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 /// ```
38pub fn with<T: Send + Sync + 'static>(mut self, val: T) -> Self {
39self.insert(val);
40self
41}
4243/// Removes the values from `other` and inserts them into `self`.
44pub fn append(&mut self, other: &mut Self) {
45self.map.extend(other.map.drain())
46 }
4748/// Insert a value into this `Extensions`.
49 ///
50 /// If a value of this type already exists, it will be returned.
51pub fn insert<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T> {
52self.map
53 .insert(TypeId::of::<T>(), Box::new(val))
54 .and_then(|boxed| (boxed as Box<dyn Any>).downcast().ok().map(|boxed| *boxed))
55 }
5657/// Check if container contains value for type
58pub fn contains<T: 'static>(&self) -> bool {
59self.map.get(&TypeId::of::<T>()).is_some()
60 }
6162/// Get a reference to a value previously inserted on this `Extensions`.
63pub fn get<T: 'static>(&self) -> Option<&T> {
64self.map
65 .get(&TypeId::of::<T>())
66 .and_then(|boxed| (&**boxed as &(dyn Any)).downcast_ref())
67 }
6869/// Get a mutable reference to a value previously inserted on this `Extensions`.
70pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
71self.map
72 .get_mut(&TypeId::of::<T>())
73 .and_then(|boxed| (&mut **boxed as &mut (dyn Any)).downcast_mut())
74 }
7576/// Remove a value from this `Extensions`.
77 ///
78 /// If a value of this type exists, it will be returned.
79pub fn remove<T: 'static>(&mut self) -> Option<T> {
80self.map
81 .remove(&TypeId::of::<T>())
82 .and_then(|boxed| (boxed as Box<dyn Any>).downcast().ok().map(|boxed| *boxed))
83 }
8485/// Clear the `Extensions` of all inserted values.
86#[inline]
87pub fn clear(&mut self) {
88self.map.clear();
89 }
90}
9192impl fmt::Debug for Extensions {
93fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 f.debug_struct("Extensions").finish()
95 }
96}
9798#[cfg(test)]
99mod tests {
100use super::*;
101#[test]
102fn test_extensions() {
103#[derive(Debug, PartialEq)]
104struct MyType(i32);
105106let mut map = Extensions::new();
107108 map.insert(5i32);
109 map.insert(MyType(10));
110111assert_eq!(map.get(), Some(&5i32));
112assert_eq!(map.get_mut(), Some(&mut 5i32));
113114assert_eq!(map.remove::<i32>(), Some(5i32));
115assert!(map.get::<i32>().is_none());
116117assert_eq!(map.get::<bool>(), None);
118assert_eq!(map.get(), Some(&MyType(10)));
119 }
120}