blueprint_core/
extensions.rs

1use alloc::boxed::Box;
2use core::any::{Any, TypeId};
3use core::fmt;
4use core::hash::{BuildHasherDefault, Hasher};
5use hashbrown::HashMap;
6
7type AnyMap = HashMap<TypeId, Box<dyn AnyClone + Send + Sync>, BuildHasherDefault<IdHasher>>;
8
9// With TypeIds as keys, there's no need to hash them. They are already hashes
10// themselves, coming from the compiler. The IdHasher just holds the u64 of
11// the TypeId, and then returns it, instead of doing any bit fiddling.
12#[derive(Default)]
13struct IdHasher(u64);
14
15impl Hasher for IdHasher {
16    #[inline]
17    fn finish(&self) -> u64 {
18        self.0
19    }
20
21    fn write(&mut self, _: &[u8]) {
22        unreachable!("TypeId calls write_u64");
23    }
24
25    #[inline]
26    fn write_u64(&mut self, id: u64) {
27        self.0 = id;
28    }
29}
30
31/// A type map of protocol extensions.
32///
33/// `Extensions` can be used by [`JobCall`] and [`JobResult`] to store
34/// extra data derived from the underlying protocol.
35///
36/// [`JobCall`]: crate::job::call::JobCall
37/// [`JobResult`]: crate::job::result::JobResult
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 an extension of this type already exists, it will
55    /// be returned and replaced with the new one.
56    ///
57    /// # Example
58    ///
59    /// ```
60    /// use blueprint_sdk::extensions::Extensions;
61    ///
62    /// let mut ext = Extensions::new();
63    /// assert!(ext.insert(5i32).is_none());
64    /// assert!(ext.insert(4u8).is_none());
65    /// assert_eq!(ext.insert(9i32), Some(5i32));
66    /// ```
67    pub fn insert<T: Clone + Send + Sync + 'static>(&mut self, val: T) -> Option<T> {
68        self.map
69            .get_or_insert_with(Box::default)
70            .insert(TypeId::of::<T>(), Box::new(val))
71            .and_then(|boxed| boxed.into_any().downcast().ok().map(|boxed| *boxed))
72    }
73
74    /// Get a reference to a type previously inserted on this `Extensions`.
75    ///
76    /// # Example
77    ///
78    /// ```
79    /// use blueprint_sdk::extensions::Extensions;
80    ///
81    /// let mut ext = Extensions::new();
82    /// assert!(ext.get::<i32>().is_none());
83    /// ext.insert(5i32);
84    ///
85    /// assert_eq!(ext.get::<i32>(), Some(&5i32));
86    /// ```
87    pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
88        self.map
89            .as_ref()
90            .and_then(|map| map.get(&TypeId::of::<T>()))
91            .and_then(|boxed| (**boxed).as_any().downcast_ref())
92    }
93
94    /// Get a mutable reference to a type previously inserted on this `Extensions`.
95    ///
96    /// # Example
97    ///
98    /// ```
99    /// use blueprint_sdk::extensions::Extensions;
100    ///
101    /// let mut ext = Extensions::new();
102    /// ext.insert(String::from("Hello"));
103    /// ext.get_mut::<String>().unwrap().push_str(" World");
104    ///
105    /// assert_eq!(ext.get::<String>().unwrap(), "Hello World");
106    /// ```
107    pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
108        self.map
109            .as_mut()
110            .and_then(|map| map.get_mut(&TypeId::of::<T>()))
111            .and_then(|boxed| (**boxed).as_any_mut().downcast_mut())
112    }
113
114    /// Get a mutable reference to a type, inserting `value` if not already present on this
115    /// `Extensions`.
116    ///
117    /// # Example
118    ///
119    /// ```
120    /// use blueprint_sdk::extensions::Extensions;
121    ///
122    /// let mut ext = Extensions::new();
123    /// *ext.get_or_insert(1i32) += 2;
124    ///
125    /// assert_eq!(*ext.get::<i32>().unwrap(), 3);
126    /// ```
127    pub fn get_or_insert<T: Clone + Send + Sync + 'static>(&mut self, value: T) -> &mut T {
128        self.get_or_insert_with(|| value)
129    }
130
131    /// Get a mutable reference to a type, inserting the value created by `f` if not already present
132    /// on this `Extensions`.
133    ///
134    /// # Example
135    ///
136    /// ```
137    /// use blueprint_sdk::extensions::Extensions;
138    ///
139    /// let mut ext = Extensions::new();
140    /// *ext.get_or_insert_with(|| 1i32) += 2;
141    ///
142    /// assert_eq!(*ext.get::<i32>().unwrap(), 3);
143    /// ```
144    pub fn get_or_insert_with<T: Clone + Send + Sync + 'static, F: FnOnce() -> T>(
145        &mut self,
146        f: F,
147    ) -> &mut T {
148        let out = self
149            .map
150            .get_or_insert_with(Box::default)
151            .entry(TypeId::of::<T>())
152            .or_insert_with(|| Box::new(f()));
153        (**out).as_any_mut().downcast_mut().unwrap()
154    }
155
156    /// Get a mutable reference to a type, inserting the type's default value if not already present
157    /// on this `Extensions`.
158    ///
159    /// # Example
160    ///
161    /// ```
162    /// use blueprint_sdk::extensions::Extensions;
163    ///
164    /// let mut ext = Extensions::new();
165    /// *ext.get_or_insert_default::<i32>() += 2;
166    ///
167    /// assert_eq!(*ext.get::<i32>().unwrap(), 2);
168    /// ```
169    pub fn get_or_insert_default<T: Default + Clone + Send + Sync + 'static>(&mut self) -> &mut T {
170        self.get_or_insert_with(T::default)
171    }
172
173    /// Remove a type from this `Extensions`.
174    ///
175    /// If a extension of this type existed, it will be returned.
176    ///
177    /// # Example
178    ///
179    /// ```
180    /// use blueprint_sdk::extensions::Extensions;
181    ///
182    /// let mut ext = Extensions::new();
183    /// ext.insert(5i32);
184    /// assert_eq!(ext.remove::<i32>(), Some(5i32));
185    /// assert!(ext.get::<i32>().is_none());
186    /// ```
187    pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T> {
188        self.map
189            .as_mut()
190            .and_then(|map| map.remove(&TypeId::of::<T>()))
191            .and_then(|boxed| boxed.into_any().downcast().ok().map(|boxed| *boxed))
192    }
193
194    /// Clear the `Extensions` of all inserted extensions.
195    ///
196    /// # Example
197    ///
198    /// ```
199    /// use blueprint_sdk::extensions::Extensions;
200    ///
201    /// let mut ext = Extensions::new();
202    /// ext.insert(5i32);
203    /// ext.clear();
204    ///
205    /// assert!(ext.get::<i32>().is_none());
206    /// ```
207    #[inline]
208    pub fn clear(&mut self) {
209        if let Some(ref mut map) = self.map {
210            map.clear();
211        }
212    }
213
214    /// Check whether the extension set is empty or not.
215    ///
216    /// # Example
217    ///
218    /// ```
219    /// use blueprint_sdk::extensions::Extensions;
220    ///
221    /// let mut ext = Extensions::new();
222    /// assert!(ext.is_empty());
223    /// ext.insert(5i32);
224    /// assert!(!ext.is_empty());
225    /// ```
226    #[inline]
227    pub fn is_empty(&self) -> bool {
228        self.map.as_ref().is_none_or(|map| map.is_empty())
229    }
230
231    /// Get the number of extensions available.
232    ///
233    /// # Example
234    ///
235    /// ```
236    /// use blueprint_sdk::extensions::Extensions;
237    ///
238    /// let mut ext = Extensions::new();
239    /// assert_eq!(ext.len(), 0);
240    /// ext.insert(5i32);
241    /// assert_eq!(ext.len(), 1);
242    /// ```
243    #[inline]
244    pub fn len(&self) -> usize {
245        self.map.as_ref().map_or(0, |map| map.len())
246    }
247
248    /// Extends `self` with another `Extensions`.
249    ///
250    /// If an instance of a specific type exists in both, the one in `self` is overwritten with the
251    /// one from `other`.
252    ///
253    /// # Example
254    ///
255    /// ```
256    /// use blueprint_sdk::extensions::Extensions;
257    ///
258    /// let mut ext_a = Extensions::new();
259    /// ext_a.insert(8u8);
260    /// ext_a.insert(16u16);
261    ///
262    /// let mut ext_b = Extensions::new();
263    /// ext_b.insert(4u8);
264    /// ext_b.insert("hello");
265    ///
266    /// ext_a.extend(ext_b);
267    /// assert_eq!(ext_a.len(), 3);
268    /// assert_eq!(ext_a.get::<u8>(), Some(&4u8));
269    /// assert_eq!(ext_a.get::<u16>(), Some(&16u16));
270    /// assert_eq!(ext_a.get::<&'static str>().copied(), Some("hello"));
271    /// ```
272    pub fn extend(&mut self, other: Self) {
273        if let Some(other) = other.map {
274            if let Some(map) = &mut self.map {
275                map.extend(*other);
276            } else {
277                self.map = Some(other);
278            }
279        }
280    }
281}
282
283impl fmt::Debug for Extensions {
284    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285        f.debug_struct("Extensions").finish()
286    }
287}
288
289trait AnyClone: Any {
290    fn clone_box(&self) -> Box<dyn AnyClone + Send + Sync>;
291    fn as_any(&self) -> &dyn Any;
292    fn as_any_mut(&mut self) -> &mut dyn Any;
293    fn into_any(self: Box<Self>) -> Box<dyn Any>;
294}
295
296impl<T: Clone + Send + Sync + 'static> AnyClone for T {
297    fn clone_box(&self) -> Box<dyn AnyClone + Send + Sync> {
298        Box::new(self.clone())
299    }
300
301    fn as_any(&self) -> &dyn Any {
302        self
303    }
304
305    fn as_any_mut(&mut self) -> &mut dyn Any {
306        self
307    }
308
309    fn into_any(self: Box<Self>) -> Box<dyn Any> {
310        self
311    }
312}
313
314impl Clone for Box<dyn AnyClone + Send + Sync> {
315    fn clone(&self) -> Self {
316        (**self).clone_box()
317    }
318}
319
320#[test]
321fn test_extensions() {
322    #[derive(Clone, Debug, PartialEq)]
323    struct MyType(i32);
324
325    let mut extensions = Extensions::new();
326
327    extensions.insert(5i32);
328    extensions.insert(MyType(10));
329
330    assert_eq!(extensions.get(), Some(&5i32));
331    assert_eq!(extensions.get_mut(), Some(&mut 5i32));
332
333    let ext2 = extensions.clone();
334
335    assert_eq!(extensions.remove::<i32>(), Some(5i32));
336    assert!(extensions.get::<i32>().is_none());
337
338    // clone still has it
339    assert_eq!(ext2.get(), Some(&5i32));
340    assert_eq!(ext2.get(), Some(&MyType(10)));
341
342    assert_eq!(extensions.get::<bool>(), None);
343    assert_eq!(extensions.get(), Some(&MyType(10)));
344}