http_types_rs/
extensions.rs1use std::any::{Any, TypeId};
6use std::collections::HashMap;
7use std::fmt;
8use std::hash::{BuildHasherDefault, Hasher};
9
10#[derive(Default)]
17pub struct Extensions {
18 map: Option<HashMap<TypeId, Box<dyn Any + Send + Sync>, BuildHasherDefault<IdHasher>>>,
19}
20
21impl Extensions {
22 #[inline]
24 pub fn new() -> Self {
25 Self { map: None }
26 }
27
28 pub fn insert<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T> {
32 self.map
33 .get_or_insert_with(Default::default)
34 .insert(TypeId::of::<T>(), Box::new(val))
35 .and_then(|boxed| (boxed as Box<dyn Any>).downcast().ok().map(|boxed| *boxed))
36 }
37
38 pub fn contains<T: 'static>(&self) -> bool {
40 self.map.as_ref().and_then(|m| m.get(&TypeId::of::<T>())).is_some()
41 }
42
43 pub fn get<T: 'static>(&self) -> Option<&T> {
45 self.map
46 .as_ref()
47 .and_then(|m| m.get(&TypeId::of::<T>()))
48 .and_then(|boxed| (&**boxed as &(dyn Any)).downcast_ref())
49 }
50
51 pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
53 self.map
54 .as_mut()
55 .and_then(|m| m.get_mut(&TypeId::of::<T>()))
56 .and_then(|boxed| (&mut **boxed as &mut (dyn Any)).downcast_mut())
57 }
58
59 pub fn remove<T: 'static>(&mut self) -> Option<T> {
63 self.map
64 .as_mut()
65 .and_then(|m| m.remove(&TypeId::of::<T>()))
66 .and_then(|boxed| (boxed as Box<dyn Any>).downcast().ok().map(|boxed| *boxed))
67 }
68
69 #[inline]
71 pub fn clear(&mut self) {
72 self.map = None;
73 }
74}
75
76impl fmt::Debug for Extensions {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 f.debug_struct("Extensions").finish()
79 }
80}
81
82#[derive(Default)]
84struct IdHasher(u64);
85
86impl Hasher for IdHasher {
87 fn write(&mut self, _: &[u8]) {
88 unreachable!("TypeId calls write_u64");
89 }
90
91 #[inline]
92 fn write_u64(&mut self, id: u64) {
93 self.0 = id;
94 }
95
96 #[inline]
97 fn finish(&self) -> u64 {
98 self.0
99 }
100}
101
102#[cfg(test)]
103mod tests {
104 use super::*;
105 #[test]
106 fn test_extensions() {
107 #[derive(Debug, PartialEq)]
108 struct MyType(i32);
109
110 let mut map = Extensions::new();
111
112 map.insert(5i32);
113 map.insert(MyType(10));
114
115 assert_eq!(map.get(), Some(&5i32));
116 assert_eq!(map.get_mut(), Some(&mut 5i32));
117
118 assert_eq!(map.remove::<i32>(), Some(5i32));
119 assert!(map.get::<i32>().is_none());
120
121 assert_eq!(map.get::<bool>(), None);
122 assert_eq!(map.get(), Some(&MyType(10)));
123 }
124}