defuse_map_utils/
lib.rs

1mod btree_map;
2pub mod cleanup;
3mod hash_map;
4mod iter;
5#[cfg(feature = "near")]
6mod near;
7
8pub use self::iter::*;
9
10pub trait Map {
11    type K;
12    type V;
13
14    type VacantEntry<'a>: VacantEntry<'a, K = Self::K, V = Self::V>
15    where
16        Self: 'a;
17    type OccupiedEntry<'a>: OccupiedEntry<'a, K = Self::K, V = Self::V>
18    where
19        Self: 'a;
20
21    fn contains_key(&self, k: &Self::K) -> bool;
22    fn get(&self, k: &Self::K) -> Option<&Self::V>;
23    fn get_mut(&mut self, k: &Self::K) -> Option<&mut Self::V>;
24    fn insert(&mut self, k: Self::K, v: Self::V) -> Option<Self::V>;
25    fn entry(&mut self, k: Self::K) -> Entry<Self::VacantEntry<'_>, Self::OccupiedEntry<'_>>;
26    fn remove(&mut self, k: &Self::K) -> Option<Self::V>;
27}
28
29#[derive(Debug)]
30pub enum Entry<V, O> {
31    Vacant(V),
32    Occupied(O),
33}
34
35impl<'a, V, O> Entry<V, O>
36where
37    V: VacantEntry<'a>,
38    O: OccupiedEntry<'a, K = V::K, V = V::V>,
39{
40    #[inline]
41    pub fn key(&self) -> &V::K {
42        match self {
43            Self::Vacant(entry) => entry.key(),
44            Self::Occupied(entry) => entry.key(),
45        }
46    }
47
48    #[inline]
49    pub fn or_default(self) -> &'a mut V::V
50    where
51        V::V: Default,
52    {
53        self.or_insert_with(Default::default)
54    }
55
56    #[inline]
57    pub fn or_insert(self, default: V::V) -> &'a mut V::V {
58        self.or_insert_with(|| default)
59    }
60
61    #[inline]
62    pub fn or_insert_with(self, default: impl FnOnce() -> V::V) -> &'a mut V::V {
63        self.or_insert_with_key(|_| default())
64    }
65
66    #[inline]
67    pub fn or_insert_with_key(self, default: impl FnOnce(&V::K) -> V::V) -> &'a mut V::V {
68        match self {
69            Self::Vacant(entry) => {
70                let v = default(entry.key());
71                entry.insert(v)
72            }
73            Self::Occupied(entry) => entry.into_mut(),
74        }
75    }
76
77    #[must_use]
78    #[inline]
79    pub fn and_modify(mut self, f: impl FnOnce(&mut V::V)) -> Self {
80        if let Self::Occupied(ref mut entry) = self {
81            f(entry.get_mut());
82        }
83        self
84    }
85}
86
87pub trait VacantEntry<'a> {
88    type K;
89    type V;
90
91    fn key(&self) -> &Self::K;
92    fn into_key(self) -> Self::K;
93    fn insert(self, v: Self::V) -> &'a mut Self::V;
94}
95
96pub trait OccupiedEntry<'a> {
97    type K;
98    type V;
99
100    fn key(&self) -> &Self::K;
101    fn get(&self) -> &Self::V;
102    fn get_mut(&mut self) -> &mut Self::V;
103    fn into_mut(self) -> &'a mut Self::V;
104    fn insert(&mut self, v: Self::V) -> Self::V;
105    fn remove(self) -> Self::V;
106}