http1/common/
any_map.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
use std::{
    any::{Any, TypeId},
    collections::HashMap,
    fmt::Debug,
};

/// A map that holds data of any type.
#[derive(Default, Clone)]
pub struct AnyMap(HashMap<TypeId, Box<dyn CloneBox + Send + Sync>>);

impl AnyMap {
    /// Creates an empty `AnyMap`.
    pub fn new() -> Self {
        Default::default()
    }

    /// Returns the number of items in this map.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns `true` if this map is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns a reference of a value of type `T`.
    pub fn get<T>(&self) -> Option<&T>
    where
        T: Send + Sync + 'static,
    {
        self.0
            .get(&TypeId::of::<T>())
            .and_then(|x| (**x).as_any().downcast_ref())
    }

    /// Returns a mutable reference of a value of type `T`.
    pub fn get_mut<T>(&mut self) -> Option<&mut T>
    where
        T: Send + Sync + 'static,
    {
        self.0
            .get_mut(&TypeId::of::<T>())
            .and_then(|x| (**x).as_any_mut().downcast_mut())
    }

    /// Returns `true` if contains a value from the given type `T`.
    pub fn contains<T>(&self) -> bool
    where
        T: Send + Sync + 'static,
    {
        self.0.contains_key(&TypeId::of::<T>())
    }

    /// Inserts the given value.
    pub fn insert<T>(&mut self, value: T) -> Option<T>
    where
        T: Send + Clone + Sync + 'static,
    {
        self.0
            .insert(TypeId::of::<T>(), Box::new(value))
            .and_then(|x| x.into_any().downcast().ok())
            .map(|x| *x)
    }

    /// Removes the value of the given type.
    pub fn remove<T>(&mut self) -> Option<T>
    where
        T: Send + Sync + 'static,
    {
        self.0
            .remove(&TypeId::of::<T>())
            .and_then(|x| x.into_any().downcast().ok())
            .map(|x| *x)
    }

    /// Extend this type from other.
    pub fn extend(&mut self, other: AnyMap) {
        self.0.extend(other.0);
    }
}

impl Debug for AnyMap {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("AnyMap").finish()
    }
}

#[doc(hidden)]
pub trait CloneBox: Any {
    fn clone_box(&self) -> Box<dyn CloneBox + Send + Sync>;
    fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync>;
    fn as_any(&self) -> &dyn Any;
    fn as_any_mut(&mut self) -> &mut dyn Any;
}

impl<T> CloneBox for T
where
    T: Any + Clone + Send + Sync,
{
    fn clone_box(&self) -> Box<dyn CloneBox + Send + Sync> {
        Box::new(self.clone())
    }

    fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync> {
        self
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

impl Clone for Box<dyn CloneBox + Send + Sync> {
    fn clone(&self) -> Self {
        (**self).clone_box()
    }
}

#[cfg(test)]
mod tests {
    use super::AnyMap;

    #[test]
    fn test_any_map() {
        #[derive(Debug, Clone, PartialEq, Eq)]
        struct Sorcerer {
            name: &'static str,
        }

        let mut map = AnyMap::new();

        map.insert(Sorcerer {
            name: "Satoru Gojo",
        });
        map.insert(String::from("Infinite Void"));
        map.insert(2018_u32);
        map.insert((true, String::from("Nobara")));

        assert_eq!(map.len(), 4);
        assert!(map.contains::<Sorcerer>());
        assert!(!map.contains::<f32>());

        assert_eq!(
            map.get::<Sorcerer>().unwrap(),
            &Sorcerer {
                name: "Satoru Gojo"
            }
        );
        assert_eq!(map.get::<u32>().unwrap(), &2018);
        assert_eq!(map.get::<String>().unwrap(), "Infinite Void");
        assert_eq!(
            map.get::<(bool, String)>().unwrap(),
            &(true, String::from("Nobara"))
        );
        assert!(map.get::<Vec<u8>>().is_none());
    }
}