wasmer_types/entity/
secondary_map.rs

1// This file contains code from external sources.
2// Attributions: https://github.com/wasmerio/wasmer/blob/main/docs/ATTRIBUTIONS.md
3
4//! Densely numbered entity references as mapping keys.
5
6use crate::entity::iter::{Iter, IterMut};
7use crate::entity::keys::Keys;
8use crate::entity::EntityRef;
9use crate::lib::std::cmp::min;
10use crate::lib::std::marker::PhantomData;
11use crate::lib::std::ops::{Index, IndexMut};
12use crate::lib::std::slice;
13use crate::lib::std::vec::Vec;
14use rkyv::{Archive, Archived, Deserialize as RkyvDeserialize, Serialize as RkyvSerialize};
15#[cfg(feature = "enable-serde")]
16use serde::{
17    de::{Deserializer, SeqAccess, Visitor},
18    ser::{SerializeSeq, Serializer},
19    Deserialize, Serialize,
20};
21
22/// A mapping `K -> V` for densely indexed entity references.
23///
24/// The `SecondaryMap` data structure uses the dense index space to implement a map with a vector.
25/// Unlike `PrimaryMap`, an `SecondaryMap` can't be used to allocate entity references. It is used
26/// to associate secondary information with entities.
27///
28/// The map does not track if an entry for a key has been inserted or not. Instead it behaves as if
29/// all keys have a default entry from the beginning.
30#[derive(Debug, Clone, RkyvSerialize, RkyvDeserialize, Archive)]
31pub struct SecondaryMap<K, V>
32where
33    K: EntityRef,
34    V: Clone,
35{
36    pub(crate) elems: Vec<V>,
37    pub(crate) default: V,
38    pub(crate) unused: PhantomData<K>,
39}
40
41#[cfg(feature = "artifact-size")]
42impl<K, V> loupe::MemoryUsage for SecondaryMap<K, V>
43where
44    K: EntityRef,
45    V: Clone + loupe::MemoryUsage,
46{
47    fn size_of_val(&self, tracker: &mut dyn loupe::MemoryUsageTracker) -> usize {
48        std::mem::size_of_val(self)
49            + self
50                .elems
51                .iter()
52                .map(|value| value.size_of_val(tracker) - std::mem::size_of_val(value))
53                .sum::<usize>()
54    }
55}
56
57/// Shared `SecondaryMap` implementation for all value types.
58impl<K, V> SecondaryMap<K, V>
59where
60    K: EntityRef,
61    V: Clone,
62{
63    /// Create a new empty map.
64    pub fn new() -> Self
65    where
66        V: Default,
67    {
68        Self {
69            elems: Vec::new(),
70            default: Default::default(),
71            unused: PhantomData,
72        }
73    }
74
75    /// Create a new, empty map with the specified capacity.
76    ///
77    /// The map will be able to hold exactly `capacity` elements without reallocating.
78    pub fn with_capacity(capacity: usize) -> Self
79    where
80        V: Default,
81    {
82        Self {
83            elems: Vec::with_capacity(capacity),
84            default: Default::default(),
85            unused: PhantomData,
86        }
87    }
88
89    /// Create a new empty map with a specified default value.
90    ///
91    /// This constructor does not require V to implement Default.
92    pub fn with_default(default: V) -> Self {
93        Self {
94            elems: Vec::new(),
95            default,
96            unused: PhantomData,
97        }
98    }
99
100    /// Returns the number of elements the map can hold without reallocating.
101    pub fn capacity(&self) -> usize {
102        self.elems.capacity()
103    }
104
105    /// Get the element at `k` if it exists.
106    #[inline(always)]
107    pub fn get(&self, k: K) -> Option<&V> {
108        self.elems.get(k.index())
109    }
110
111    /// Is this map completely empty?
112    #[inline(always)]
113    pub fn is_empty(&self) -> bool {
114        self.elems.is_empty()
115    }
116
117    /// Remove all entries from this map.
118    #[inline(always)]
119    pub fn clear(&mut self) {
120        self.elems.clear()
121    }
122
123    /// Iterate over all the keys and values in this map.
124    pub fn iter(&self) -> Iter<K, V> {
125        Iter::new(self.elems.iter())
126    }
127
128    /// Iterate over all the keys and values in this map, mutable edition.
129    pub fn iter_mut(&mut self) -> IterMut<K, V> {
130        IterMut::new(self.elems.iter_mut())
131    }
132
133    /// Iterate over all the keys in this map.
134    pub fn keys(&self) -> Keys<K> {
135        Keys::with_len(self.elems.len())
136    }
137
138    /// Iterate over all the values in this map.
139    pub fn values(&self) -> slice::Iter<V> {
140        self.elems.iter()
141    }
142
143    /// Iterate over all the values in this map, mutable edition.
144    pub fn values_mut(&mut self) -> slice::IterMut<V> {
145        self.elems.iter_mut()
146    }
147
148    /// Resize the map to have `n` entries by adding default entries as needed.
149    pub fn resize(&mut self, n: usize) {
150        self.elems.resize(n, self.default.clone());
151    }
152}
153
154impl<K, V> ArchivedSecondaryMap<K, V>
155where
156    K: EntityRef,
157    V: Archive + Clone,
158{
159    /// Get the element at `k` if it exists.
160    pub fn get(&self, k: K) -> Option<&V::Archived> {
161        self.elems.get(k.index())
162    }
163
164    /// Iterator over all values in the `ArchivedPrimaryMap`
165    pub fn values(&self) -> slice::Iter<Archived<V>> {
166        self.elems.iter()
167    }
168
169    /// Iterate over all the keys and values in this map.
170    pub fn iter(&self) -> Iter<K, Archived<V>> {
171        Iter::new(self.elems.iter())
172    }
173}
174
175impl<K, V> std::fmt::Debug for ArchivedSecondaryMap<K, V>
176where
177    K: EntityRef + std::fmt::Debug,
178    V: Archive + Clone,
179    V::Archived: std::fmt::Debug,
180{
181    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182        f.debug_map().entries(self.iter()).finish()
183    }
184}
185
186impl<K, V> Default for SecondaryMap<K, V>
187where
188    K: EntityRef,
189    V: Clone + Default,
190{
191    fn default() -> Self {
192        Self::new()
193    }
194}
195
196/// Immutable indexing into an `SecondaryMap`.
197///
198/// All keys are permitted. Untouched entries have the default value.
199impl<K, V> Index<K> for SecondaryMap<K, V>
200where
201    K: EntityRef,
202    V: Clone,
203{
204    type Output = V;
205
206    #[inline(always)]
207    fn index(&self, k: K) -> &V {
208        self.elems.get(k.index()).unwrap_or(&self.default)
209    }
210}
211
212/// Mutable indexing into an `SecondaryMap`.
213///
214/// The map grows as needed to accommodate new keys.
215impl<K, V> IndexMut<K> for SecondaryMap<K, V>
216where
217    K: EntityRef,
218    V: Clone,
219{
220    #[inline(always)]
221    fn index_mut(&mut self, k: K) -> &mut V {
222        let i = k.index();
223        if i >= self.elems.len() {
224            self.elems.resize(i + 1, self.default.clone());
225        }
226        &mut self.elems[i]
227    }
228}
229
230impl<K, V> PartialEq for SecondaryMap<K, V>
231where
232    K: EntityRef,
233    V: Clone + PartialEq,
234{
235    fn eq(&self, other: &Self) -> bool {
236        let min_size = min(self.elems.len(), other.elems.len());
237        self.default == other.default
238            && self.elems[..min_size] == other.elems[..min_size]
239            && self.elems[min_size..].iter().all(|e| *e == self.default)
240            && other.elems[min_size..].iter().all(|e| *e == other.default)
241    }
242}
243
244impl<K, V> Eq for SecondaryMap<K, V>
245where
246    K: EntityRef,
247    V: Clone + PartialEq + Eq,
248{
249}
250
251#[cfg(feature = "enable-serde")]
252impl<K, V> Serialize for SecondaryMap<K, V>
253where
254    K: EntityRef,
255    V: Clone + PartialEq + Serialize,
256{
257    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
258    where
259        S: Serializer,
260    {
261        // TODO: bincode encodes option as "byte for Some/None" and then optionally the content
262        // TODO: we can actually optimize it by encoding manually bitmask, then elements
263        let mut elems_cnt = self.elems.len();
264        while elems_cnt > 0 && self.elems[elems_cnt - 1] == self.default {
265            elems_cnt -= 1;
266        }
267        let mut seq = serializer.serialize_seq(Some(1 + elems_cnt))?;
268        seq.serialize_element(&Some(self.default.clone()))?;
269        for e in self.elems.iter().take(elems_cnt) {
270            let some_e = Some(e);
271            seq.serialize_element(if *e == self.default { &None } else { &some_e })?;
272        }
273        seq.end()
274    }
275}
276
277#[cfg(feature = "enable-serde")]
278impl<'de, K, V> Deserialize<'de> for SecondaryMap<K, V>
279where
280    K: EntityRef,
281    V: Clone + Deserialize<'de>,
282{
283    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
284    where
285        D: Deserializer<'de>,
286    {
287        use crate::lib::std::fmt;
288
289        struct SecondaryMapVisitor<K, V> {
290            unused: PhantomData<fn(K) -> V>,
291        }
292
293        impl<'de, K, V> Visitor<'de> for SecondaryMapVisitor<K, V>
294        where
295            K: EntityRef,
296            V: Clone + Deserialize<'de>,
297        {
298            type Value = SecondaryMap<K, V>;
299
300            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
301                formatter.write_str("struct SecondaryMap")
302            }
303
304            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
305            where
306                A: SeqAccess<'de>,
307            {
308                match seq.next_element()? {
309                    Some(Some(default_val)) => {
310                        let default_val: V = default_val; // compiler can't infer the type
311                        let mut m = SecondaryMap::with_default(default_val.clone());
312                        let mut idx = 0;
313                        while let Some(val) = seq.next_element()? {
314                            let val: Option<_> = val; // compiler can't infer the type
315                            m[K::new(idx)] = val.unwrap_or_else(|| default_val.clone());
316                            idx += 1;
317                        }
318                        Ok(m)
319                    }
320                    _ => Err(serde::de::Error::custom("Default value required")),
321                }
322            }
323        }
324
325        deserializer.deserialize_seq(SecondaryMapVisitor {
326            unused: PhantomData {},
327        })
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    // `EntityRef` impl for testing.
336    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
337    struct E(u32);
338
339    impl EntityRef for E {
340        fn new(i: usize) -> Self {
341            Self(i as u32)
342        }
343        fn index(self) -> usize {
344            self.0 as usize
345        }
346    }
347
348    #[test]
349    fn basic() {
350        let r0 = E(0);
351        let r1 = E(1);
352        let r2 = E(2);
353        let mut m = SecondaryMap::new();
354
355        let v: Vec<E> = m.keys().collect();
356        assert_eq!(v, []);
357
358        m[r2] = 3;
359        m[r1] = 5;
360
361        assert_eq!(m[r1], 5);
362        assert_eq!(m[r2], 3);
363
364        let v: Vec<E> = m.keys().collect();
365        assert_eq!(v, [r0, r1, r2]);
366
367        let shared = &m;
368        assert_eq!(shared[r0], 0);
369        assert_eq!(shared[r1], 5);
370        assert_eq!(shared[r2], 3);
371    }
372}