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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
//! Polymorphic data store (collection)

// TODO: support other collection types? If so, we can support `no_std` too.

#![cfg_attr(doc_cfg, feature(doc_cfg))]

use std::any::{Any, TypeId};
use std::collections::hash_map as std_hm;
use std::hash::{BuildHasher, Hash};
use std::marker::PhantomData;
use std::ops::Deref;
pub use std_hm::Keys;

/// Polymorphic hash map
///
/// Internally this uses a `HashMap` with boxed values, thus performance is
/// much like that of `HashMap`.
///
/// Note: [`HashMap`]'s capacity reservation API is excluded. There is no
/// fundamental reason for this, other than each stored value requiring an
/// allocation (boxing) anyway.
///
/// # Warning
///
/// **Warning:** values stored in the map will not have their destructor
/// ([`Drop::drop`]) run when the map is destroyed. This is not currently
/// fixable (`min_specialization` +
/// <https://github.com/rust-lang/rust/issues/46893> may be sufficient).
#[derive(Debug)]
pub struct HashMap<K, S>(std_hm::HashMap<K, Box<dyn Any>, S>);

/// Polymorphic hash map using fxhash hasher
#[cfg_attr(doc_cfg, doc(cfg(feature = "fxhash")))]
#[cfg(feature = "fxhash")]
pub type FxHashMap<K> = HashMap<K, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>;

impl<K, S: Default> Default for HashMap<K, S> {
    fn default() -> Self {
        HashMap::with_hasher(Default::default())
    }
}

/// Typed key used to access elements
pub struct TaggedKey<K, V>(pub K, PhantomData<V>);
impl<K, V> TaggedKey<K, V> {
    /// Construct from a `key`
    pub fn new(key: K) -> Self {
        TaggedKey(key, Default::default())
    }
}
impl<K, V> Deref for TaggedKey<K, V> {
    type Target = K;
    fn deref(&self) -> &K {
        &self.0
    }
}

impl<K> HashMap<K, std_hm::RandomState> {
    /// Construct a new store
    pub fn new() -> Self {
        Default::default()
    }
}

impl<K, S> HashMap<K, S> {
    /// Construct a new store with the given hash bulider
    pub fn with_hasher(hash_builder: S) -> Self {
        HashMap(std_hm::HashMap::with_hasher(hash_builder))
    }

    /// Return's a reference to the map's [`BuildHasher`]
    pub fn hasher(&self) -> &S {
        self.0.hasher()
    }

    /// Returns an iterator over all keys in arbitrary order
    ///
    /// These are *not* tagged keys; only the bare key is stored.
    pub fn keys(&self) -> Keys<K, Box<dyn Any>> {
        self.0.keys()
    }

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

    /// Returns true if the store contains no elements
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Clears the store, removing all elements
    pub fn clear(&mut self) {
        self.0.clear();
    }
}

impl<K: Eq + Hash, S: BuildHasher> HashMap<K, S> {
    /// Checks whether a value matching the specified `key` exists
    pub fn contains_key(&self, key: &K) -> bool {
        self.0.contains_key(key)
    }

    /// Get the [`TypeId`] of a stored value
    pub fn get_type_id(&self, key: &K) -> Option<TypeId> {
        self.0.get(key).map(|v| v.type_id())
    }

    /// Returns a reference to the value corresponding to the key
    ///
    /// The value's type is inferred from the [`TaggedKey`].
    ///
    /// Returns `None` if no element matches `tag` or if the type `V` does not match the element.
    pub fn get_tagged<V: 'static>(&self, key: &TaggedKey<K, V>) -> Option<&V> {
        self.get::<V>(key)
    }

    /// Returns a reference to the value corresponding to the key
    ///
    /// The value's type must be specified explicitly.
    ///
    /// Returns `None` if no element matches `key`. Panics on type mismatch.
    pub fn get<V: 'static>(&self, key: &K) -> Option<&V> {
        self.0.get(key).and_then(|v| v.downcast_ref())
    }

    /// Returns a mutable reference to the value corresponding to the key
    pub fn get_tagged_mut<V: 'static>(&mut self, key: &TaggedKey<K, V>) -> Option<&mut V> {
        self.get_mut::<V>(key)
    }

    /// Returns a mutable reference to the value corresponding to the key
    ///
    /// Returns `None` if no element matches `key`. Panics on type mismatch.
    pub fn get_mut<V: 'static>(&mut self, key: &K) -> Option<&mut V> {
        self.0.get_mut(key).and_then(|v| v.downcast_mut())
    }

    /// Inserts a key-value pair into the store
    ///
    /// Returns the corresponding [`TaggedKey`] for convenience.
    ///
    /// Unlike [`HashMap`] this does not return any displaced old value since
    /// the type of any such value is unknown.
    #[inline]
    pub fn insert<V: 'static>(&mut self, key: K, value: V) -> TaggedKey<K, V>
    where
        K: Clone,
    {
        self.insert_boxed(key, Box::new(value))
    }

    /// Inserts a key and boxed value pair
    ///
    /// Returns the corresponding [`TaggedKey`] for convenience.
    ///
    /// Unlike [`HashMap`] this does not return any displaced old value since
    /// the type of any such value is unknown.
    pub fn insert_boxed<V: 'static>(&mut self, key: K, value: Box<V>) -> TaggedKey<K, V>
    where
        K: Clone,
    {
        self.0.insert(key.clone(), value);
        TaggedKey::new(key)
    }

    /// Removes and returns a value, if present
    ///
    /// Panics on type mismatch.
    pub fn remove<V: 'static>(&mut self, key: &TaggedKey<K, V>) -> Option<V> {
        self.remove_boxed(key).map(|v| *v)
    }

    /// Removes and returns a value, if present
    ///
    /// Panics on type mismatch.
    pub fn remove_boxed<V: 'static>(&mut self, key: &TaggedKey<K, V>) -> Option<Box<V>> {
        self.0.remove(key).and_then(|v| v.downcast().ok())
    }

    /// Get `key`'s entry for in-place manipulation
    pub fn entry<V: 'static>(&mut self, key: K) -> Entry<K, V> {
        match self.0.entry(key) {
            std_hm::Entry::Occupied(entry) => {
                Entry::Occupied(OccupiedEntry(entry, Default::default()))
            }
            std_hm::Entry::Vacant(entry) => Entry::Vacant(VacantEntry(entry, Default::default())),
        }
    }
}

