Skip to main content

wasmtime_environ/collections/
entity_set.rs

1use cranelift_entity::{EntityRef, Keys, SetIter};
2use wasmtime_core::error::OutOfMemory;
3
4/// Like `cranelift_entity::EntitySet` but enforces fallible allocation for all
5/// methods that allocate.
6#[derive(Debug)]
7pub struct TryEntitySet<K>
8where
9    K: EntityRef,
10{
11    inner: cranelift_entity::EntitySet<K>,
12}
13
14impl<K> Default for TryEntitySet<K>
15where
16    K: EntityRef,
17{
18    fn default() -> Self {
19        Self {
20            inner: Default::default(),
21        }
22    }
23}
24
25impl<K> TryEntitySet<K>
26where
27    K: EntityRef,
28{
29    /// Create a new empty set.
30    pub fn new() -> Self {
31        TryEntitySet {
32            inner: Default::default(),
33        }
34    }
35
36    /// Creates a new empty set with the specified capacity.
37    pub fn with_capacity(capacity: usize) -> Result<Self, OutOfMemory> {
38        let mut set = Self::new();
39        set.inner.try_ensure_capacity(capacity)?;
40        Ok(set)
41    }
42
43    /// Ensure that there is enough capacity to hold `capacity` total elements.
44    pub fn ensure_capacity(&mut self, capacity: usize) -> Result<(), OutOfMemory> {
45        self.inner.try_ensure_capacity(capacity)
46    }
47
48    /// Is this set completely empty?
49    pub fn is_empty(&self) -> bool {
50        self.inner.is_empty()
51    }
52
53    /// Get the element at `k` if it exists.
54    pub fn contains(&self, k: K) -> bool {
55        self.inner.contains(k)
56    }
57
58    /// Remove all entries from this set.
59    pub fn clear(&mut self) {
60        self.inner.clear();
61    }
62
63    /// Iterate over all the keys up to the maximum in this set.
64    ///
65    /// This will yield intermediate keys on the way up to the max key, even if
66    /// they are not contained within the set.
67    pub fn keys(&self) -> Keys<K> {
68        self.inner.keys()
69    }
70
71    /// Iterate over the elements of this set.
72    pub fn iter(&self) -> SetIter<'_, K> {
73        self.inner.iter()
74    }
75
76    /// Insert the element at `k`.
77    ///
78    /// Returns `true` if `k` was not present in the set, i.e. this is a
79    /// newly-added element. Returns `false` otherwise.
80    pub fn insert(&mut self, k: K) -> Result<bool, OutOfMemory> {
81        self.inner.try_ensure_capacity(k.index() + 1)?;
82        Ok(self.inner.insert(k))
83    }
84
85    /// Remove `k` from this bitset.
86    ///
87    /// Returns whether `k` was previously in this set or not.
88    pub fn remove(&mut self, k: K) -> bool {
89        self.inner.remove(k)
90    }
91
92    /// Removes and returns the highest-index entity from the set if it exists.
93    pub fn pop(&mut self) -> Option<K> {
94        self.inner.pop()
95    }
96}