webparse/
extensions.rs

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