/// A view into a single entry in a map
pub enum Entry<'a, K: 'a, V: 'static> {
    Occupied(OccupiedEntry<'a, K, V>),
    Vacant(VacantEntry<'a, K, V>),
}

impl<'a, K: 'a, V: 'static> Entry<'a, K, V> {
    /// Ensure a value exists and return its reference
    pub fn or_insert(self, default: V) -> &'a mut V {
        match self {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => entry.insert(default),
        }
    }

    /// Ensure a value exists and return its reference
    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
        match self {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => entry.insert(default()),
        }
    }
}

/// An occupied entry
pub struct OccupiedEntry<'a, K: 'a, V: 'static>(
    std_hm::OccupiedEntry<'a, K, Box<dyn Any>>,
    PhantomData<V>,
);
impl<'a, K: 'a, V: 'static> OccupiedEntry<'a, K, V> {
    /// Get the entry
    ///
    /// Panics on type mismatch.
    pub fn get(&self) -> &V {
        self.0.get().downcast_ref().unwrap()
    }

    /// Get the entry, mutably
    ///
    /// Panics on type mismatch.
    pub fn get_mut(&mut self) -> &mut V {
        self.0.get_mut().downcast_mut().unwrap()
    }

    /// Convert into a mutable reference
    ///
    /// Panics on type mismatch.
    pub fn into_mut(self) -> &'a mut V {
        self.0.into_mut().downcast_mut().unwrap()
    }

    /// Sets the value of the entry
    pub fn insert(&mut self, value: V) -> Box<dyn Any> {
        self.0.insert(Box::new(value))
    }

    /// Removes and returns the entry's value
    ///
    /// Panics on type mismatch.
    pub fn remove_boxed(self) -> Box<V> {
        self.0.remove().downcast().unwrap()
    }
}

/// A vacant entry
pub struct VacantEntry<'a, K: 'a, V: 'static>(
    std_hm::VacantEntry<'a, K, Box<dyn Any>>,
    PhantomData<V>,
);
impl<'a, K: 'a, V: 'static> VacantEntry<'a, K, V> {
    /// Sets the value of the entry and returns a mutable reference to it
    pub fn insert(self, value: V) -> &'a mut V {
        let v = self.0.insert(Box::new(value));
        v.downcast_mut().unwrap()
    }
}

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

    #[test]
    fn insert_and_access() {
        let mut store = HashMap::new();

        let k1 = store.insert(1, "A static str");
        if let Some(v) = store.get_mut(&k1) {
            *v = "another str";
        }
        assert_eq!(store.get_tagged(&k1), Some(&"another str"));

        let k2 = store.insert(2, "A String".to_string());
        assert_eq!(store.get_tagged(&k2), Some(&"A String".to_string()));

        assert!(store.contains_key(&k1));
        assert!(store.contains_key(&1));
        assert!(!store.contains_key(&3));
    }

    #[test]
    fn zero_sized() {
        let mut store = HashMap::new();
        let k = store.insert(1, ());
        assert_eq!(store.get_tagged(&k), Some(&()));
    }

    #[test]
    fn untyped_keys() {
        let mut store = HashMap::new();
        store.insert(1, ());
        assert_eq!(store.get(&1), Some(&()));
    }

    #[test]
    #[should_panic]
    fn incorrect_untyped_keys() {
        let mut store = HashMap::new();
        store.insert(1, ());
        assert_eq!(store.get(&1), Some(&1));
    }

    #[test]
    fn entry_api() {
        let mut store = HashMap::new();
        let k = 1;
        *store.entry(k).or_insert(0) = 10;
        assert_eq!(store.get(&k), Some(&10));

        *store.entry(k).or_insert(0) = 20;
        assert_eq!(store.get(&k), Some(&20));
    }
}