generational_cache/map/
mod.rs

1//! Module providing abstractions to implement maps.
2
3/// An abstract mapping from a set of keys to a set of values.
4pub trait Map<K, V> {
5    /// Associated error type.
6    type Error: core::fmt::Debug;
7
8    /// Inserts a new key/value pair into this map.
9    fn insert(&mut self, key: K, value: V) -> Result<Option<V>, Self::Error>;
10
11    /// Returns an immutable reference to the value associated with the given key.
12    fn get(&self, key: &K) -> Option<&V>;
13
14    /// Returns a mutable reference to the value associated with the given key.
15    fn get_mut(&mut self, key: &K) -> Option<&mut V>;
16
17    /// Removes the key/value pair associated with the given key from this map.
18    fn remove(&mut self, key: &K) -> Option<V>;
19
20    /// Removes all key/value pairs stored in this map.
21    fn clear(&mut self) -> Result<(), Self::Error>;
22
23    /// Returns whether this map is empty.
24    fn is_empty(&self) -> bool;
25
26    /// Returns the number of key/value pairs this map is capable of storing.
27    fn capacity(&self) -> Option<usize>;
28
29    /// Rethrns the number of key/value pairs currently stored in this map.
30    fn len(&self) -> usize;
31}
32
33pub mod impls;
34
35#[doc(hidden)]
36pub mod tests {
37    use super::Map;
38
39    pub fn _test_map_consistency<M: Map<usize, usize> + Default>() {
40        let mut map = M::default();
41
42        map.clear().unwrap();
43
44        assert!(map.is_empty());
45
46        let num_entries: usize = map.capacity().unwrap_or(10);
47
48        for i in 0..num_entries {
49            assert!(map.insert(i, i).unwrap().is_none());
50        }
51
52        for i in 0..num_entries {
53            assert_eq!(map.get(&i), Some(&i));
54        }
55
56        for i in 0..num_entries {
57            let val = map.get_mut(&i);
58
59            if let Some(val) = val {
60                *val += 1;
61            }
62        }
63
64        for i in 0..num_entries {
65            assert_eq!(map.get(&i), Some(&(i + 1)));
66        }
67
68        assert_eq!(map.insert(0, num_entries).unwrap(), Some(1));
69        assert_eq!(map.get(&0), Some(&num_entries));
70
71        assert_eq!(map.len(), num_entries);
72
73        if let Some(capacity) = map.capacity() {
74            assert_eq!(capacity, map.len());
75        }
76
77        if let (Some(_), Ok(_)) = (map.capacity(), map.insert(num_entries, num_entries)) {
78            unreachable!("No error on capacity breach.")
79        }
80
81        assert_eq!(map.remove(&0), Some(num_entries));
82
83        assert!(map.get(&0).is_none());
84
85        map.clear().unwrap();
86        assert!(map.is_empty());
87    }
88}