]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_data_structures/src/vec_map.rs
Rollup merge of #93732 - lcnr:hrlt-backcompa, r=Mark-Simulacrum
[rust.git] / compiler / rustc_data_structures / src / vec_map.rs
1 use std::borrow::Borrow;
2 use std::fmt::Debug;
3 use std::iter::FromIterator;
4 use std::slice::Iter;
5 use std::vec::IntoIter;
6
7 use crate::stable_hasher::{HashStable, StableHasher};
8
9 /// A map type implemented as a vector of pairs `K` (key) and `V` (value).
10 /// It currently provides a subset of all the map operations, the rest could be added as needed.
11 #[derive(Clone, Encodable, Decodable, Debug)]
12 pub struct VecMap<K, V>(Vec<(K, V)>);
13
14 impl<K, V> VecMap<K, V>
15 where
16     K: Debug + PartialEq,
17     V: Debug,
18 {
19     pub fn new() -> Self {
20         VecMap(Default::default())
21     }
22
23     /// Sets the value of the entry, and returns the entry's old value.
24     pub fn insert(&mut self, k: K, v: V) -> Option<V> {
25         if let Some(elem) = self.0.iter_mut().find(|(key, _)| *key == k) {
26             Some(std::mem::replace(&mut elem.1, v))
27         } else {
28             self.0.push((k, v));
29             None
30         }
31     }
32
33     /// Removes the entry from the map and returns the removed value
34     pub fn remove(&mut self, k: &K) -> Option<V> {
35         self.0.iter().position(|(k2, _)| k2 == k).map(|pos| self.0.remove(pos).1)
36     }
37
38     /// Gets a reference to the value in the entry.
39     pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
40     where
41         K: Borrow<Q>,
42         Q: Eq,
43     {
44         self.0.iter().find(|(key, _)| k == key.borrow()).map(|elem| &elem.1)
45     }
46
47     /// Gets a mutable reference to the value in the entry.
48     pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
49     where
50         K: Borrow<Q>,
51         Q: Eq,
52     {
53         self.0.iter_mut().find(|(key, _)| k == key.borrow()).map(|elem| &mut elem.1)
54     }
55
56     /// Returns the any value corresponding to the supplied predicate filter.
57     ///
58     /// The supplied predicate will be applied to each (key, value) pair and it will return a
59     /// reference to the values where the predicate returns `true`.
60     pub fn any_value_matching(&self, mut predicate: impl FnMut(&(K, V)) -> bool) -> Option<&V> {
61         self.0.iter().find(|kv| predicate(kv)).map(|elem| &elem.1)
62     }
63
64     /// Returns the value corresponding to the supplied predicate filter. It crashes if there's
65     /// more than one matching element.
66     ///
67     /// The supplied predicate will be applied to each (key, value) pair and it will return a
68     /// reference to the value where the predicate returns `true`.
69     pub fn get_value_matching(&self, mut predicate: impl FnMut(&(K, V)) -> bool) -> Option<&V> {
70         let mut filter = self.0.iter().filter(|kv| predicate(kv));
71         let (_, value) = filter.next()?;
72         // This should return just one element, otherwise it's a bug
73         assert!(
74             filter.next().is_none(),
75             "Collection {:#?} should have just one matching element",
76             self
77         );
78         Some(value)
79     }
80
81     /// Returns `true` if the map contains a value for the specified key.
82     ///
83     /// The key may be any borrowed form of the map's key type,
84     /// [`Eq`] on the borrowed form *must* match those for
85     /// the key type.
86     pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
87     where
88         K: Borrow<Q>,
89         Q: Eq,
90     {
91         self.get(k).is_some()
92     }
93
94     /// Returns `true` if the map contains no elements.
95     pub fn is_empty(&self) -> bool {
96         self.0.is_empty()
97     }
98
99     pub fn iter(&self) -> Iter<'_, (K, V)> {
100         self.into_iter()
101     }
102
103     pub fn iter_mut(&mut self) -> impl Iterator<Item = (&K, &mut V)> {
104         self.into_iter()
105     }
106
107     pub fn retain(&mut self, f: impl Fn(&(K, V)) -> bool) {
108         self.0.retain(f)
109     }
110 }
111
112 impl<K, V> Default for VecMap<K, V> {
113     #[inline]
114     fn default() -> Self {
115         Self(Default::default())
116     }
117 }
118
119 impl<K, V> From<Vec<(K, V)>> for VecMap<K, V> {
120     fn from(vec: Vec<(K, V)>) -> Self {
121         Self(vec)
122     }
123 }
124
125 impl<K, V> Into<Vec<(K, V)>> for VecMap<K, V> {
126     fn into(self) -> Vec<(K, V)> {
127         self.0
128     }
129 }
130
131 impl<K, V> FromIterator<(K, V)> for VecMap<K, V> {
132     fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
133         Self(iter.into_iter().collect())
134     }
135 }
136
137 impl<'a, K, V> IntoIterator for &'a VecMap<K, V> {
138     type Item = &'a (K, V);
139     type IntoIter = Iter<'a, (K, V)>;
140
141     #[inline]
142     fn into_iter(self) -> Self::IntoIter {
143         self.0.iter()
144     }
145 }
146
147 impl<'a, K, V> IntoIterator for &'a mut VecMap<K, V> {
148     type Item = (&'a K, &'a mut V);
149     type IntoIter = impl Iterator<Item = Self::Item>;
150
151     #[inline]
152     fn into_iter(self) -> Self::IntoIter {
153         self.0.iter_mut().map(|(k, v)| (&*k, v))
154     }
155 }
156
157 impl<K, V> IntoIterator for VecMap<K, V> {
158     type Item = (K, V);
159     type IntoIter = IntoIter<(K, V)>;
160
161     #[inline]
162     fn into_iter(self) -> Self::IntoIter {
163         self.0.into_iter()
164     }
165 }
166
167 impl<K: PartialEq + Debug, V: Debug> Extend<(K, V)> for VecMap<K, V> {
168     fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
169         for (k, v) in iter {
170             self.insert(k, v);
171         }
172     }
173
174     fn extend_one(&mut self, (k, v): (K, V)) {
175         self.insert(k, v);
176     }
177
178     fn extend_reserve(&mut self, additional: usize) {
179         self.0.extend_reserve(additional);
180     }
181 }
182
183 impl<K, V, CTX> HashStable<CTX> for VecMap<K, V>
184 where
185     K: HashStable<CTX> + Eq,
186     V: HashStable<CTX>,
187 {
188     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
189         self.0.hash_stable(hcx, hasher)
190     }
191 }
192
193 #[cfg(test)]
194 mod tests;