1 use std
::any
::{Any, TypeId}
;
2 use std
::collections
::HashMap
;
4 use std
::hash
::{BuildHasherDefault, Hasher}
;
6 type AnyMap
= HashMap
<TypeId
, Box
<dyn Any
+ Send
+ Sync
>, BuildHasherDefault
<IdHasher
>>;
8 // With TypeIds as keys, there's no need to hash them. They are already hashes
9 // themselves, coming from the compiler. The IdHasher just holds the u64 of
10 // the TypeId, and then returns it, instead of doing any bit fiddling.
14 impl Hasher
for IdHasher
{
15 fn write(&mut self, _
: &[u8]) {
16 unreachable
!("TypeId calls write_u64");
20 fn write_u64(&mut self, id
: u64) {
25 fn finish(&self) -> u64 {
30 /// A type map of protocol extensions.
32 /// `Extensions` can be used by `Request` and `Response` to store
33 /// extra data derived from the underlying protocol.
35 pub struct Extensions
{
36 // If extensions are never used, no need to carry around an empty HashMap.
37 // That's 3 words. Instead, this is only 1 word.
38 map
: Option
<Box
<AnyMap
>>,
42 /// Create an empty `Extensions`.
44 pub fn new() -> Extensions
{
45 Extensions { map: None }
48 /// Insert a type into this `Extensions`.
50 /// If a extension of this type already existed, it will
56 /// # use http::Extensions;
57 /// let mut ext = Extensions::new();
58 /// assert!(ext.insert(5i32).is_none());
59 /// assert!(ext.insert(4u8).is_none());
60 /// assert_eq!(ext.insert(9i32), Some(5i32));
62 pub fn insert
<T
: Send
+ Sync
+ '
static>(&mut self, val
: T
) -> Option
<T
> {
64 .get_or_insert_with(|| Box
::new(HashMap
::default()))
65 .insert(TypeId
::of
::<T
>(), Box
::new(val
))
67 (boxed
as Box
<dyn Any
+ '
static>)
74 /// Get a reference to a type previously inserted on this `Extensions`.
79 /// # use http::Extensions;
80 /// let mut ext = Extensions::new();
81 /// assert!(ext.get::<i32>().is_none());
84 /// assert_eq!(ext.get::<i32>(), Some(&5i32));
86 pub fn get
<T
: Send
+ Sync
+ '
static>(&self) -> Option
<&T
> {
89 .and_then(|map
| map
.get(&TypeId
::of
::<T
>()))
90 .and_then(|boxed
| (&**boxed
as &(dyn Any
+ '
static)).downcast_ref())
93 /// Get a mutable reference to a type previously inserted on this `Extensions`.
98 /// # use http::Extensions;
99 /// let mut ext = Extensions::new();
100 /// ext.insert(String::from("Hello"));
101 /// ext.get_mut::<String>().unwrap().push_str(" World");
103 /// assert_eq!(ext.get::<String>().unwrap(), "Hello World");
105 pub fn get_mut
<T
: Send
+ Sync
+ '
static>(&mut self) -> Option
<&mut T
> {
108 .and_then(|map
| map
.get_mut(&TypeId
::of
::<T
>()))
109 .and_then(|boxed
| (&mut **boxed
as &mut (dyn Any
+ '
static)).downcast_mut())
112 /// Remove a type from this `Extensions`.
114 /// If a extension of this type existed, it will be returned.
119 /// # use http::Extensions;
120 /// let mut ext = Extensions::new();
121 /// ext.insert(5i32);
122 /// assert_eq!(ext.remove::<i32>(), Some(5i32));
123 /// assert!(ext.get::<i32>().is_none());
125 pub fn remove
<T
: Send
+ Sync
+ '
static>(&mut self) -> Option
<T
> {
128 .and_then(|map
| map
.remove(&TypeId
::of
::<T
>()))
130 (boxed
as Box
<dyn Any
+ '
static>)
137 /// Clear the `Extensions` of all inserted extensions.
142 /// # use http::Extensions;
143 /// let mut ext = Extensions::new();
144 /// ext.insert(5i32);
147 /// assert!(ext.get::<i32>().is_none());
150 pub fn clear(&mut self) {
151 if let Some(ref mut map
) = self.map
{
156 /// Check whether the extension set is empty or not.
161 /// # use http::Extensions;
162 /// let mut ext = Extensions::new();
163 /// assert!(ext.is_empty());
164 /// ext.insert(5i32);
165 /// assert!(!ext.is_empty());
168 pub fn is_empty(&self) -> bool
{
171 .map_or(true, |map
| map
.is_empty())
174 /// Get the numer of extensions available.
179 /// # use http::Extensions;
180 /// let mut ext = Extensions::new();
181 /// assert_eq!(ext.len(), 0);
182 /// ext.insert(5i32);
183 /// assert_eq!(ext.len(), 1);
186 pub fn len(&self) -> usize {
189 .map_or(0, |map
| map
.len())
192 /// Extends `self` with another `Extensions`.
194 /// If an instance of a specific type exists in both, the one in `self` is overwritten with the
195 /// one from `other`.
200 /// # use http::Extensions;
201 /// let mut ext_a = Extensions::new();
202 /// ext_a.insert(8u8);
203 /// ext_a.insert(16u16);
205 /// let mut ext_b = Extensions::new();
206 /// ext_b.insert(4u8);
207 /// ext_b.insert("hello");
209 /// ext_a.extend(ext_b);
210 /// assert_eq!(ext_a.len(), 3);
211 /// assert_eq!(ext_a.get::<u8>(), Some(&4u8));
212 /// assert_eq!(ext_a.get::<u16>(), Some(&16u16));
213 /// assert_eq!(ext_a.get::<&'static str>().copied(), Some("hello"));
215 pub fn extend(&mut self, other
: Self) {
216 if let Some(other
) = other
.map
{
217 if let Some(map
) = &mut self.map
{
220 self.map
= Some(other
);
226 impl fmt
::Debug
for Extensions
{
227 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
228 f
.debug_struct("Extensions").finish()
233 fn test_extensions() {
234 #[derive(Debug, PartialEq)]
237 let mut extensions
= Extensions
::new();
239 extensions
.insert(5i32);
240 extensions
.insert(MyType(10));
242 assert_eq
!(extensions
.get(), Some(&5i32));
243 assert_eq
!(extensions
.get_mut(), Some(&mut 5i32));
245 assert_eq
!(extensions
.remove
::<i32>(), Some(5i32));
246 assert
!(extensions
.get
::<i32>().is_none());
248 assert_eq
!(extensions
.get
::<bool
>(), None
);
249 assert_eq
!(extensions
.get(), Some(&MyType(10)));