1 use cranelift_entity::{EntityRef, Keys, SetIter}; 2 use wasmtime_core::error::OutOfMemory; 3 4 /// Like `cranelift_entity::EntitySet` but enforces fallible allocation for all 5 /// methods that allocate. 6 #[derive(Debug, Default)] 7 pub struct TryEntitySet<K> 8 where 9 K: EntityRef, 10 { 11 inner: cranelift_entity::EntitySet<K>, 12 } 13 14 impl<K> TryEntitySet<K> 15 where 16 K: EntityRef, 17 { 18 /// Create a new empty set. new() -> Self19 pub fn new() -> Self { 20 TryEntitySet { 21 inner: Default::default(), 22 } 23 } 24 25 /// Creates a new empty set with the specified capacity. with_capacity(capacity: usize) -> Result<Self, OutOfMemory>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. ensure_capacity(&mut self, capacity: usize) -> Result<(), OutOfMemory>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? is_empty(&self) -> bool38 pub fn is_empty(&self) -> bool { 39 self.inner.is_empty() 40 } 41 42 /// Get the element at `k` if it exists. contains(&self, k: K) -> bool43 pub fn contains(&self, k: K) -> bool { 44 self.inner.contains(k) 45 } 46 47 /// Remove all entries from this set. clear(&mut self)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. keys(&self) -> Keys<K>56 pub fn keys(&self) -> Keys<K> { 57 self.inner.keys() 58 } 59 60 /// Iterate over the elements of this set. iter(&self) -> SetIter<'_, K>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. insert(&mut self, k: K) -> Result<bool, OutOfMemory>69 pub fn insert(&mut self, k: K) -> Result<bool, OutOfMemory> { 70 self.inner.try_ensure_capacity(k.index() + 1)?; 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. remove(&mut self, k: K) -> bool77 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. pop(&mut self) -> Option<K>82 pub fn pop(&mut self) -> Option<K> { 83 self.inner.pop() 84 } 85 } 86