vecmap/map/
mutable_keys.rs

1use super::{Entries, IterMut2, KeysMut, Slot, VecMap};
2use core::borrow::Borrow;
3
4/// Opt-in mutable access to keys.
5///
6/// These methods expose `&mut K`, mutable references to the key as it is stored in the map.
7///
8/// You are allowed to modify the keys in the map **as long as the modified key does not compare
9/// equal to another key already in the map**.
10///
11/// If keys are modified erroneously, you are no longer able to look up values for duplicate keys
12/// directly. This is sound (memory safe) but a logical error hazard (just like implementing
13/// `PartialEq`, `Eq`, or `Hash` incorrectly would be).
14///
15/// This trait is sealed and cannot be implemented for types outside this crate.
16pub trait MutableKeys: private::Sealed {
17    /// The map's key type.
18    type Key;
19
20    /// The map's value type.
21    type Value;
22
23    /// Return the index, a mutable reference to the key and a mutable reference to the value
24    /// stored for `key`, if it is present, else `None`.
25    ///
26    /// # Examples
27    ///
28    /// ```
29    /// use vecmap::map::{MutableKeys, VecMap};
30    ///
31    /// let mut map = VecMap::new();
32    /// map.insert(1, "a");
33    ///
34    /// if let Some((_, k, v)) = map.get_full_mut2(&1) {
35    ///     *k = 2;
36    ///     *v = "b";
37    /// }
38    /// assert_eq!(map.get(&1), None);
39    /// assert_eq!(map.get(&2), Some(&"b"));
40    /// ```
41    fn get_full_mut2<Q>(&mut self, key: &Q) -> Option<(usize, &mut Self::Key, &mut Self::Value)>
42    where
43        Self::Key: Borrow<Q>,
44        Q: Eq + ?Sized;
45
46    /// Return a mutable reference to the key and a mutable reference to the value stored at
47    /// `index`, if it is present, else `None`.
48    ///
49    /// # Examples
50    ///
51    /// ```
52    /// use vecmap::map::{MutableKeys, VecMap};
53    ///
54    /// let mut map = VecMap::new();
55    /// map.insert(1, "a");
56    /// if let Some((k, v)) = map.get_index_mut2(0) {
57    ///     *k = 2;
58    ///     *v = "b";
59    /// }
60    /// assert_eq!(map[0], "b");
61    /// assert_eq!(map.get(&1), None);
62    /// assert_eq!(map.get(&2), Some(&"b"));
63    /// ```
64    fn get_index_mut2(&mut self, index: usize) -> Option<(&mut Self::Key, &mut Self::Value)>;
65
66    /// Retains only the elements specified by the predicate.
67    ///
68    /// In other words, remove all pairs `(k, v)` for which `f(&mut k, &mut v)` returns `false`.
69    ///
70    /// # Examples
71    ///
72    /// ```
73    /// use vecmap::map::{MutableKeys, VecMap};
74    ///
75    /// let mut map: VecMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
76    /// map.retain2(|k, v| {
77    ///     std::mem::swap(k, v);  
78    ///     *v % 2 == 0
79    /// });
80    /// assert_eq!(map.len(), 4);
81    /// assert_eq!(map, VecMap::from([(0, 0), (20, 2), (40, 4), (60, 6)]));
82    /// ```
83    fn retain2<F>(&mut self, f: F)
84    where
85        F: FnMut(&mut Self::Key, &mut Self::Value) -> bool;
86
87    /// An iterator visiting all key-value pairs in insertion order, with mutable references to the
88    /// values. The iterator element type is `(&'a mut K, &'a mut V)`.
89    ///
90    /// # Examples
91    ///
92    /// ```
93    /// use vecmap::map::{MutableKeys, VecMap};
94    ///
95    /// let mut map = VecMap::from([
96    ///     ('a', 1),
97    ///     ('b', 2),
98    ///     ('c', 3),
99    /// ]);
100    ///
101    /// // Update all values
102    /// for (key, val) in map.iter_mut2() {
103    ///     *key = key.to_ascii_uppercase();
104    ///     *val *= 2;
105    /// }
106    ///
107    /// assert_eq!(map, VecMap::from([('A', 2), ('B', 4), ('C', 6)]));
108    /// ```
109    fn iter_mut2(&mut self) -> IterMut2<'_, Self::Key, Self::Value>;
110
111    /// An iterator visiting all keys mutably in insertion order. The iterator element type is `&'a
112    /// mut K`.
113    ///
114    /// # Examples
115    ///
116    /// ```
117    /// use vecmap::map::{MutableKeys, VecMap};
118    ///
119    /// let mut map = VecMap::from([
120    ///     (1, "a"),
121    ///     (2, "b"),
122    ///     (3, "c"),
123    /// ]);
124    ///
125    /// for key in map.keys_mut() {
126    ///     *key = *key * 10;
127    /// }
128    ///
129    /// assert_eq!(map, VecMap::from([(10, "a"), (20, "b"), (30, "c")]));
130    /// ```
131    fn keys_mut(&mut self) -> KeysMut<'_, Self::Key, Self::Value>;
132}
133
134impl<K, V> MutableKeys for VecMap<K, V> {
135    type Key = K;
136    type Value = V;
137
138    fn get_full_mut2<Q>(&mut self, key: &Q) -> Option<(usize, &mut K, &mut V)>
139    where
140        K: Borrow<Q>,
141        Q: Eq + ?Sized,
142    {
143        self.get_index_of(key).map(|index| {
144            let (key, value) = self.base[index].muts();
145            (index, key, value)
146        })
147    }
148
149    fn get_index_mut2(&mut self, index: usize) -> Option<(&mut K, &mut V)> {
150        self.base.get_mut(index).map(Slot::muts)
151    }
152
153    fn retain2<F>(&mut self, mut f: F)
154    where
155        F: FnMut(&mut K, &mut V) -> bool,
156    {
157        self.base.retain_mut(|slot| {
158            let (key, value) = slot.muts();
159            f(key, value)
160        });
161    }
162
163    fn iter_mut2(&mut self) -> IterMut2<'_, K, V> {
164        IterMut2::new(self.as_entries_mut())
165    }
166
167    fn keys_mut(&mut self) -> KeysMut<'_, K, V> {
168        KeysMut::new(self.as_entries_mut())
169    }
170}
171
172mod private {
173    pub trait Sealed {}
174
175    impl<K, V> Sealed for super::VecMap<K, V> {}
176}