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