xref: /wasmtime-44.0.1/cranelift/entity/src/set.rs (revision eaa4632e)
1 //! Densely numbered entity references as set keys.
2 
3 use crate::EntityRef;
4 use crate::keys::Keys;
5 use core::fmt;
6 use core::marker::PhantomData;
7 use cranelift_bitset::CompoundBitSet;
8 
9 /// A set of `K` for densely indexed entity references.
10 ///
11 /// The `EntitySet` data structure uses the dense index space to implement a set with a bitvector.
12 /// Like `SecondaryMap`, an `EntitySet` is used to associate secondary information with entities.
13 #[derive(Clone, PartialEq, Eq)]
14 #[cfg_attr(
15     feature = "enable-serde",
16     derive(serde_derive::Serialize, serde_derive::Deserialize)
17 )]
18 pub struct EntitySet<K>
19 where
20     K: EntityRef,
21 {
22     bitset: CompoundBitSet,
23     unused: PhantomData<K>,
24 }
25 
26 impl<K: fmt::Debug> fmt::Debug for EntitySet<K>
27 where
28     K: EntityRef,
29 {
30     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31         f.debug_set().entries(self.keys()).finish()
32     }
33 }
34 
35 impl<K: EntityRef> Default for EntitySet<K> {
36     fn default() -> Self {
37         Self {
38             bitset: CompoundBitSet::default(),
39             unused: PhantomData,
40         }
41     }
42 }
43 
44 impl<K: EntityRef> Extend<K> for EntitySet<K> {
45     fn extend<T: IntoIterator<Item = K>>(&mut self, iter: T) {
46         for k in iter {
47             self.insert(k);
48         }
49     }
50 }
51 
52 /// Shared `EntitySet` implementation for all value types.
53 impl<K> EntitySet<K>
54 where
55     K: EntityRef,
56 {
57     /// Create a new empty set.
58     pub fn new() -> Self {
59         Self::default()
60     }
61 
62     /// Creates a new empty set with the specified capacity.
63     pub fn with_capacity(capacity: usize) -> Self {
64         Self {
65             bitset: CompoundBitSet::with_capacity(capacity),
66             unused: PhantomData,
67         }
68     }
69 
70     /// Ensure that the set has enough capacity to hold `capacity` total
71     /// elements.
72     pub fn ensure_capacity(&mut self, capacity: usize) {
73         self.bitset.ensure_capacity(capacity);
74     }
75 
76     /// Get the element at `k` if it exists.
77     pub fn contains(&self, k: K) -> bool {
78         let index = k.index();
79         self.bitset.contains(index)
80     }
81 
82     /// Is this set completely empty?
83     pub fn is_empty(&self) -> bool {
84         self.bitset.is_empty()
85     }
86 
87     /// Remove all entries from this set.
88     pub fn clear(&mut self) {
89         self.bitset.clear()
90     }
91 
92     /// Iterate over all the keys up to the maximum in this set.
93     ///
94     /// This will yield intermediate keys on the way up to the max key, even if
95     /// they are not contained within the set.
96     ///
97     /// ```
98     /// use cranelift_entity::{entity_impl, EntityRef, EntitySet};
99     ///
100     /// #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
101     /// struct Entity(u32);
102     /// entity_impl!(Entity);
103     ///
104     /// let mut set = EntitySet::new();
105     /// set.insert(Entity::new(2));
106     ///
107     /// let mut keys = set.keys();
108     /// assert_eq!(keys.next(), Some(Entity::new(0)));
109     /// assert_eq!(keys.next(), Some(Entity::new(1)));
110     /// assert_eq!(keys.next(), Some(Entity::new(2)));
111     /// assert!(keys.next().is_none());
112     /// ```
113     pub fn keys(&self) -> Keys<K> {
114         Keys::with_len(self.bitset.max().map_or(0, |x| x + 1))
115     }
116 
117     /// Iterate over the elements of this set.
118     ///
119     /// ```
120     /// use cranelift_entity::{entity_impl, EntityRef, EntitySet};
121     ///
122     /// #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
123     /// struct Entity(u32);
124     /// entity_impl!(Entity);
125     ///
126     /// let mut set = EntitySet::new();
127     /// set.insert(Entity::new(2));
128     /// set.insert(Entity::new(3));
129     ///
130     /// let mut iter = set.iter();
131     /// assert_eq!(iter.next(), Some(Entity::new(2)));
132     /// assert_eq!(iter.next(), Some(Entity::new(3)));
133     /// assert!(iter.next().is_none());
134     /// ```
135     pub fn iter(&self) -> SetIter<'_, K> {
136         SetIter {
137             inner: self.bitset.iter(),
138             _phantom: PhantomData,
139         }
140     }
141 
142     /// Insert the element at `k`.
143     ///
144     /// Returns `true` if `k` was not present in the set, i.e. this is a
145     /// newly-added element. Returns `false` otherwise.
146     pub fn insert(&mut self, k: K) -> bool {
147         let index = k.index();
148         self.bitset.insert(index)
149     }
150 
151     /// Removes and returns the entity from the set if it exists.
152     pub fn pop(&mut self) -> Option<K> {
153         let index = self.bitset.pop()?;
154         Some(K::new(index))
155     }
156 }
157 
158 /// An iterator over the elements in an `EntitySet`.
159 pub struct SetIter<'a, K> {
160     inner: cranelift_bitset::compound::Iter<'a>,
161     _phantom: PhantomData<K>,
162 }
163 
164 impl<K> Iterator for SetIter<'_, K>
165 where
166     K: EntityRef,
167 {
168     type Item = K;
169 
170     #[inline]
171     fn next(&mut self) -> Option<Self::Item> {
172         let k = self.inner.next()?;
173         Some(K::new(k))
174     }
175 }
176 
177 #[cfg(test)]
178 mod tests {
179     use super::*;
180     use alloc::vec::Vec;
181     use core::u32;
182 
183     // `EntityRef` impl for testing.
184     #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
185     struct E(u32);
186 
187     impl EntityRef for E {
188         fn new(i: usize) -> Self {
189             E(i as u32)
190         }
191         fn index(self) -> usize {
192             self.0 as usize
193         }
194     }
195 
196     #[test]
197     fn basic() {
198         let r0 = E(0);
199         let r1 = E(1);
200         let r2 = E(2);
201         let mut m = EntitySet::new();
202 
203         let v: Vec<E> = m.keys().collect();
204         assert_eq!(v, []);
205         assert!(m.is_empty());
206 
207         m.insert(r2);
208         m.insert(r1);
209 
210         assert!(!m.contains(r0));
211         assert!(m.contains(r1));
212         assert!(m.contains(r2));
213         assert!(!m.contains(E(3)));
214         assert!(!m.is_empty());
215 
216         let v: Vec<E> = m.keys().collect();
217         assert_eq!(v, [r0, r1, r2]);
218 
219         assert!(!m.contains(E(3)));
220         assert!(!m.contains(E(4)));
221         assert!(!m.contains(E(8)));
222         assert!(!m.contains(E(15)));
223         assert!(!m.contains(E(19)));
224 
225         m.insert(E(8));
226         m.insert(E(15));
227         assert!(!m.contains(E(3)));
228         assert!(!m.contains(E(4)));
229         assert!(m.contains(E(8)));
230         assert!(!m.contains(E(9)));
231         assert!(!m.contains(E(14)));
232         assert!(m.contains(E(15)));
233         assert!(!m.contains(E(16)));
234         assert!(!m.contains(E(19)));
235         assert!(!m.contains(E(20)));
236         assert!(!m.contains(E(u32::MAX)));
237 
238         m.clear();
239         assert!(m.is_empty());
240     }
241 
242     #[test]
243     fn pop_ordered() {
244         let r0 = E(0);
245         let r1 = E(1);
246         let r2 = E(2);
247         let mut m = EntitySet::new();
248         m.insert(r0);
249         m.insert(r1);
250         m.insert(r2);
251 
252         assert_eq!(r2, m.pop().unwrap());
253         assert_eq!(r1, m.pop().unwrap());
254         assert_eq!(r0, m.pop().unwrap());
255         assert!(m.pop().is_none());
256         assert!(m.pop().is_none());
257     }
258 
259     #[test]
260     fn pop_unordered() {
261         let mut blocks = [
262             E(0),
263             E(1),
264             E(6),
265             E(7),
266             E(5),
267             E(9),
268             E(10),
269             E(2),
270             E(3),
271             E(11),
272             E(12),
273         ];
274 
275         let mut m = EntitySet::new();
276         for &block in &blocks {
277             m.insert(block);
278         }
279         assert_eq!(m.bitset.max(), Some(12));
280         blocks.sort();
281 
282         for &block in blocks.iter().rev() {
283             assert_eq!(block, m.pop().unwrap());
284         }
285 
286         assert!(m.is_empty());
287     }
288 }
289