apalis_core/data.rs
1// Taken from https://github.com/hyperium/http
2// See repo for license
3use std::any::{Any, TypeId};
4use std::collections::HashMap;
5use std::fmt;
6use std::hash::{BuildHasherDefault, Hasher};
7
8use crate::error::Error;
9
10type AnyMap = HashMap<TypeId, Box<dyn AnyClone + Send + Sync>, BuildHasherDefault<IdHasher>>;
11
12// With TypeIds as keys, there's no need to hash them. They are already hashes
13// themselves, coming from the compiler. The IdHasher just holds the u64 of
14// the TypeId, and then returns it, instead of doing any bit fiddling.
15#[derive(Default)]
16struct IdHasher(u64);
17
18impl Hasher for IdHasher {
19 fn write(&mut self, _: &[u8]) {
20 unreachable!("TypeId calls write_u64");
21 }
22
23 #[inline]
24 fn write_u64(&mut self, id: u64) {
25 self.0 = id;
26 }
27
28 #[inline]
29 fn finish(&self) -> u64 {
30 self.0
31 }
32}
33
34/// A type map of protocol extensions.
35///
36/// `Extensions` can be used by `Request` and `Response` to store
37/// extra data derived from the underlying protocol.
38#[derive(Clone, Default)]
39pub struct Extensions {
40 // If extensions are never used, no need to carry around an empty HashMap.
41 // That's 3 words. Instead, this is only 1 word.
42 map: Option<Box<AnyMap>>,
43}
44
45impl Extensions {
46 /// Create an empty `Extensions`.
47 #[inline]
48 pub fn new() -> Extensions {
49 Extensions { map: None }
50 }
51
52 /// Insert a type into this `Extensions`.
53 ///
54 /// If a extension of this type already existed, it will
55 /// be returned.
56 ///
57 /// # Example
58 ///
59 /// ```
60 /// # use apalis_core::data::Extensions;
61 /// let mut ext = Extensions::new();
62 /// assert!(ext.insert(5i32).is_none());
63 /// assert!(ext.insert(4u8).is_none());
64 /// assert_eq!(ext.insert(9i32), Some(5i32));
65 /// ```
66 pub fn insert<T: Clone + Send + Sync + 'static>(&mut self, val: T) -> Option<T> {
67 self.map
68 .get_or_insert_with(Box::default)
69 .insert(TypeId::of::<T>(), Box::new(val))
70 .and_then(|boxed| boxed.into_any().downcast().ok().map(|boxed| *boxed))
71 }
72
73 /// Get a reference to a type previously inserted on this `Extensions`.
74 ///
75 /// # Example
76 ///
77 /// ```
78 /// # use apalis_core::data::Extensions;
79 /// let mut ext = Extensions::new();
80 /// assert!(ext.get::<i32>().is_none());
81 /// ext.insert(5i32);
82 ///
83 /// assert_eq!(ext.get::<i32>(), Some(&5i32));
84 /// ```
85 pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
86 self.map
87 .as_ref()
88 .and_then(|map| map.get(&TypeId::of::<T>()))
89 .and_then(|boxed| (**boxed).as_any().downcast_ref())
90 }
91
92 /// Get a checked reference to a type previously inserted on this `Extensions`.
93 ///
94 /// # Example
95 ///
96 /// ```
97 /// # use apalis_core::data::Extensions;
98 /// let mut ext = Extensions::new();
99 /// assert!(ext.get_checked::<i32>().is_err());
100 /// ext.insert(5i32);
101 ///
102 /// assert_eq!(ext.get_checked::<i32>(), Ok(&5i32));
103 /// ```
104 pub fn get_checked<T: Send + Sync + 'static>(&self) -> Result<&T, Error> {
105 self.get()
106 .ok_or({
107 let type_name = std::any::type_name::<T>();
108 Error::MissingData(
109 format!("Missing the an entry for `{type_name}`. Did you forget to add `.data(<{type_name}>)", ))
110 })
111 }
112
113 /// Get a mutable reference to a type previously inserted on this `Extensions`.
114 ///
115 /// # Example
116 ///
117 /// ```
118 /// # use apalis_core::data::Extensions;
119 /// let mut ext = Extensions::new();
120 /// ext.insert(String::from("Hello"));
121 /// ext.get_mut::<String>().unwrap().push_str(" World");
122 ///
123 /// assert_eq!(ext.get::<String>().unwrap(), "Hello World");
124 /// ```
125 pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
126 self.map
127 .as_mut()
128 .and_then(|map| map.get_mut(&TypeId::of::<T>()))
129 .and_then(|boxed| (**boxed).as_any_mut().downcast_mut())
130 }
131
132 /// Remove a type from this `Extensions`.
133 ///
134 /// If a extension of this type existed, it will be returned.
135 ///
136 /// # Example
137 ///
138 /// ```
139 /// # use apalis_core::data::Extensions;
140 /// let mut ext = Extensions::new();
141 /// ext.insert(5i32);
142 /// assert_eq!(ext.remove::<i32>(), Some(5i32));
143 /// assert!(ext.get::<i32>().is_none());
144 /// ```
145 pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T> {
146 self.map
147 .as_mut()
148 .and_then(|map| map.remove(&TypeId::of::<T>()))
149 .and_then(|boxed| boxed.into_any().downcast().ok().map(|boxed| *boxed))
150 }
151
152 /// Clear the `Extensions` of all inserted extensions.
153 ///
154 /// # Example
155 ///
156 /// ```
157 /// # use apalis_core::data::Extensions;
158 /// let mut ext = Extensions::new();
159 /// ext.insert(5i32);
160 /// ext.clear();
161 ///
162 /// assert!(ext.get::<i32>().is_none());
163 /// ```
164 #[inline]
165 pub fn clear(&mut self) {
166 if let Some(ref mut map) = self.map {
167 map.clear();
168 }
169 }
170
171 /// Check whether the extension set is empty or not.
172 ///
173 /// # Example
174 ///
175 /// ```
176 /// # use apalis_core::data::Extensions;
177 /// let mut ext = Extensions::new();
178 /// assert!(ext.is_empty());
179 /// ext.insert(5i32);
180 /// assert!(!ext.is_empty());
181 /// ```
182 #[inline]
183 pub fn is_empty(&self) -> bool {
184 self.map.as_ref().map_or(true, |map| map.is_empty())
185 }
186
187 /// Get the number of extensions available.
188 ///
189 /// # Example
190 ///
191 /// ```
192 /// # use apalis_core::data::Extensions;
193 /// let mut ext = Extensions::new();
194 /// assert_eq!(ext.len(), 0);
195 /// ext.insert(5i32);
196 /// assert_eq!(ext.len(), 1);
197 /// ```
198 #[inline]
199 pub fn len(&self) -> usize {
200 self.map.as_ref().map_or(0, |map| map.len())
201 }
202
203 /// Extends `self` with another `Extensions`.
204 ///
205 /// If an instance of a specific type exists in both, the one in `self` is overwritten with the
206 /// one from `other`.
207 ///
208 /// # Example
209 ///
210 /// ```
211 /// # use apalis_core::data::Extensions;
212 /// let mut ext_a = Extensions::new();
213 /// ext_a.insert(8u8);
214 /// ext_a.insert(16u16);
215 ///
216 /// let mut ext_b = Extensions::new();
217 /// ext_b.insert(4u8);
218 /// ext_b.insert("hello");
219 ///
220 /// ext_a.extend(ext_b);
221 /// assert_eq!(ext_a.len(), 3);
222 /// assert_eq!(ext_a.get::<u8>(), Some(&4u8));
223 /// assert_eq!(ext_a.get::<u16>(), Some(&16u16));
224 /// assert_eq!(ext_a.get::<&'static str>().copied(), Some("hello"));
225 /// ```
226 pub fn extend(&mut self, other: Self) {
227 if let Some(other) = other.map {
228 if let Some(map) = &mut self.map {
229 map.extend(*other);
230 } else {
231 self.map = Some(other);
232 }
233 }
234 }
235}
236
237impl fmt::Debug for Extensions {
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239 f.debug_struct("Extensions").finish()
240 }
241}
242
243trait AnyClone: Any {
244 fn clone_box(&self) -> Box<dyn AnyClone + Send + Sync>;
245 fn as_any(&self) -> &dyn Any;
246 fn as_any_mut(&mut self) -> &mut dyn Any;
247 fn into_any(self: Box<Self>) -> Box<dyn Any>;
248}
249
250impl<T: Clone + Send + Sync + 'static> AnyClone for T {
251 fn clone_box(&self) -> Box<dyn AnyClone + Send + Sync> {
252 Box::new(self.clone())
253 }
254
255 fn as_any(&self) -> &dyn Any {
256 self
257 }
258
259 fn as_any_mut(&mut self) -> &mut dyn Any {
260 self
261 }
262
263 fn into_any(self: Box<Self>) -> Box<dyn Any> {
264 self
265 }
266}
267
268impl Clone for Box<dyn AnyClone + Send + Sync> {
269 fn clone(&self) -> Self {
270 (**self).clone_box()
271 }
272}
273
274#[test]
275fn test_extensions() {
276 #[derive(Clone, Debug, PartialEq)]
277 struct MyType(i32);
278
279 let mut extensions = Extensions::new();
280
281 extensions.insert(5i32);
282 extensions.insert(MyType(10));
283
284 assert_eq!(extensions.get(), Some(&5i32));
285 assert_eq!(extensions.get_mut(), Some(&mut 5i32));
286
287 let ext2 = extensions.clone();
288
289 assert_eq!(extensions.remove::<i32>(), Some(5i32));
290 assert!(extensions.get::<i32>().is_none());
291
292 // clone still has it
293 assert_eq!(ext2.get(), Some(&5i32));
294 assert_eq!(ext2.get(), Some(&MyType(10)));
295
296 assert_eq!(extensions.get::<bool>(), None);
297 assert_eq!(extensions.get(), Some(&MyType(10)));
298}