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