xref: /wasmtime-44.0.1/cranelift/entity/src/map.rs (revision bda02c19)
1 //! Densely numbered entity references as mapping keys.
2 
3 use crate::EntityRef;
4 use crate::iter::{Iter, IterMut};
5 use crate::keys::Keys;
6 use alloc::vec::Vec;
7 use core::cmp::min;
8 use core::fmt;
9 use core::marker::PhantomData;
10 use core::ops::{Index, IndexMut};
11 use core::slice;
12 #[cfg(feature = "enable-serde")]
13 use serde::{
14     Deserialize, Serialize,
15     de::{Deserializer, SeqAccess, Visitor},
16     ser::{SerializeSeq, Serializer},
17 };
18 use wasmtime_core::{alloc::PanicOnOom as _, error::OutOfMemory};
19 
20 /// A mapping `K -> V` for densely indexed entity references.
21 ///
22 /// The `SecondaryMap` data structure uses the dense index space to implement a map with a vector.
23 /// Unlike `PrimaryMap`, an `SecondaryMap` can't be used to allocate entity references. It is used
24 /// to associate secondary information with entities.
25 ///
26 /// The map does not track if an entry for a key has been inserted or not. Instead it behaves as if
27 /// all keys have a default entry from the beginning.
28 #[derive(Clone, Hash)]
29 pub struct SecondaryMap<K, V>
30 where
31     K: EntityRef,
32     V: Clone,
33 {
34     elems: Vec<V>,
35     default: V,
36     unused: PhantomData<K>,
37 }
38 
39 /// Shared `SecondaryMap` implementation for all value types.
40 impl<K, V> SecondaryMap<K, V>
41 where
42     K: EntityRef,
43     V: Clone,
44 {
45     /// Create a new empty map.
46     pub fn new() -> Self
47     where
48         V: Default,
49     {
50         Self {
51             elems: Vec::new(),
52             default: Default::default(),
53             unused: PhantomData,
54         }
55     }
56 
57     /// Create a new, empty map with the specified capacity.
58     ///
59     /// The map will be able to hold exactly `capacity` elements without reallocating.
60     pub fn with_capacity(capacity: usize) -> Self
61     where
62         V: Default,
63     {
64         Self {
65             elems: Vec::with_capacity(capacity),
66             default: Default::default(),
67             unused: PhantomData,
68         }
69     }
70 
71     /// Like `with_capacity` but returns an error on allocation failure.
72     pub fn try_with_capacity(capacity: usize) -> Result<Self, OutOfMemory>
73     where
74         V: Default,
75     {
76         let mut elems = Vec::new();
77         elems
78             .try_reserve(capacity)
79             .map_err(|_| OutOfMemory::new(core::mem::size_of::<V>().saturating_mul(capacity)))?;
80         Ok(Self {
81             elems,
82             default: Default::default(),
83             unused: PhantomData,
84         })
85     }
86 
87     /// Create a new empty map with a specified default value.
88     ///
89     /// This constructor does not require V to implement Default.
90     pub fn with_default(default: V) -> Self {
91         Self {
92             elems: Vec::new(),
93             default,
94             unused: PhantomData,
95         }
96     }
97 
98     /// Returns the number of elements the map can hold without reallocating.
99     pub fn capacity(&self) -> usize {
100         self.elems.capacity()
101     }
102 
103     /// Get the element at `k` if it exists.
104     #[inline(always)]
105     pub fn get(&self, k: K) -> Option<&V> {
106         self.elems.get(k.index())
107     }
108 
109     /// Get the element at `k` mutably, if it exists.
110     pub fn get_mut(&mut self, k: K) -> Option<&mut V> {
111         self.elems.get_mut(k.index())
112     }
113 
114     /// Insert the given key-value pair, returning the old value if it exists.
115     pub fn insert(&mut self, k: K, v: V) -> Option<V> {
116         self.try_insert(k, v).panic_on_oom()
117     }
118 
119     /// Like `insert` but returns an error on allocation failure.
120     pub fn try_insert(&mut self, k: K, v: V) -> Result<Option<V>, OutOfMemory> {
121         let i = k.index();
122         if i < self.elems.len() {
123             Ok(Some(core::mem::replace(&mut self.elems[i], v)))
124         } else {
125             self.try_resize(i + 1)?;
126             self.elems[i] = v;
127             Ok(None)
128         }
129     }
130 
131     /// Remove the element at `k`, if it exists, replacing it with the default
132     /// value.
133     pub fn remove(&mut self, k: K) -> Option<V> {
134         let i = k.index();
135         if i < self.elems.len() {
136             let default = self.default.clone();
137             Some(core::mem::replace(&mut self.elems[i], default))
138         } else {
139             None
140         }
141     }
142 
143     /// Is this map completely empty?
144     #[inline(always)]
145     pub fn is_empty(&self) -> bool {
146         self.elems.is_empty()
147     }
148 
149     /// Remove all entries from this map.
150     #[inline(always)]
151     pub fn clear(&mut self) {
152         self.elems.clear()
153     }
154 
155     /// Iterate over all the keys and values in this map.
156     pub fn iter(&self) -> Iter<'_, K, V> {
157         Iter::new(self.elems.iter())
158     }
159 
160     /// Iterate over all the keys and values in this map, mutable edition.
161     pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
162         IterMut::new(self.elems.iter_mut())
163     }
164 
165     /// Iterate over all the keys in this map.
166     pub fn keys(&self) -> Keys<K> {
167         Keys::with_len(self.elems.len())
168     }
169 
170     /// Iterate over all the values in this map.
171     pub fn values(&self) -> slice::Iter<'_, V> {
172         self.elems.iter()
173     }
174 
175     /// Iterate over all the values in this map, mutable edition.
176     pub fn values_mut(&mut self) -> slice::IterMut<'_, V> {
177         self.elems.iter_mut()
178     }
179 
180     /// Resize the map to have `n` entries by adding default entries as needed.
181     pub fn resize(&mut self, n: usize) {
182         self.elems.resize(n, self.default.clone());
183     }
184 
185     /// Like `resize` but returns an error on allocation failure.
186     pub fn try_resize(&mut self, n: usize) -> Result<(), OutOfMemory> {
187         if self.elems.capacity() < n {
188             self.elems
189                 .try_reserve(n - self.elems.len())
190                 .map_err(|_| OutOfMemory::new(core::mem::size_of::<V>().saturating_mul(n)))?;
191         }
192         debug_assert!(self.elems.capacity() >= n);
193         self.elems.resize(n, self.default.clone());
194         Ok(())
195     }
196 
197     /// Slow path for `index_mut` which resizes the vector.
198     #[cold]
199     fn resize_for_index_mut(&mut self, i: usize) -> &mut V {
200         self.elems.resize(i + 1, self.default.clone());
201         &mut self.elems[i]
202     }
203 }
204 
205 impl<K, V> Default for SecondaryMap<K, V>
206 where
207     K: EntityRef,
208     V: Clone + Default,
209 {
210     fn default() -> SecondaryMap<K, V> {
211         SecondaryMap::new()
212     }
213 }
214 
215 impl<K, V> From<Vec<V>> for SecondaryMap<K, V>
216 where
217     K: EntityRef,
218     V: Clone + Default,
219 {
220     fn from(elems: Vec<V>) -> Self {
221         let default = Default::default();
222         Self {
223             elems,
224             default,
225             unused: PhantomData,
226         }
227     }
228 }
229 
230 impl<K, V> FromIterator<(K, V)> for SecondaryMap<K, V>
231 where
232     K: EntityRef,
233     V: Clone + Default,
234 {
235     fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
236         let iter = iter.into_iter();
237         let (min, max) = iter.size_hint();
238         let cap = max.unwrap_or_else(|| 2 * min);
239         let mut map = Self::with_capacity(cap);
240         for (k, v) in iter {
241             map[k] = v;
242         }
243         map
244     }
245 }
246 
247 /// Immutable indexing into an `SecondaryMap`.
248 ///
249 /// All keys are permitted. Untouched entries have the default value.
250 impl<K, V> Index<K> for SecondaryMap<K, V>
251 where
252     K: EntityRef,
253     V: Clone,
254 {
255     type Output = V;
256 
257     #[inline(always)]
258     fn index(&self, k: K) -> &V {
259         self.elems.get(k.index()).unwrap_or(&self.default)
260     }
261 }
262 
263 /// Mutable indexing into an `SecondaryMap`.
264 ///
265 /// The map grows as needed to accommodate new keys.
266 impl<K, V> IndexMut<K> for SecondaryMap<K, V>
267 where
268     K: EntityRef,
269     V: Clone,
270 {
271     #[inline(always)]
272     fn index_mut(&mut self, k: K) -> &mut V {
273         let i = k.index();
274         if i >= self.elems.len() {
275             return self.resize_for_index_mut(i);
276         }
277         &mut self.elems[i]
278     }
279 }
280 
281 impl<K, V> PartialEq for SecondaryMap<K, V>
282 where
283     K: EntityRef,
284     V: Clone + PartialEq,
285 {
286     fn eq(&self, other: &Self) -> bool {
287         let min_size = min(self.elems.len(), other.elems.len());
288         self.default == other.default
289             && self.elems[..min_size] == other.elems[..min_size]
290             && self.elems[min_size..].iter().all(|e| *e == self.default)
291             && other.elems[min_size..].iter().all(|e| *e == other.default)
292     }
293 }
294 
295 impl<K, V> Eq for SecondaryMap<K, V>
296 where
297     K: EntityRef,
298     V: Clone + PartialEq + Eq,
299 {
300 }
301 
302 #[cfg(feature = "enable-serde")]
303 impl<K, V> Serialize for SecondaryMap<K, V>
304 where
305     K: EntityRef,
306     V: Clone + PartialEq + Serialize,
307 {
308     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
309     where
310         S: Serializer,
311     {
312         // TODO: bincode encodes option as "byte for Some/None" and then optionally the content
313         // TODO: we can actually optimize it by encoding manually bitmask, then elements
314         let mut elems_cnt = self.elems.len();
315         while elems_cnt > 0 && self.elems[elems_cnt - 1] == self.default {
316             elems_cnt -= 1;
317         }
318         let mut seq = serializer.serialize_seq(Some(1 + elems_cnt))?;
319         seq.serialize_element(&Some(self.default.clone()))?;
320         for e in self.elems.iter().take(elems_cnt) {
321             let some_e = Some(e);
322             seq.serialize_element(if *e == self.default { &None } else { &some_e })?;
323         }
324         seq.end()
325     }
326 }
327 
328 #[cfg(feature = "enable-serde")]
329 impl<'de, K, V> Deserialize<'de> for SecondaryMap<K, V>
330 where
331     K: EntityRef,
332     V: Clone + Deserialize<'de>,
333 {
334     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
335     where
336         D: Deserializer<'de>,
337     {
338         use alloc::fmt;
339         struct SecondaryMapVisitor<K, V> {
340             unused: PhantomData<fn(K) -> V>,
341         }
342 
343         impl<'de, K, V> Visitor<'de> for SecondaryMapVisitor<K, V>
344         where
345             K: EntityRef,
346             V: Clone + Deserialize<'de>,
347         {
348             type Value = SecondaryMap<K, V>;
349 
350             fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
351                 formatter.write_str("struct SecondaryMap")
352             }
353 
354             fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
355             where
356                 A: SeqAccess<'de>,
357             {
358                 match seq.next_element()? {
359                     Some(Some(default_val)) => {
360                         let default_val: V = default_val; // compiler can't infer the type
361                         let mut m = SecondaryMap::with_default(default_val.clone());
362                         let mut idx = 0;
363                         while let Some(val) = seq.next_element()? {
364                             let val: Option<_> = val; // compiler can't infer the type
365                             m[K::new(idx)] = val.unwrap_or_else(|| default_val.clone());
366                             idx += 1;
367                         }
368                         Ok(m)
369                     }
370                     _ => Err(serde::de::Error::custom("Default value required")),
371                 }
372             }
373         }
374 
375         deserializer.deserialize_seq(SecondaryMapVisitor {
376             unused: PhantomData {},
377         })
378     }
379 }
380 
381 impl<K: EntityRef + fmt::Debug, V: fmt::Debug + Clone> fmt::Debug for SecondaryMap<K, V> {
382     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383         f.debug_struct("SecondaryMap")
384             .field("elems", &self.elems)
385             .field("default", &self.default)
386             .finish()
387     }
388 }
389 
390 #[cfg(test)]
391 mod tests {
392     use super::*;
393 
394     // `EntityRef` impl for testing.
395     #[derive(Clone, Copy, Debug, PartialEq, Eq)]
396     struct E(u32);
397 
398     impl EntityRef for E {
399         fn new(i: usize) -> Self {
400             E(i as u32)
401         }
402         fn index(self) -> usize {
403             self.0 as usize
404         }
405     }
406 
407     #[test]
408     fn basic() {
409         let r0 = E(0);
410         let r1 = E(1);
411         let r2 = E(2);
412         let r3 = E(3);
413         let mut m = SecondaryMap::new();
414 
415         let v: Vec<E> = m.keys().collect();
416         assert_eq!(v, []);
417 
418         m[r2] = 3;
419         m[r1] = 5;
420 
421         assert_eq!(m[r1], 5);
422         assert_eq!(m[r2], 3);
423 
424         assert!(m.get(r3).is_none());
425         assert!(m.get_mut(r3).is_none());
426 
427         let old = m.insert(r3, 99);
428         assert!(old.is_none());
429         assert_eq!(m.get(r3), Some(&99));
430         assert_eq!(m[r3], 99);
431 
432         *m.get_mut(r3).unwrap() += 1;
433         assert_eq!(m.get(r3), Some(&100));
434         assert_eq!(m[r3], 100);
435 
436         let old = m.insert(r3, 42);
437         assert_eq!(old, Some(100));
438         assert_eq!(m.get(r3), Some(&42));
439         assert_eq!(m[r3], 42);
440 
441         let old = m.remove(r3);
442         assert_eq!(old, Some(42));
443         assert_eq!(m[r3], 0);
444         let old = m.remove(r3);
445         assert_eq!(old, Some(0));
446         m.resize(3);
447         let old = m.remove(r3);
448         assert_eq!(old, None);
449 
450         let v: Vec<E> = m.keys().collect();
451         assert_eq!(v, [r0, r1, r2]);
452 
453         let shared = &m;
454         assert_eq!(shared[r0], 0);
455         assert_eq!(shared[r1], 5);
456         assert_eq!(shared[r2], 3);
457     }
458 }
459