xref: /wasmtime-44.0.1/cranelift/entity/src/map.rs (revision 416691c8)
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.
new() -> Self where V: Default,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.
with_capacity(capacity: usize) -> Self where V: Default,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.
try_with_capacity(capacity: usize) -> Result<Self, OutOfMemory> where V: Default,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.
with_default(default: V) -> Self90     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.
capacity(&self) -> usize99     pub fn capacity(&self) -> usize {
100         self.elems.capacity()
101     }
102 
103     /// Get the element at `k` if it exists.
104     #[inline(always)]
get(&self, k: K) -> Option<&V>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.
get_mut(&mut self, k: K) -> Option<&mut V>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.
insert(&mut self, k: K, v: V) -> Option<V>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.
try_insert(&mut self, k: K, v: V) -> Result<Option<V>, OutOfMemory>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.
remove(&mut self, k: K) -> Option<V>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)]
is_empty(&self) -> bool145     pub fn is_empty(&self) -> bool {
146         self.elems.is_empty()
147     }
148 
149     /// Remove all entries from this map.
150     #[inline(always)]
clear(&mut self)151     pub fn clear(&mut self) {
152         self.elems.clear()
153     }
154 
155     /// Iterate over all the keys and values in this map.
iter(&self) -> Iter<'_, K, V>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.
iter_mut(&mut self) -> IterMut<'_, K, V>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.
keys(&self) -> Keys<K>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.
values(&self) -> slice::Iter<'_, V>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.
values_mut(&mut self) -> slice::IterMut<'_, V>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.
resize(&mut self, n: usize)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.
try_resize(&mut self, n: usize) -> Result<(), OutOfMemory>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     /// Get this map's underlying values as a slice.
as_values_slice(&self) -> &[V]198     pub fn as_values_slice(&self) -> &[V] {
199         &self.elems
200     }
201 
202     /// Get this map's default value.
default_value(&self) -> &V203     pub fn default_value(&self) -> &V {
204         &self.default
205     }
206 
207     /// Slow path for `index_mut` which resizes the vector.
208     #[cold]
resize_for_index_mut(&mut self, i: usize) -> &mut V209     fn resize_for_index_mut(&mut self, i: usize) -> &mut V {
210         self.elems.resize(i + 1, self.default.clone());
211         &mut self.elems[i]
212     }
213 }
214 
215 impl<K, V> Default for SecondaryMap<K, V>
216 where
217     K: EntityRef,
218     V: Clone + Default,
219 {
default() -> SecondaryMap<K, V>220     fn default() -> SecondaryMap<K, V> {
221         SecondaryMap::new()
222     }
223 }
224 
225 impl<K, V> From<Vec<V>> for SecondaryMap<K, V>
226 where
227     K: EntityRef,
228     V: Clone + Default,
229 {
from(elems: Vec<V>) -> Self230     fn from(elems: Vec<V>) -> Self {
231         let default = Default::default();
232         Self {
233             elems,
234             default,
235             unused: PhantomData,
236         }
237     }
238 }
239 
240 impl<K, V> FromIterator<(K, V)> for SecondaryMap<K, V>
241 where
242     K: EntityRef,
243     V: Clone + Default,
244 {
from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self245     fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
246         let iter = iter.into_iter();
247         let (min, max) = iter.size_hint();
248         let cap = max.unwrap_or_else(|| 2 * min);
249         let mut map = Self::with_capacity(cap);
250         for (k, v) in iter {
251             map[k] = v;
252         }
253         map
254     }
255 }
256 
257 /// Immutable indexing into an `SecondaryMap`.
258 ///
259 /// All keys are permitted. Untouched entries have the default value.
260 impl<K, V> Index<K> for SecondaryMap<K, V>
261 where
262     K: EntityRef,
263     V: Clone,
264 {
265     type Output = V;
266 
267     #[inline(always)]
index(&self, k: K) -> &V268     fn index(&self, k: K) -> &V {
269         self.elems.get(k.index()).unwrap_or(&self.default)
270     }
271 }
272 
273 /// Mutable indexing into an `SecondaryMap`.
274 ///
275 /// The map grows as needed to accommodate new keys.
276 impl<K, V> IndexMut<K> for SecondaryMap<K, V>
277 where
278     K: EntityRef,
279     V: Clone,
280 {
281     #[inline(always)]
index_mut(&mut self, k: K) -> &mut V282     fn index_mut(&mut self, k: K) -> &mut V {
283         let i = k.index();
284         if i >= self.elems.len() {
285             return self.resize_for_index_mut(i);
286         }
287         &mut self.elems[i]
288     }
289 }
290 
291 impl<K, V> PartialEq for SecondaryMap<K, V>
292 where
293     K: EntityRef,
294     V: Clone + PartialEq,
295 {
eq(&self, other: &Self) -> bool296     fn eq(&self, other: &Self) -> bool {
297         let min_size = min(self.elems.len(), other.elems.len());
298         self.default == other.default
299             && self.elems[..min_size] == other.elems[..min_size]
300             && self.elems[min_size..].iter().all(|e| *e == self.default)
301             && other.elems[min_size..].iter().all(|e| *e == other.default)
302     }
303 }
304 
305 impl<K, V> Eq for SecondaryMap<K, V>
306 where
307     K: EntityRef,
308     V: Clone + PartialEq + Eq,
309 {
310 }
311 
312 #[cfg(feature = "enable-serde")]
313 impl<K, V> Serialize for SecondaryMap<K, V>
314 where
315     K: EntityRef,
316     V: Clone + PartialEq + Serialize,
317 {
serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer,318     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
319     where
320         S: Serializer,
321     {
322         // TODO: bincode encodes option as "byte for Some/None" and then optionally the content
323         // TODO: we can actually optimize it by encoding manually bitmask, then elements
324         let mut elems_cnt = self.elems.len();
325         while elems_cnt > 0 && self.elems[elems_cnt - 1] == self.default {
326             elems_cnt -= 1;
327         }
328         let mut seq = serializer.serialize_seq(Some(1 + elems_cnt))?;
329         seq.serialize_element(&Some(self.default.clone()))?;
330         for e in self.elems.iter().take(elems_cnt) {
331             let some_e = Some(e);
332             seq.serialize_element(if *e == self.default { &None } else { &some_e })?;
333         }
334         seq.end()
335     }
336 }
337 
338 #[cfg(feature = "enable-serde")]
339 impl<'de, K, V> Deserialize<'de> for SecondaryMap<K, V>
340 where
341     K: EntityRef,
342     V: Clone + Deserialize<'de>,
343 {
deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,344     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
345     where
346         D: Deserializer<'de>,
347     {
348         use alloc::fmt;
349         struct SecondaryMapVisitor<K, V> {
350             unused: PhantomData<fn(K) -> V>,
351         }
352 
353         impl<'de, K, V> Visitor<'de> for SecondaryMapVisitor<K, V>
354         where
355             K: EntityRef,
356             V: Clone + Deserialize<'de>,
357         {
358             type Value = SecondaryMap<K, V>;
359 
360             fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
361                 formatter.write_str("struct SecondaryMap")
362             }
363 
364             fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
365             where
366                 A: SeqAccess<'de>,
367             {
368                 match seq.next_element()? {
369                     Some(Some(default_val)) => {
370                         let default_val: V = default_val; // compiler can't infer the type
371                         let mut m = SecondaryMap::with_default(default_val.clone());
372                         let mut idx = 0;
373                         while let Some(val) = seq.next_element()? {
374                             let val: Option<_> = val; // compiler can't infer the type
375                             m[K::new(idx)] = val.unwrap_or_else(|| default_val.clone());
376                             idx += 1;
377                         }
378                         Ok(m)
379                     }
380                     _ => Err(serde::de::Error::custom("Default value required")),
381                 }
382             }
383         }
384 
385         deserializer.deserialize_seq(SecondaryMapVisitor {
386             unused: PhantomData {},
387         })
388     }
389 }
390 
391 impl<K: EntityRef + fmt::Debug, V: fmt::Debug + Clone> fmt::Debug for SecondaryMap<K, V> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result392     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393         f.debug_struct("SecondaryMap")
394             .field("elems", &self.elems)
395             .field("default", &self.default)
396             .finish()
397     }
398 }
399 
400 #[cfg(test)]
401 mod tests {
402     use super::*;
403 
404     // `EntityRef` impl for testing.
405     #[derive(Clone, Copy, Debug, PartialEq, Eq)]
406     struct E(u32);
407 
408     impl EntityRef for E {
new(i: usize) -> Self409         fn new(i: usize) -> Self {
410             E(i as u32)
411         }
index(self) -> usize412         fn index(self) -> usize {
413             self.0 as usize
414         }
415     }
416 
417     #[test]
basic()418     fn basic() {
419         let r0 = E(0);
420         let r1 = E(1);
421         let r2 = E(2);
422         let r3 = E(3);
423         let mut m = SecondaryMap::new();
424 
425         let v: Vec<E> = m.keys().collect();
426         assert_eq!(v, []);
427 
428         m[r2] = 3;
429         m[r1] = 5;
430 
431         assert_eq!(m[r1], 5);
432         assert_eq!(m[r2], 3);
433 
434         assert!(m.get(r3).is_none());
435         assert!(m.get_mut(r3).is_none());
436 
437         let old = m.insert(r3, 99);
438         assert!(old.is_none());
439         assert_eq!(m.get(r3), Some(&99));
440         assert_eq!(m[r3], 99);
441 
442         *m.get_mut(r3).unwrap() += 1;
443         assert_eq!(m.get(r3), Some(&100));
444         assert_eq!(m[r3], 100);
445 
446         let old = m.insert(r3, 42);
447         assert_eq!(old, Some(100));
448         assert_eq!(m.get(r3), Some(&42));
449         assert_eq!(m[r3], 42);
450 
451         let old = m.remove(r3);
452         assert_eq!(old, Some(42));
453         assert_eq!(m[r3], 0);
454         let old = m.remove(r3);
455         assert_eq!(old, Some(0));
456         m.resize(3);
457         let old = m.remove(r3);
458         assert_eq!(old, None);
459 
460         let v: Vec<E> = m.keys().collect();
461         assert_eq!(v, [r0, r1, r2]);
462 
463         let shared = &m;
464         assert_eq!(shared[r0], 0);
465         assert_eq!(shared[r1], 5);
466         assert_eq!(shared[r2], 3);
467     }
468 }
469