|
| 1 | +// NOTE: this module is taken from tokio's tracing span's extensions |
| 2 | +// which is taken from https://github.com/hyperium/http/blob/master/src/extensions.rs |
| 3 | + |
| 4 | +use std::any::Any; |
| 5 | +use std::any::TypeId; |
| 6 | +use std::collections::HashMap; |
| 7 | +use std::fmt; |
| 8 | +use std::hash::BuildHasherDefault; |
| 9 | +use std::hash::Hasher; |
| 10 | + |
| 11 | +type AnyMap = HashMap<TypeId, Box<dyn Any + Send + Sync>, BuildHasherDefault<IdHasher>>; |
| 12 | + |
| 13 | +// With TypeIds as keys, there's no need to hash them. They are already hashes |
| 14 | +// themselves, coming from the compiler. The IdHasher just holds the u64 of |
| 15 | +// the TypeId, and then returns it, instead of doing any bit fiddling. |
| 16 | +#[derive(Default)] |
| 17 | +struct IdHasher(u64); |
| 18 | + |
| 19 | +impl Hasher for IdHasher { |
| 20 | + fn write(&mut self, _: &[u8]) { |
| 21 | + unreachable!("TypeId calls write_u64"); |
| 22 | + } |
| 23 | + |
| 24 | + #[inline] |
| 25 | + fn write_u64(&mut self, id: u64) { |
| 26 | + self.0 = id; |
| 27 | + } |
| 28 | + |
| 29 | + #[inline] |
| 30 | + fn finish(&self) -> u64 { |
| 31 | + self.0 |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +/// A type map of protocol extensions. |
| 36 | +/// |
| 37 | +/// `Extensions` can be used by `Request` and `Response` to store |
| 38 | +/// extra data derived from the underlying protocol. |
| 39 | +#[derive(Default)] |
| 40 | +pub(crate) struct Extensions { |
| 41 | + // If extensions are never used, no need to carry around an empty HashMap. |
| 42 | + // That's 3 words. Instead, this is only 1 word. |
| 43 | + map: Option<Box<AnyMap>>, |
| 44 | +} |
| 45 | + |
| 46 | +#[allow(unused)] |
| 47 | +impl Extensions { |
| 48 | + /// Create an empty `Extensions`. |
| 49 | + #[inline] |
| 50 | + pub(crate) fn new() -> Extensions { |
| 51 | + Extensions { map: None } |
| 52 | + } |
| 53 | + |
| 54 | + /// Insert a type into this `Extensions`. |
| 55 | + /// |
| 56 | + /// If a extension of this type already existed, it will |
| 57 | + /// be returned. |
| 58 | + pub(crate) fn insert<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T> { |
| 59 | + self.map |
| 60 | + .get_or_insert_with(Box::default) |
| 61 | + .insert(TypeId::of::<T>(), Box::new(val)) |
| 62 | + .and_then(|boxed| { |
| 63 | + (boxed as Box<dyn Any + 'static>) |
| 64 | + .downcast() |
| 65 | + .ok() |
| 66 | + .map(|boxed| *boxed) |
| 67 | + }) |
| 68 | + } |
| 69 | + |
| 70 | + /// Get a reference to a type previously inserted on this `Extensions`. |
| 71 | + pub(crate) fn get<T: Send + Sync + 'static>(&self) -> Option<&T> { |
| 72 | + self.map |
| 73 | + .as_ref() |
| 74 | + .and_then(|map| map.get(&TypeId::of::<T>())) |
| 75 | + .and_then(|boxed| (&**boxed as &(dyn Any + 'static)).downcast_ref()) |
| 76 | + } |
| 77 | + |
| 78 | + /// Get a mutable reference to a type previously inserted on this `Extensions`. |
| 79 | + pub(crate) fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> { |
| 80 | + self.map |
| 81 | + .as_mut() |
| 82 | + .and_then(|map| map.get_mut(&TypeId::of::<T>())) |
| 83 | + .and_then(|boxed| (&mut **boxed as &mut (dyn Any + 'static)).downcast_mut()) |
| 84 | + } |
| 85 | + |
| 86 | + pub(crate) fn contains_key<T: Send + Sync + 'static>(&self) -> bool { |
| 87 | + self.map |
| 88 | + .as_ref() |
| 89 | + .map(|map| map.contains_key(&TypeId::of::<T>())) |
| 90 | + .unwrap_or_default() |
| 91 | + } |
| 92 | + |
| 93 | + /// Remove a type from this `Extensions`. |
| 94 | + /// |
| 95 | + /// If a extension of this type existed, it will be returned. |
| 96 | + pub(crate) fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T> { |
| 97 | + self.map |
| 98 | + .as_mut() |
| 99 | + .and_then(|map| map.remove(&TypeId::of::<T>())) |
| 100 | + .and_then(|boxed| { |
| 101 | + (boxed as Box<dyn Any + 'static>) |
| 102 | + .downcast() |
| 103 | + .ok() |
| 104 | + .map(|boxed| *boxed) |
| 105 | + }) |
| 106 | + } |
| 107 | + |
| 108 | + /// Clear the `Extensions` of all inserted extensions. |
| 109 | + #[inline] |
| 110 | + pub(crate) fn clear(&mut self) { |
| 111 | + if let Some(ref mut map) = self.map { |
| 112 | + map.clear(); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + /// Check whether the extension set is empty or not. |
| 117 | + #[inline] |
| 118 | + pub(crate) fn is_empty(&self) -> bool { |
| 119 | + self.map.as_ref().map_or(true, |map| map.is_empty()) |
| 120 | + } |
| 121 | + |
| 122 | + /// Get the numer of extensions available. |
| 123 | + #[inline] |
| 124 | + pub(crate) fn len(&self) -> usize { |
| 125 | + self.map.as_ref().map_or(0, |map| map.len()) |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +impl fmt::Debug for Extensions { |
| 130 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 131 | + f.debug_struct("Extensions").finish() |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +#[test] |
| 136 | +fn test_extensions() { |
| 137 | + #[derive(Debug, PartialEq)] |
| 138 | + struct MyType(i32); |
| 139 | + |
| 140 | + let mut extensions = Extensions::new(); |
| 141 | + |
| 142 | + extensions.insert(5i32); |
| 143 | + extensions.insert(MyType(10)); |
| 144 | + |
| 145 | + assert_eq!(extensions.get(), Some(&5i32)); |
| 146 | + assert_eq!(extensions.get_mut(), Some(&mut 5i32)); |
| 147 | + |
| 148 | + assert_eq!(extensions.remove::<i32>(), Some(5i32)); |
| 149 | + assert!(extensions.get::<i32>().is_none()); |
| 150 | + |
| 151 | + assert_eq!(extensions.get::<bool>(), None); |
| 152 | + assert_eq!(extensions.get(), Some(&MyType(10))); |
| 153 | +} |
0 commit comments