generational_cache/map/
mod.rs1pub trait Map<K, V> {
5 type Error: core::fmt::Debug;
7
8 fn insert(&mut self, key: K, value: V) -> Result<Option<V>, Self::Error>;
10
11 fn get(&self, key: &K) -> Option<&V>;
13
14 fn get_mut(&mut self, key: &K) -> Option<&mut V>;
16
17 fn remove(&mut self, key: &K) -> Option<V>;
19
20 fn clear(&mut self) -> Result<(), Self::Error>;
22
23 fn is_empty(&self) -> bool;
25
26 fn capacity(&self) -> Option<usize>;
28
29 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}