]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_index/src/bit_set.rs
Auto merge of #98614 - oli-obk:take_unsound_opaque_types, r=wesleywiser
[rust.git] / compiler / rustc_index / src / bit_set.rs
1 use crate::vec::{Idx, IndexVec};
2 use arrayvec::ArrayVec;
3 use std::fmt;
4 use std::iter;
5 use std::marker::PhantomData;
6 use std::mem;
7 use std::ops::{BitAnd, BitAndAssign, BitOrAssign, Bound, Not, Range, RangeBounds, Shl};
8 use std::rc::Rc;
9 use std::slice;
10
11 use rustc_macros::{Decodable, Encodable};
12
13 use Chunk::*;
14
15 #[cfg(test)]
16 mod tests;
17
18 type Word = u64;
19 const WORD_BYTES: usize = mem::size_of::<Word>();
20 const WORD_BITS: usize = WORD_BYTES * 8;
21
22 // The choice of chunk size has some trade-offs.
23 //
24 // A big chunk size tends to favour cases where many large `ChunkedBitSet`s are
25 // present, because they require fewer `Chunk`s, reducing the number of
26 // allocations and reducing peak memory usage. Also, fewer chunk operations are
27 // required, though more of them might be `Mixed`.
28 //
29 // A small chunk size tends to favour cases where many small `ChunkedBitSet`s
30 // are present, because less space is wasted at the end of the final chunk (if
31 // it's not full).
32 const CHUNK_WORDS: usize = 32;
33 const CHUNK_BITS: usize = CHUNK_WORDS * WORD_BITS; // 2048 bits
34
35 /// ChunkSize is small to keep `Chunk` small. The static assertion ensures it's
36 /// not too small.
37 type ChunkSize = u16;
38 const _: () = assert!(CHUNK_BITS <= ChunkSize::MAX as usize);
39
40 pub trait BitRelations<Rhs> {
41     fn union(&mut self, other: &Rhs) -> bool;
42     fn subtract(&mut self, other: &Rhs) -> bool;
43     fn intersect(&mut self, other: &Rhs) -> bool;
44 }
45
46 #[inline]
47 fn inclusive_start_end<T: Idx>(
48     range: impl RangeBounds<T>,
49     domain: usize,
50 ) -> Option<(usize, usize)> {
51     // Both start and end are inclusive.
52     let start = match range.start_bound().cloned() {
53         Bound::Included(start) => start.index(),
54         Bound::Excluded(start) => start.index() + 1,
55         Bound::Unbounded => 0,
56     };
57     let end = match range.end_bound().cloned() {
58         Bound::Included(end) => end.index(),
59         Bound::Excluded(end) => end.index().checked_sub(1)?,
60         Bound::Unbounded => domain - 1,
61     };
62     assert!(end < domain);
63     if start > end {
64         return None;
65     }
66     Some((start, end))
67 }
68
69 macro_rules! bit_relations_inherent_impls {
70     () => {
71         /// Sets `self = self | other` and returns `true` if `self` changed
72         /// (i.e., if new bits were added).
73         pub fn union<Rhs>(&mut self, other: &Rhs) -> bool
74         where
75             Self: BitRelations<Rhs>,
76         {
77             <Self as BitRelations<Rhs>>::union(self, other)
78         }
79
80         /// Sets `self = self - other` and returns `true` if `self` changed.
81         /// (i.e., if any bits were removed).
82         pub fn subtract<Rhs>(&mut self, other: &Rhs) -> bool
83         where
84             Self: BitRelations<Rhs>,
85         {
86             <Self as BitRelations<Rhs>>::subtract(self, other)
87         }
88
89         /// Sets `self = self & other` and return `true` if `self` changed.
90         /// (i.e., if any bits were removed).
91         pub fn intersect<Rhs>(&mut self, other: &Rhs) -> bool
92         where
93             Self: BitRelations<Rhs>,
94         {
95             <Self as BitRelations<Rhs>>::intersect(self, other)
96         }
97     };
98 }
99
100 /// A fixed-size bitset type with a dense representation.
101 ///
102 /// NOTE: Use [`GrowableBitSet`] if you need support for resizing after creation.
103 ///
104 /// `T` is an index type, typically a newtyped `usize` wrapper, but it can also
105 /// just be `usize`.
106 ///
107 /// All operations that involve an element will panic if the element is equal
108 /// to or greater than the domain size. All operations that involve two bitsets
109 /// will panic if the bitsets have differing domain sizes.
110 ///
111 #[derive(Eq, PartialEq, Hash, Decodable, Encodable)]
112 pub struct BitSet<T> {
113     domain_size: usize,
114     words: Vec<Word>,
115     marker: PhantomData<T>,
116 }
117
118 impl<T> BitSet<T> {
119     /// Gets the domain size.
120     pub fn domain_size(&self) -> usize {
121         self.domain_size
122     }
123 }
124
125 impl<T: Idx> BitSet<T> {
126     /// Creates a new, empty bitset with a given `domain_size`.
127     #[inline]
128     pub fn new_empty(domain_size: usize) -> BitSet<T> {
129         let num_words = num_words(domain_size);
130         BitSet { domain_size, words: vec![0; num_words], marker: PhantomData }
131     }
132
133     /// Creates a new, filled bitset with a given `domain_size`.
134     #[inline]
135     pub fn new_filled(domain_size: usize) -> BitSet<T> {
136         let num_words = num_words(domain_size);
137         let mut result = BitSet { domain_size, words: vec![!0; num_words], marker: PhantomData };
138         result.clear_excess_bits();
139         result
140     }
141
142     /// Clear all elements.
143     #[inline]
144     pub fn clear(&mut self) {
145         self.words.fill(0);
146     }
147
148     /// Clear excess bits in the final word.
149     fn clear_excess_bits(&mut self) {
150         clear_excess_bits_in_final_word(self.domain_size, &mut self.words);
151     }
152
153     /// Count the number of set bits in the set.
154     pub fn count(&self) -> usize {
155         self.words.iter().map(|e| e.count_ones() as usize).sum()
156     }
157
158     /// Returns `true` if `self` contains `elem`.
159     #[inline]
160     pub fn contains(&self, elem: T) -> bool {
161         assert!(elem.index() < self.domain_size);
162         let (word_index, mask) = word_index_and_mask(elem);
163         (self.words[word_index] & mask) != 0
164     }
165
166     /// Is `self` is a (non-strict) superset of `other`?
167     #[inline]
168     pub fn superset(&self, other: &BitSet<T>) -> bool {
169         assert_eq!(self.domain_size, other.domain_size);
170         self.words.iter().zip(&other.words).all(|(a, b)| (a & b) == *b)
171     }
172
173     /// Is the set empty?
174     #[inline]
175     pub fn is_empty(&self) -> bool {
176         self.words.iter().all(|a| *a == 0)
177     }
178
179     /// Insert `elem`. Returns whether the set has changed.
180     #[inline]
181     pub fn insert(&mut self, elem: T) -> bool {
182         assert!(elem.index() < self.domain_size);
183         let (word_index, mask) = word_index_and_mask(elem);
184         let word_ref = &mut self.words[word_index];
185         let word = *word_ref;
186         let new_word = word | mask;
187         *word_ref = new_word;
188         new_word != word
189     }
190
191     #[inline]
192     pub fn insert_range(&mut self, elems: impl RangeBounds<T>) {
193         let Some((start, end)) = inclusive_start_end(elems, self.domain_size) else {
194             return;
195         };
196
197         let (start_word_index, start_mask) = word_index_and_mask(start);
198         let (end_word_index, end_mask) = word_index_and_mask(end);
199
200         // Set all words in between start and end (exclusively of both).
201         for word_index in (start_word_index + 1)..end_word_index {
202             self.words[word_index] = !0;
203         }
204
205         if start_word_index != end_word_index {
206             // Start and end are in different words, so we handle each in turn.
207             //
208             // We set all leading bits. This includes the start_mask bit.
209             self.words[start_word_index] |= !(start_mask - 1);
210             // And all trailing bits (i.e. from 0..=end) in the end word,
211             // including the end.
212             self.words[end_word_index] |= end_mask | end_mask - 1;
213         } else {
214             self.words[start_word_index] |= end_mask | (end_mask - start_mask);
215         }
216     }
217
218     /// Sets all bits to true.
219     pub fn insert_all(&mut self) {
220         self.words.fill(!0);
221         self.clear_excess_bits();
222     }
223
224     /// Returns `true` if the set has changed.
225     #[inline]
226     pub fn remove(&mut self, elem: T) -> bool {
227         assert!(elem.index() < self.domain_size);
228         let (word_index, mask) = word_index_and_mask(elem);
229         let word_ref = &mut self.words[word_index];
230         let word = *word_ref;
231         let new_word = word & !mask;
232         *word_ref = new_word;
233         new_word != word
234     }
235
236     /// Gets a slice of the underlying words.
237     pub fn words(&self) -> &[Word] {
238         &self.words
239     }
240
241     /// Iterates over the indices of set bits in a sorted order.
242     #[inline]
243     pub fn iter(&self) -> BitIter<'_, T> {
244         BitIter::new(&self.words)
245     }
246
247     /// Duplicates the set as a hybrid set.
248     pub fn to_hybrid(&self) -> HybridBitSet<T> {
249         // Note: we currently don't bother trying to make a Sparse set.
250         HybridBitSet::Dense(self.to_owned())
251     }
252
253     /// Set `self = self | other`. In contrast to `union` returns `true` if the set contains at
254     /// least one bit that is not in `other` (i.e. `other` is not a superset of `self`).
255     ///
256     /// This is an optimization for union of a hybrid bitset.
257     fn reverse_union_sparse(&mut self, sparse: &SparseBitSet<T>) -> bool {
258         assert!(sparse.domain_size == self.domain_size);
259         self.clear_excess_bits();
260
261         let mut not_already = false;
262         // Index of the current word not yet merged.
263         let mut current_index = 0;
264         // Mask of bits that came from the sparse set in the current word.
265         let mut new_bit_mask = 0;
266         for (word_index, mask) in sparse.iter().map(|x| word_index_and_mask(*x)) {
267             // Next bit is in a word not inspected yet.
268             if word_index > current_index {
269                 self.words[current_index] |= new_bit_mask;
270                 // Were there any bits in the old word that did not occur in the sparse set?
271                 not_already |= (self.words[current_index] ^ new_bit_mask) != 0;
272                 // Check all words we skipped for any set bit.
273                 not_already |= self.words[current_index + 1..word_index].iter().any(|&x| x != 0);
274                 // Update next word.
275                 current_index = word_index;
276                 // Reset bit mask, no bits have been merged yet.
277                 new_bit_mask = 0;
278             }
279             // Add bit and mark it as coming from the sparse set.
280             // self.words[word_index] |= mask;
281             new_bit_mask |= mask;
282         }
283         self.words[current_index] |= new_bit_mask;
284         // Any bits in the last inspected word that were not in the sparse set?
285         not_already |= (self.words[current_index] ^ new_bit_mask) != 0;
286         // Any bits in the tail? Note `clear_excess_bits` before.
287         not_already |= self.words[current_index + 1..].iter().any(|&x| x != 0);
288
289         not_already
290     }
291
292     fn last_set_in(&self, range: impl RangeBounds<T>) -> Option<T> {
293         let (start, end) = inclusive_start_end(range, self.domain_size)?;
294         let (start_word_index, _) = word_index_and_mask(start);
295         let (end_word_index, end_mask) = word_index_and_mask(end);
296
297         let end_word = self.words[end_word_index] & (end_mask | (end_mask - 1));
298         if end_word != 0 {
299             let pos = max_bit(end_word) + WORD_BITS * end_word_index;
300             if start <= pos {
301                 return Some(T::new(pos));
302             }
303         }
304
305         // We exclude end_word_index from the range here, because we don't want
306         // to limit ourselves to *just* the last word: the bits set it in may be
307         // after `end`, so it may not work out.
308         if let Some(offset) =
309             self.words[start_word_index..end_word_index].iter().rposition(|&w| w != 0)
310         {
311             let word_idx = start_word_index + offset;
312             let start_word = self.words[word_idx];
313             let pos = max_bit(start_word) + WORD_BITS * word_idx;
314             if start <= pos {
315                 return Some(T::new(pos));
316             }
317         }
318
319         None
320     }
321
322     bit_relations_inherent_impls! {}
323 }
324
325 // dense REL dense
326 impl<T: Idx> BitRelations<BitSet<T>> for BitSet<T> {
327     fn union(&mut self, other: &BitSet<T>) -> bool {
328         assert_eq!(self.domain_size, other.domain_size);
329         bitwise(&mut self.words, &other.words, |a, b| a | b)
330     }
331
332     fn subtract(&mut self, other: &BitSet<T>) -> bool {
333         assert_eq!(self.domain_size, other.domain_size);
334         bitwise(&mut self.words, &other.words, |a, b| a & !b)
335     }
336
337     fn intersect(&mut self, other: &BitSet<T>) -> bool {
338         assert_eq!(self.domain_size, other.domain_size);
339         bitwise(&mut self.words, &other.words, |a, b| a & b)
340     }
341 }
342
343 impl<T: Idx> From<GrowableBitSet<T>> for BitSet<T> {
344     fn from(bit_set: GrowableBitSet<T>) -> Self {
345         bit_set.bit_set
346     }
347 }
348
349 /// A fixed-size bitset type with a partially dense, partially sparse
350 /// representation. The bitset is broken into chunks, and chunks that are all
351 /// zeros or all ones are represented and handled very efficiently.
352 ///
353 /// This type is especially efficient for sets that typically have a large
354 /// `domain_size` with significant stretches of all zeros or all ones, and also
355 /// some stretches with lots of 0s and 1s mixed in a way that causes trouble
356 /// for `IntervalSet`.
357 ///
358 /// `T` is an index type, typically a newtyped `usize` wrapper, but it can also
359 /// just be `usize`.
360 ///
361 /// All operations that involve an element will panic if the element is equal
362 /// to or greater than the domain size. All operations that involve two bitsets
363 /// will panic if the bitsets have differing domain sizes.
364 #[derive(Debug, PartialEq, Eq)]
365 pub struct ChunkedBitSet<T> {
366     domain_size: usize,
367
368     /// The chunks. Each one contains exactly CHUNK_BITS values, except the
369     /// last one which contains 1..=CHUNK_BITS values.
370     chunks: Box<[Chunk]>,
371
372     marker: PhantomData<T>,
373 }
374
375 // Note: the chunk domain size is duplicated in each variant. This is a bit
376 // inconvenient, but it allows the type size to be smaller than if we had an
377 // outer struct containing a chunk domain size plus the `Chunk`, because the
378 // compiler can place the chunk domain size after the tag.
379 #[derive(Clone, Debug, PartialEq, Eq)]
380 enum Chunk {
381     /// A chunk that is all zeros; we don't represent the zeros explicitly.
382     Zeros(ChunkSize),
383
384     /// A chunk that is all ones; we don't represent the ones explicitly.
385     Ones(ChunkSize),
386
387     /// A chunk that has a mix of zeros and ones, which are represented
388     /// explicitly and densely. It never has all zeros or all ones.
389     ///
390     /// If this is the final chunk there may be excess, unused words. This
391     /// turns out to be both simpler and have better performance than
392     /// allocating the minimum number of words, largely because we avoid having
393     /// to store the length, which would make this type larger. These excess
394     /// words are always be zero, as are any excess bits in the final in-use
395     /// word.
396     ///
397     /// The second field is the count of 1s set in the chunk, and must satisfy
398     /// `0 < count < chunk_domain_size`.
399     ///
400     /// The words are within an `Rc` because it's surprisingly common to
401     /// duplicate an entire chunk, e.g. in `ChunkedBitSet::clone_from()`, or
402     /// when a `Mixed` chunk is union'd into a `Zeros` chunk. When we do need
403     /// to modify a chunk we use `Rc::make_mut`.
404     Mixed(ChunkSize, ChunkSize, Rc<[Word; CHUNK_WORDS]>),
405 }
406
407 // This type is used a lot. Make sure it doesn't unintentionally get bigger.
408 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
409 crate::static_assert_size!(Chunk, 16);
410
411 impl<T> ChunkedBitSet<T> {
412     pub fn domain_size(&self) -> usize {
413         self.domain_size
414     }
415
416     #[cfg(test)]
417     fn assert_valid(&self) {
418         if self.domain_size == 0 {
419             assert!(self.chunks.is_empty());
420             return;
421         }
422
423         assert!((self.chunks.len() - 1) * CHUNK_BITS <= self.domain_size);
424         assert!(self.chunks.len() * CHUNK_BITS >= self.domain_size);
425         for chunk in self.chunks.iter() {
426             chunk.assert_valid();
427         }
428     }
429 }
430
431 impl<T: Idx> ChunkedBitSet<T> {
432     /// Creates a new bitset with a given `domain_size` and chunk kind.
433     fn new(domain_size: usize, is_empty: bool) -> Self {
434         let chunks = if domain_size == 0 {
435             Box::new([])
436         } else {
437             // All the chunks have a chunk_domain_size of `CHUNK_BITS` except
438             // the final one.
439             let final_chunk_domain_size = {
440                 let n = domain_size % CHUNK_BITS;
441                 if n == 0 { CHUNK_BITS } else { n }
442             };
443             let mut chunks =
444                 vec![Chunk::new(CHUNK_BITS, is_empty); num_chunks(domain_size)].into_boxed_slice();
445             *chunks.last_mut().unwrap() = Chunk::new(final_chunk_domain_size, is_empty);
446             chunks
447         };
448         ChunkedBitSet { domain_size, chunks, marker: PhantomData }
449     }
450
451     /// Creates a new, empty bitset with a given `domain_size`.
452     #[inline]
453     pub fn new_empty(domain_size: usize) -> Self {
454         ChunkedBitSet::new(domain_size, /* is_empty */ true)
455     }
456
457     /// Creates a new, filled bitset with a given `domain_size`.
458     #[inline]
459     pub fn new_filled(domain_size: usize) -> Self {
460         ChunkedBitSet::new(domain_size, /* is_empty */ false)
461     }
462
463     #[cfg(test)]
464     fn chunks(&self) -> &[Chunk] {
465         &self.chunks
466     }
467
468     /// Count the number of bits in the set.
469     pub fn count(&self) -> usize {
470         self.chunks.iter().map(|chunk| chunk.count()).sum()
471     }
472
473     /// Returns `true` if `self` contains `elem`.
474     #[inline]
475     pub fn contains(&self, elem: T) -> bool {
476         assert!(elem.index() < self.domain_size);
477         let chunk = &self.chunks[chunk_index(elem)];
478         match &chunk {
479             Zeros(_) => false,
480             Ones(_) => true,
481             Mixed(_, _, words) => {
482                 let (word_index, mask) = chunk_word_index_and_mask(elem);
483                 (words[word_index] & mask) != 0
484             }
485         }
486     }
487
488     #[inline]
489     pub fn iter(&self) -> ChunkedBitIter<'_, T> {
490         ChunkedBitIter::new(self)
491     }
492
493     /// Insert `elem`. Returns whether the set has changed.
494     pub fn insert(&mut self, elem: T) -> bool {
495         assert!(elem.index() < self.domain_size);
496         let chunk_index = chunk_index(elem);
497         let chunk = &mut self.chunks[chunk_index];
498         match *chunk {
499             Zeros(chunk_domain_size) => {
500                 if chunk_domain_size > 1 {
501                     // We take some effort to avoid copying the words.
502                     let words = Rc::<[Word; CHUNK_WORDS]>::new_zeroed();
503                     // SAFETY: `words` can safely be all zeroes.
504                     let mut words = unsafe { words.assume_init() };
505                     let words_ref = Rc::get_mut(&mut words).unwrap();
506
507                     let (word_index, mask) = chunk_word_index_and_mask(elem);
508                     words_ref[word_index] |= mask;
509                     *chunk = Mixed(chunk_domain_size, 1, words);
510                 } else {
511                     *chunk = Ones(chunk_domain_size);
512                 }
513                 true
514             }
515             Ones(_) => false,
516             Mixed(chunk_domain_size, ref mut count, ref mut words) => {
517                 // We skip all the work if the bit is already set.
518                 let (word_index, mask) = chunk_word_index_and_mask(elem);
519                 if (words[word_index] & mask) == 0 {
520                     *count += 1;
521                     if *count < chunk_domain_size {
522                         let words = Rc::make_mut(words);
523                         words[word_index] |= mask;
524                     } else {
525                         *chunk = Ones(chunk_domain_size);
526                     }
527                     true
528                 } else {
529                     false
530                 }
531             }
532         }
533     }
534
535     /// Sets all bits to true.
536     pub fn insert_all(&mut self) {
537         for chunk in self.chunks.iter_mut() {
538             *chunk = match *chunk {
539                 Zeros(chunk_domain_size)
540                 | Ones(chunk_domain_size)
541                 | Mixed(chunk_domain_size, ..) => Ones(chunk_domain_size),
542             }
543         }
544     }
545
546     /// Returns `true` if the set has changed.
547     pub fn remove(&mut self, elem: T) -> bool {
548         assert!(elem.index() < self.domain_size);
549         let chunk_index = chunk_index(elem);
550         let chunk = &mut self.chunks[chunk_index];
551         match *chunk {
552             Zeros(_) => false,
553             Ones(chunk_domain_size) => {
554                 if chunk_domain_size > 1 {
555                     // We take some effort to avoid copying the words.
556                     let words = Rc::<[Word; CHUNK_WORDS]>::new_zeroed();
557                     // SAFETY: `words` can safely be all zeroes.
558                     let mut words = unsafe { words.assume_init() };
559                     let words_ref = Rc::get_mut(&mut words).unwrap();
560
561                     // Set only the bits in use.
562                     let num_words = num_words(chunk_domain_size as usize);
563                     words_ref[..num_words].fill(!0);
564                     clear_excess_bits_in_final_word(
565                         chunk_domain_size as usize,
566                         &mut words_ref[..num_words],
567                     );
568                     let (word_index, mask) = chunk_word_index_and_mask(elem);
569                     words_ref[word_index] &= !mask;
570                     *chunk = Mixed(chunk_domain_size, chunk_domain_size - 1, words);
571                 } else {
572                     *chunk = Zeros(chunk_domain_size);
573                 }
574                 true
575             }
576             Mixed(chunk_domain_size, ref mut count, ref mut words) => {
577                 // We skip all the work if the bit is already clear.
578                 let (word_index, mask) = chunk_word_index_and_mask(elem);
579                 if (words[word_index] & mask) != 0 {
580                     *count -= 1;
581                     if *count > 0 {
582                         let words = Rc::make_mut(words);
583                         words[word_index] &= !mask;
584                     } else {
585                         *chunk = Zeros(chunk_domain_size);
586                     }
587                     true
588                 } else {
589                     false
590                 }
591             }
592         }
593     }
594
595     bit_relations_inherent_impls! {}
596 }
597
598 impl<T: Idx> BitRelations<ChunkedBitSet<T>> for ChunkedBitSet<T> {
599     fn union(&mut self, other: &ChunkedBitSet<T>) -> bool {
600         assert_eq!(self.domain_size, other.domain_size);
601         debug_assert_eq!(self.chunks.len(), other.chunks.len());
602
603         let mut changed = false;
604         for (mut self_chunk, other_chunk) in self.chunks.iter_mut().zip(other.chunks.iter()) {
605             match (&mut self_chunk, &other_chunk) {
606                 (_, Zeros(_)) | (Ones(_), _) => {}
607                 (Zeros(self_chunk_domain_size), Ones(other_chunk_domain_size))
608                 | (Mixed(self_chunk_domain_size, ..), Ones(other_chunk_domain_size))
609                 | (Zeros(self_chunk_domain_size), Mixed(other_chunk_domain_size, ..)) => {
610                     // `other_chunk` fully overwrites `self_chunk`
611                     debug_assert_eq!(self_chunk_domain_size, other_chunk_domain_size);
612                     *self_chunk = other_chunk.clone();
613                     changed = true;
614                 }
615                 (
616                     Mixed(
617                         self_chunk_domain_size,
618                         ref mut self_chunk_count,
619                         ref mut self_chunk_words,
620                     ),
621                     Mixed(_other_chunk_domain_size, _other_chunk_count, other_chunk_words),
622                 ) => {
623                     // First check if the operation would change
624                     // `self_chunk.words`. If not, we can avoid allocating some
625                     // words, and this happens often enough that it's a
626                     // performance win. Also, we only need to operate on the
627                     // in-use words, hence the slicing.
628                     let op = |a, b| a | b;
629                     let num_words = num_words(*self_chunk_domain_size as usize);
630                     if bitwise_changes(
631                         &self_chunk_words[0..num_words],
632                         &other_chunk_words[0..num_words],
633                         op,
634                     ) {
635                         let self_chunk_words = Rc::make_mut(self_chunk_words);
636                         let has_changed = bitwise(
637                             &mut self_chunk_words[0..num_words],
638                             &other_chunk_words[0..num_words],
639                             op,
640                         );
641                         debug_assert!(has_changed);
642                         *self_chunk_count = self_chunk_words[0..num_words]
643                             .iter()
644                             .map(|w| w.count_ones() as ChunkSize)
645                             .sum();
646                         if *self_chunk_count == *self_chunk_domain_size {
647                             *self_chunk = Ones(*self_chunk_domain_size);
648                         }
649                         changed = true;
650                     }
651                 }
652             }
653         }
654         changed
655     }
656
657     fn subtract(&mut self, _other: &ChunkedBitSet<T>) -> bool {
658         unimplemented!("implement if/when necessary");
659     }
660
661     fn intersect(&mut self, _other: &ChunkedBitSet<T>) -> bool {
662         unimplemented!("implement if/when necessary");
663     }
664 }
665
666 impl<T: Idx> BitRelations<HybridBitSet<T>> for ChunkedBitSet<T> {
667     fn union(&mut self, other: &HybridBitSet<T>) -> bool {
668         // FIXME: This is slow if `other` is dense, but it hasn't been a problem
669         // in practice so far.
670         // If a faster implementation of this operation is required, consider
671         // reopening https://github.com/rust-lang/rust/pull/94625
672         assert_eq!(self.domain_size, other.domain_size());
673         sequential_update(|elem| self.insert(elem), other.iter())
674     }
675
676     fn subtract(&mut self, other: &HybridBitSet<T>) -> bool {
677         // FIXME: This is slow if `other` is dense, but it hasn't been a problem
678         // in practice so far.
679         // If a faster implementation of this operation is required, consider
680         // reopening https://github.com/rust-lang/rust/pull/94625
681         assert_eq!(self.domain_size, other.domain_size());
682         sequential_update(|elem| self.remove(elem), other.iter())
683     }
684
685     fn intersect(&mut self, _other: &HybridBitSet<T>) -> bool {
686         unimplemented!("implement if/when necessary");
687     }
688 }
689
690 impl<T: Idx> BitRelations<ChunkedBitSet<T>> for BitSet<T> {
691     fn union(&mut self, other: &ChunkedBitSet<T>) -> bool {
692         sequential_update(|elem| self.insert(elem), other.iter())
693     }
694
695     fn subtract(&mut self, _other: &ChunkedBitSet<T>) -> bool {
696         unimplemented!("implement if/when necessary");
697     }
698
699     fn intersect(&mut self, other: &ChunkedBitSet<T>) -> bool {
700         assert_eq!(self.domain_size(), other.domain_size);
701         let mut changed = false;
702         for (i, chunk) in other.chunks.iter().enumerate() {
703             let mut words = &mut self.words[i * CHUNK_WORDS..];
704             if words.len() > CHUNK_WORDS {
705                 words = &mut words[..CHUNK_WORDS];
706             }
707             match chunk {
708                 Chunk::Zeros(..) => {
709                     for word in words {
710                         if *word != 0 {
711                             changed = true;
712                             *word = 0;
713                         }
714                     }
715                 }
716                 Chunk::Ones(..) => (),
717                 Chunk::Mixed(_, _, data) => {
718                     for (i, word) in words.iter_mut().enumerate() {
719                         let new_val = *word & data[i];
720                         if new_val != *word {
721                             changed = true;
722                             *word = new_val;
723                         }
724                     }
725                 }
726             }
727         }
728         changed
729     }
730 }
731
732 impl<T> Clone for ChunkedBitSet<T> {
733     fn clone(&self) -> Self {
734         ChunkedBitSet {
735             domain_size: self.domain_size,
736             chunks: self.chunks.clone(),
737             marker: PhantomData,
738         }
739     }
740
741     /// WARNING: this implementation of clone_from will panic if the two
742     /// bitsets have different domain sizes. This constraint is not inherent to
743     /// `clone_from`, but it works with the existing call sites and allows a
744     /// faster implementation, which is important because this function is hot.
745     fn clone_from(&mut self, from: &Self) {
746         assert_eq!(self.domain_size, from.domain_size);
747         debug_assert_eq!(self.chunks.len(), from.chunks.len());
748
749         self.chunks.clone_from(&from.chunks)
750     }
751 }
752
753 pub struct ChunkedBitIter<'a, T: Idx> {
754     index: usize,
755     bitset: &'a ChunkedBitSet<T>,
756 }
757
758 impl<'a, T: Idx> ChunkedBitIter<'a, T> {
759     #[inline]
760     fn new(bitset: &'a ChunkedBitSet<T>) -> ChunkedBitIter<'a, T> {
761         ChunkedBitIter { index: 0, bitset }
762     }
763 }
764
765 impl<'a, T: Idx> Iterator for ChunkedBitIter<'a, T> {
766     type Item = T;
767     fn next(&mut self) -> Option<T> {
768         while self.index < self.bitset.domain_size() {
769             let elem = T::new(self.index);
770             let chunk = &self.bitset.chunks[chunk_index(elem)];
771             match &chunk {
772                 Zeros(chunk_domain_size) => {
773                     self.index += *chunk_domain_size as usize;
774                 }
775                 Ones(_chunk_domain_size) => {
776                     self.index += 1;
777                     return Some(elem);
778                 }
779                 Mixed(_chunk_domain_size, _, words) => loop {
780                     let elem = T::new(self.index);
781                     self.index += 1;
782                     let (word_index, mask) = chunk_word_index_and_mask(elem);
783                     if (words[word_index] & mask) != 0 {
784                         return Some(elem);
785                     }
786                     if self.index % CHUNK_BITS == 0 {
787                         break;
788                     }
789                 },
790             }
791         }
792         None
793     }
794
795     fn fold<B, F>(mut self, mut init: B, mut f: F) -> B
796     where
797         F: FnMut(B, Self::Item) -> B,
798     {
799         // If `next` has already been called, we may not be at the start of a chunk, so we first
800         // advance the iterator to the start of the next chunk, before proceeding in chunk sized
801         // steps.
802         while self.index % CHUNK_BITS != 0 {
803             let Some(item) = self.next() else {
804                 return init
805             };
806             init = f(init, item);
807         }
808         let start_chunk = self.index / CHUNK_BITS;
809         let chunks = &self.bitset.chunks[start_chunk..];
810         for (i, chunk) in chunks.iter().enumerate() {
811             let base = (start_chunk + i) * CHUNK_BITS;
812             match chunk {
813                 Chunk::Zeros(_) => (),
814                 Chunk::Ones(limit) => {
815                     for j in 0..(*limit as usize) {
816                         init = f(init, T::new(base + j));
817                     }
818                 }
819                 Chunk::Mixed(_, _, words) => {
820                     init = BitIter::new(&**words).fold(init, |val, mut item: T| {
821                         item.increment_by(base);
822                         f(val, item)
823                     });
824                 }
825             }
826         }
827         init
828     }
829 }
830
831 impl Chunk {
832     #[cfg(test)]
833     fn assert_valid(&self) {
834         match *self {
835             Zeros(chunk_domain_size) | Ones(chunk_domain_size) => {
836                 assert!(chunk_domain_size as usize <= CHUNK_BITS);
837             }
838             Mixed(chunk_domain_size, count, ref words) => {
839                 assert!(chunk_domain_size as usize <= CHUNK_BITS);
840                 assert!(0 < count && count < chunk_domain_size);
841
842                 // Check the number of set bits matches `count`.
843                 assert_eq!(
844                     words.iter().map(|w| w.count_ones() as ChunkSize).sum::<ChunkSize>(),
845                     count
846                 );
847
848                 // Check the not-in-use words are all zeroed.
849                 let num_words = num_words(chunk_domain_size as usize);
850                 if num_words < CHUNK_WORDS {
851                     assert_eq!(
852                         words[num_words..]
853                             .iter()
854                             .map(|w| w.count_ones() as ChunkSize)
855                             .sum::<ChunkSize>(),
856                         0
857                     );
858                 }
859             }
860         }
861     }
862
863     fn new(chunk_domain_size: usize, is_empty: bool) -> Self {
864         debug_assert!(chunk_domain_size <= CHUNK_BITS);
865         let chunk_domain_size = chunk_domain_size as ChunkSize;
866         if is_empty { Zeros(chunk_domain_size) } else { Ones(chunk_domain_size) }
867     }
868
869     /// Count the number of 1s in the chunk.
870     fn count(&self) -> usize {
871         match *self {
872             Zeros(_) => 0,
873             Ones(chunk_domain_size) => chunk_domain_size as usize,
874             Mixed(_, count, _) => count as usize,
875         }
876     }
877 }
878
879 // Applies a function to mutate a bitset, and returns true if any
880 // of the applications return true
881 fn sequential_update<T: Idx>(
882     mut self_update: impl FnMut(T) -> bool,
883     it: impl Iterator<Item = T>,
884 ) -> bool {
885     it.fold(false, |changed, elem| self_update(elem) | changed)
886 }
887
888 // Optimization of intersection for SparseBitSet that's generic
889 // over the RHS
890 fn sparse_intersect<T: Idx>(
891     set: &mut SparseBitSet<T>,
892     other_contains: impl Fn(&T) -> bool,
893 ) -> bool {
894     let size = set.elems.len();
895     set.elems.retain(|elem| other_contains(elem));
896     set.elems.len() != size
897 }
898
899 // Optimization of dense/sparse intersection. The resulting set is
900 // guaranteed to be at most the size of the sparse set, and hence can be
901 // represented as a sparse set. Therefore the sparse set is copied and filtered,
902 // then returned as the new set.
903 fn dense_sparse_intersect<T: Idx>(
904     dense: &BitSet<T>,
905     sparse: &SparseBitSet<T>,
906 ) -> (SparseBitSet<T>, bool) {
907     let mut sparse_copy = sparse.clone();
908     sparse_intersect(&mut sparse_copy, |el| dense.contains(*el));
909     let n = sparse_copy.len();
910     (sparse_copy, n != dense.count())
911 }
912
913 // hybrid REL dense
914 impl<T: Idx> BitRelations<BitSet<T>> for HybridBitSet<T> {
915     fn union(&mut self, other: &BitSet<T>) -> bool {
916         assert_eq!(self.domain_size(), other.domain_size);
917         match self {
918             HybridBitSet::Sparse(sparse) => {
919                 // `self` is sparse and `other` is dense. To
920                 // merge them, we have two available strategies:
921                 // * Densify `self` then merge other
922                 // * Clone other then integrate bits from `self`
923                 // The second strategy requires dedicated method
924                 // since the usual `union` returns the wrong
925                 // result. In the dedicated case the computation
926                 // is slightly faster if the bits of the sparse
927                 // bitset map to only few words of the dense
928                 // representation, i.e. indices are near each
929                 // other.
930                 //
931                 // Benchmarking seems to suggest that the second
932                 // option is worth it.
933                 let mut new_dense = other.clone();
934                 let changed = new_dense.reverse_union_sparse(sparse);
935                 *self = HybridBitSet::Dense(new_dense);
936                 changed
937             }
938
939             HybridBitSet::Dense(dense) => dense.union(other),
940         }
941     }
942
943     fn subtract(&mut self, other: &BitSet<T>) -> bool {
944         assert_eq!(self.domain_size(), other.domain_size);
945         match self {
946             HybridBitSet::Sparse(sparse) => {
947                 sequential_update(|elem| sparse.remove(elem), other.iter())
948             }
949             HybridBitSet::Dense(dense) => dense.subtract(other),
950         }
951     }
952
953     fn intersect(&mut self, other: &BitSet<T>) -> bool {
954         assert_eq!(self.domain_size(), other.domain_size);
955         match self {
956             HybridBitSet::Sparse(sparse) => sparse_intersect(sparse, |elem| other.contains(*elem)),
957             HybridBitSet::Dense(dense) => dense.intersect(other),
958         }
959     }
960 }
961
962 // dense REL hybrid
963 impl<T: Idx> BitRelations<HybridBitSet<T>> for BitSet<T> {
964     fn union(&mut self, other: &HybridBitSet<T>) -> bool {
965         assert_eq!(self.domain_size, other.domain_size());
966         match other {
967             HybridBitSet::Sparse(sparse) => {
968                 sequential_update(|elem| self.insert(elem), sparse.iter().cloned())
969             }
970             HybridBitSet::Dense(dense) => self.union(dense),
971         }
972     }
973
974     fn subtract(&mut self, other: &HybridBitSet<T>) -> bool {
975         assert_eq!(self.domain_size, other.domain_size());
976         match other {
977             HybridBitSet::Sparse(sparse) => {
978                 sequential_update(|elem| self.remove(elem), sparse.iter().cloned())
979             }
980             HybridBitSet::Dense(dense) => self.subtract(dense),
981         }
982     }
983
984     fn intersect(&mut self, other: &HybridBitSet<T>) -> bool {
985         assert_eq!(self.domain_size, other.domain_size());
986         match other {
987             HybridBitSet::Sparse(sparse) => {
988                 let (updated, changed) = dense_sparse_intersect(self, sparse);
989
990                 // We can't directly assign the SparseBitSet to the BitSet, and
991                 // doing `*self = updated.to_dense()` would cause a drop / reallocation. Instead,
992                 // the BitSet is cleared and `updated` is copied into `self`.
993                 self.clear();
994                 for elem in updated.iter() {
995                     self.insert(*elem);
996                 }
997                 changed
998             }
999             HybridBitSet::Dense(dense) => self.intersect(dense),
1000         }
1001     }
1002 }
1003
1004 // hybrid REL hybrid
1005 impl<T: Idx> BitRelations<HybridBitSet<T>> for HybridBitSet<T> {
1006     fn union(&mut self, other: &HybridBitSet<T>) -> bool {
1007         assert_eq!(self.domain_size(), other.domain_size());
1008         match self {
1009             HybridBitSet::Sparse(_) => {
1010                 match other {
1011                     HybridBitSet::Sparse(other_sparse) => {
1012                         // Both sets are sparse. Add the elements in
1013                         // `other_sparse` to `self` one at a time. This
1014                         // may or may not cause `self` to be densified.
1015                         let mut changed = false;
1016                         for elem in other_sparse.iter() {
1017                             changed |= self.insert(*elem);
1018                         }
1019                         changed
1020                     }
1021
1022                     HybridBitSet::Dense(other_dense) => self.union(other_dense),
1023                 }
1024             }
1025
1026             HybridBitSet::Dense(self_dense) => self_dense.union(other),
1027         }
1028     }
1029
1030     fn subtract(&mut self, other: &HybridBitSet<T>) -> bool {
1031         assert_eq!(self.domain_size(), other.domain_size());
1032         match self {
1033             HybridBitSet::Sparse(self_sparse) => {
1034                 sequential_update(|elem| self_sparse.remove(elem), other.iter())
1035             }
1036             HybridBitSet::Dense(self_dense) => self_dense.subtract(other),
1037         }
1038     }
1039
1040     fn intersect(&mut self, other: &HybridBitSet<T>) -> bool {
1041         assert_eq!(self.domain_size(), other.domain_size());
1042         match self {
1043             HybridBitSet::Sparse(self_sparse) => {
1044                 sparse_intersect(self_sparse, |elem| other.contains(*elem))
1045             }
1046             HybridBitSet::Dense(self_dense) => match other {
1047                 HybridBitSet::Sparse(other_sparse) => {
1048                     let (updated, changed) = dense_sparse_intersect(self_dense, other_sparse);
1049                     *self = HybridBitSet::Sparse(updated);
1050                     changed
1051                 }
1052                 HybridBitSet::Dense(other_dense) => self_dense.intersect(other_dense),
1053             },
1054         }
1055     }
1056 }
1057
1058 impl<T> Clone for BitSet<T> {
1059     fn clone(&self) -> Self {
1060         BitSet { domain_size: self.domain_size, words: self.words.clone(), marker: PhantomData }
1061     }
1062
1063     fn clone_from(&mut self, from: &Self) {
1064         if self.domain_size != from.domain_size {
1065             self.words.resize(from.domain_size, 0);
1066             self.domain_size = from.domain_size;
1067         }
1068
1069         self.words.copy_from_slice(&from.words);
1070     }
1071 }
1072
1073 impl<T: Idx> fmt::Debug for BitSet<T> {
1074     fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
1075         w.debug_list().entries(self.iter()).finish()
1076     }
1077 }
1078
1079 impl<T: Idx> ToString for BitSet<T> {
1080     fn to_string(&self) -> String {
1081         let mut result = String::new();
1082         let mut sep = '[';
1083
1084         // Note: this is a little endian printout of bytes.
1085
1086         // i tracks how many bits we have printed so far.
1087         let mut i = 0;
1088         for word in &self.words {
1089             let mut word = *word;
1090             for _ in 0..WORD_BYTES {
1091                 // for each byte in `word`:
1092                 let remain = self.domain_size - i;
1093                 // If less than a byte remains, then mask just that many bits.
1094                 let mask = if remain <= 8 { (1 << remain) - 1 } else { 0xFF };
1095                 assert!(mask <= 0xFF);
1096                 let byte = word & mask;
1097
1098                 result.push_str(&format!("{}{:02x}", sep, byte));
1099
1100                 if remain <= 8 {
1101                     break;
1102                 }
1103                 word >>= 8;
1104                 i += 8;
1105                 sep = '-';
1106             }
1107             sep = '|';
1108         }
1109         result.push(']');
1110
1111         result
1112     }
1113 }
1114
1115 pub struct BitIter<'a, T: Idx> {
1116     /// A copy of the current word, but with any already-visited bits cleared.
1117     /// (This lets us use `trailing_zeros()` to find the next set bit.) When it
1118     /// is reduced to 0, we move onto the next word.
1119     word: Word,
1120
1121     /// The offset (measured in bits) of the current word.
1122     offset: usize,
1123
1124     /// Underlying iterator over the words.
1125     iter: slice::Iter<'a, Word>,
1126
1127     marker: PhantomData<T>,
1128 }
1129
1130 impl<'a, T: Idx> BitIter<'a, T> {
1131     #[inline]
1132     fn new(words: &'a [Word]) -> BitIter<'a, T> {
1133         // We initialize `word` and `offset` to degenerate values. On the first
1134         // call to `next()` we will fall through to getting the first word from
1135         // `iter`, which sets `word` to the first word (if there is one) and
1136         // `offset` to 0. Doing it this way saves us from having to maintain
1137         // additional state about whether we have started.
1138         BitIter {
1139             word: 0,
1140             offset: usize::MAX - (WORD_BITS - 1),
1141             iter: words.iter(),
1142             marker: PhantomData,
1143         }
1144     }
1145 }
1146
1147 impl<'a, T: Idx> Iterator for BitIter<'a, T> {
1148     type Item = T;
1149     fn next(&mut self) -> Option<T> {
1150         loop {
1151             if self.word != 0 {
1152                 // Get the position of the next set bit in the current word,
1153                 // then clear the bit.
1154                 let bit_pos = self.word.trailing_zeros() as usize;
1155                 let bit = 1 << bit_pos;
1156                 self.word ^= bit;
1157                 return Some(T::new(bit_pos + self.offset));
1158             }
1159
1160             // Move onto the next word. `wrapping_add()` is needed to handle
1161             // the degenerate initial value given to `offset` in `new()`.
1162             let word = self.iter.next()?;
1163             self.word = *word;
1164             self.offset = self.offset.wrapping_add(WORD_BITS);
1165         }
1166     }
1167 }
1168
1169 #[inline]
1170 fn bitwise<Op>(out_vec: &mut [Word], in_vec: &[Word], op: Op) -> bool
1171 where
1172     Op: Fn(Word, Word) -> Word,
1173 {
1174     assert_eq!(out_vec.len(), in_vec.len());
1175     let mut changed = 0;
1176     for (out_elem, in_elem) in iter::zip(out_vec, in_vec) {
1177         let old_val = *out_elem;
1178         let new_val = op(old_val, *in_elem);
1179         *out_elem = new_val;
1180         // This is essentially equivalent to a != with changed being a bool, but
1181         // in practice this code gets auto-vectorized by the compiler for most
1182         // operators. Using != here causes us to generate quite poor code as the
1183         // compiler tries to go back to a boolean on each loop iteration.
1184         changed |= old_val ^ new_val;
1185     }
1186     changed != 0
1187 }
1188
1189 /// Does this bitwise operation change `out_vec`?
1190 #[inline]
1191 fn bitwise_changes<Op>(out_vec: &[Word], in_vec: &[Word], op: Op) -> bool
1192 where
1193     Op: Fn(Word, Word) -> Word,
1194 {
1195     assert_eq!(out_vec.len(), in_vec.len());
1196     for (out_elem, in_elem) in iter::zip(out_vec, in_vec) {
1197         let old_val = *out_elem;
1198         let new_val = op(old_val, *in_elem);
1199         if old_val != new_val {
1200             return true;
1201         }
1202     }
1203     false
1204 }
1205
1206 const SPARSE_MAX: usize = 8;
1207
1208 /// A fixed-size bitset type with a sparse representation and a maximum of
1209 /// `SPARSE_MAX` elements. The elements are stored as a sorted `ArrayVec` with
1210 /// no duplicates.
1211 ///
1212 /// This type is used by `HybridBitSet`; do not use directly.
1213 #[derive(Clone, Debug)]
1214 pub struct SparseBitSet<T> {
1215     domain_size: usize,
1216     elems: ArrayVec<T, SPARSE_MAX>,
1217 }
1218
1219 impl<T: Idx> SparseBitSet<T> {
1220     fn new_empty(domain_size: usize) -> Self {
1221         SparseBitSet { domain_size, elems: ArrayVec::new() }
1222     }
1223
1224     fn len(&self) -> usize {
1225         self.elems.len()
1226     }
1227
1228     fn is_empty(&self) -> bool {
1229         self.elems.len() == 0
1230     }
1231
1232     fn contains(&self, elem: T) -> bool {
1233         assert!(elem.index() < self.domain_size);
1234         self.elems.contains(&elem)
1235     }
1236
1237     fn insert(&mut self, elem: T) -> bool {
1238         assert!(elem.index() < self.domain_size);
1239         let changed = if let Some(i) = self.elems.iter().position(|&e| e.index() >= elem.index()) {
1240             if self.elems[i] == elem {
1241                 // `elem` is already in the set.
1242                 false
1243             } else {
1244                 // `elem` is smaller than one or more existing elements.
1245                 self.elems.insert(i, elem);
1246                 true
1247             }
1248         } else {
1249             // `elem` is larger than all existing elements.
1250             self.elems.push(elem);
1251             true
1252         };
1253         assert!(self.len() <= SPARSE_MAX);
1254         changed
1255     }
1256
1257     fn remove(&mut self, elem: T) -> bool {
1258         assert!(elem.index() < self.domain_size);
1259         if let Some(i) = self.elems.iter().position(|&e| e == elem) {
1260             self.elems.remove(i);
1261             true
1262         } else {
1263             false
1264         }
1265     }
1266
1267     fn to_dense(&self) -> BitSet<T> {
1268         let mut dense = BitSet::new_empty(self.domain_size);
1269         for elem in self.elems.iter() {
1270             dense.insert(*elem);
1271         }
1272         dense
1273     }
1274
1275     fn iter(&self) -> slice::Iter<'_, T> {
1276         self.elems.iter()
1277     }
1278
1279     bit_relations_inherent_impls! {}
1280 }
1281
1282 impl<T: Idx + Ord> SparseBitSet<T> {
1283     fn last_set_in(&self, range: impl RangeBounds<T>) -> Option<T> {
1284         let mut last_leq = None;
1285         for e in self.iter() {
1286             if range.contains(e) {
1287                 last_leq = Some(*e);
1288             }
1289         }
1290         last_leq
1291     }
1292 }
1293
1294 /// A fixed-size bitset type with a hybrid representation: sparse when there
1295 /// are up to a `SPARSE_MAX` elements in the set, but dense when there are more
1296 /// than `SPARSE_MAX`.
1297 ///
1298 /// This type is especially efficient for sets that typically have a small
1299 /// number of elements, but a large `domain_size`, and are cleared frequently.
1300 ///
1301 /// `T` is an index type, typically a newtyped `usize` wrapper, but it can also
1302 /// just be `usize`.
1303 ///
1304 /// All operations that involve an element will panic if the element is equal
1305 /// to or greater than the domain size. All operations that involve two bitsets
1306 /// will panic if the bitsets have differing domain sizes.
1307 #[derive(Clone)]
1308 pub enum HybridBitSet<T> {
1309     Sparse(SparseBitSet<T>),
1310     Dense(BitSet<T>),
1311 }
1312
1313 impl<T: Idx> fmt::Debug for HybridBitSet<T> {
1314     fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
1315         match self {
1316             Self::Sparse(b) => b.fmt(w),
1317             Self::Dense(b) => b.fmt(w),
1318         }
1319     }
1320 }
1321
1322 impl<T: Idx> HybridBitSet<T> {
1323     pub fn new_empty(domain_size: usize) -> Self {
1324         HybridBitSet::Sparse(SparseBitSet::new_empty(domain_size))
1325     }
1326
1327     pub fn domain_size(&self) -> usize {
1328         match self {
1329             HybridBitSet::Sparse(sparse) => sparse.domain_size,
1330             HybridBitSet::Dense(dense) => dense.domain_size,
1331         }
1332     }
1333
1334     pub fn clear(&mut self) {
1335         let domain_size = self.domain_size();
1336         *self = HybridBitSet::new_empty(domain_size);
1337     }
1338
1339     pub fn contains(&self, elem: T) -> bool {
1340         match self {
1341             HybridBitSet::Sparse(sparse) => sparse.contains(elem),
1342             HybridBitSet::Dense(dense) => dense.contains(elem),
1343         }
1344     }
1345
1346     pub fn superset(&self, other: &HybridBitSet<T>) -> bool {
1347         match (self, other) {
1348             (HybridBitSet::Dense(self_dense), HybridBitSet::Dense(other_dense)) => {
1349                 self_dense.superset(other_dense)
1350             }
1351             _ => {
1352                 assert!(self.domain_size() == other.domain_size());
1353                 other.iter().all(|elem| self.contains(elem))
1354             }
1355         }
1356     }
1357
1358     pub fn is_empty(&self) -> bool {
1359         match self {
1360             HybridBitSet::Sparse(sparse) => sparse.is_empty(),
1361             HybridBitSet::Dense(dense) => dense.is_empty(),
1362         }
1363     }
1364
1365     /// Returns the previous element present in the bitset from `elem`,
1366     /// inclusively of elem. That is, will return `Some(elem)` if elem is in the
1367     /// bitset.
1368     pub fn last_set_in(&self, range: impl RangeBounds<T>) -> Option<T>
1369     where
1370         T: Ord,
1371     {
1372         match self {
1373             HybridBitSet::Sparse(sparse) => sparse.last_set_in(range),
1374             HybridBitSet::Dense(dense) => dense.last_set_in(range),
1375         }
1376     }
1377
1378     pub fn insert(&mut self, elem: T) -> bool {
1379         // No need to check `elem` against `self.domain_size` here because all
1380         // the match cases check it, one way or another.
1381         match self {
1382             HybridBitSet::Sparse(sparse) if sparse.len() < SPARSE_MAX => {
1383                 // The set is sparse and has space for `elem`.
1384                 sparse.insert(elem)
1385             }
1386             HybridBitSet::Sparse(sparse) if sparse.contains(elem) => {
1387                 // The set is sparse and does not have space for `elem`, but
1388                 // that doesn't matter because `elem` is already present.
1389                 false
1390             }
1391             HybridBitSet::Sparse(sparse) => {
1392                 // The set is sparse and full. Convert to a dense set.
1393                 let mut dense = sparse.to_dense();
1394                 let changed = dense.insert(elem);
1395                 assert!(changed);
1396                 *self = HybridBitSet::Dense(dense);
1397                 changed
1398             }
1399             HybridBitSet::Dense(dense) => dense.insert(elem),
1400         }
1401     }
1402
1403     pub fn insert_range(&mut self, elems: impl RangeBounds<T>) {
1404         // No need to check `elem` against `self.domain_size` here because all
1405         // the match cases check it, one way or another.
1406         let start = match elems.start_bound().cloned() {
1407             Bound::Included(start) => start.index(),
1408             Bound::Excluded(start) => start.index() + 1,
1409             Bound::Unbounded => 0,
1410         };
1411         let end = match elems.end_bound().cloned() {
1412             Bound::Included(end) => end.index() + 1,
1413             Bound::Excluded(end) => end.index(),
1414             Bound::Unbounded => self.domain_size() - 1,
1415         };
1416         let Some(len) = end.checked_sub(start) else { return };
1417         match self {
1418             HybridBitSet::Sparse(sparse) if sparse.len() + len < SPARSE_MAX => {
1419                 // The set is sparse and has space for `elems`.
1420                 for elem in start..end {
1421                     sparse.insert(T::new(elem));
1422                 }
1423             }
1424             HybridBitSet::Sparse(sparse) => {
1425                 // The set is sparse and full. Convert to a dense set.
1426                 let mut dense = sparse.to_dense();
1427                 dense.insert_range(elems);
1428                 *self = HybridBitSet::Dense(dense);
1429             }
1430             HybridBitSet::Dense(dense) => dense.insert_range(elems),
1431         }
1432     }
1433
1434     pub fn insert_all(&mut self) {
1435         let domain_size = self.domain_size();
1436         match self {
1437             HybridBitSet::Sparse(_) => {
1438                 *self = HybridBitSet::Dense(BitSet::new_filled(domain_size));
1439             }
1440             HybridBitSet::Dense(dense) => dense.insert_all(),
1441         }
1442     }
1443
1444     pub fn remove(&mut self, elem: T) -> bool {
1445         // Note: we currently don't bother going from Dense back to Sparse.
1446         match self {
1447             HybridBitSet::Sparse(sparse) => sparse.remove(elem),
1448             HybridBitSet::Dense(dense) => dense.remove(elem),
1449         }
1450     }
1451
1452     /// Converts to a dense set, consuming itself in the process.
1453     pub fn to_dense(self) -> BitSet<T> {
1454         match self {
1455             HybridBitSet::Sparse(sparse) => sparse.to_dense(),
1456             HybridBitSet::Dense(dense) => dense,
1457         }
1458     }
1459
1460     pub fn iter(&self) -> HybridIter<'_, T> {
1461         match self {
1462             HybridBitSet::Sparse(sparse) => HybridIter::Sparse(sparse.iter()),
1463             HybridBitSet::Dense(dense) => HybridIter::Dense(dense.iter()),
1464         }
1465     }
1466
1467     bit_relations_inherent_impls! {}
1468 }
1469
1470 pub enum HybridIter<'a, T: Idx> {
1471     Sparse(slice::Iter<'a, T>),
1472     Dense(BitIter<'a, T>),
1473 }
1474
1475 impl<'a, T: Idx> Iterator for HybridIter<'a, T> {
1476     type Item = T;
1477
1478     fn next(&mut self) -> Option<T> {
1479         match self {
1480             HybridIter::Sparse(sparse) => sparse.next().copied(),
1481             HybridIter::Dense(dense) => dense.next(),
1482         }
1483     }
1484 }
1485
1486 /// A resizable bitset type with a dense representation.
1487 ///
1488 /// `T` is an index type, typically a newtyped `usize` wrapper, but it can also
1489 /// just be `usize`.
1490 ///
1491 /// All operations that involve an element will panic if the element is equal
1492 /// to or greater than the domain size.
1493 #[derive(Clone, Debug, PartialEq)]
1494 pub struct GrowableBitSet<T: Idx> {
1495     bit_set: BitSet<T>,
1496 }
1497
1498 impl<T: Idx> Default for GrowableBitSet<T> {
1499     fn default() -> Self {
1500         GrowableBitSet::new_empty()
1501     }
1502 }
1503
1504 impl<T: Idx> GrowableBitSet<T> {
1505     /// Ensure that the set can hold at least `min_domain_size` elements.
1506     pub fn ensure(&mut self, min_domain_size: usize) {
1507         if self.bit_set.domain_size < min_domain_size {
1508             self.bit_set.domain_size = min_domain_size;
1509         }
1510
1511         let min_num_words = num_words(min_domain_size);
1512         if self.bit_set.words.len() < min_num_words {
1513             self.bit_set.words.resize(min_num_words, 0)
1514         }
1515     }
1516
1517     pub fn new_empty() -> GrowableBitSet<T> {
1518         GrowableBitSet { bit_set: BitSet::new_empty(0) }
1519     }
1520
1521     pub fn with_capacity(capacity: usize) -> GrowableBitSet<T> {
1522         GrowableBitSet { bit_set: BitSet::new_empty(capacity) }
1523     }
1524
1525     /// Returns `true` if the set has changed.
1526     #[inline]
1527     pub fn insert(&mut self, elem: T) -> bool {
1528         self.ensure(elem.index() + 1);
1529         self.bit_set.insert(elem)
1530     }
1531
1532     /// Returns `true` if the set has changed.
1533     #[inline]
1534     pub fn remove(&mut self, elem: T) -> bool {
1535         self.ensure(elem.index() + 1);
1536         self.bit_set.remove(elem)
1537     }
1538
1539     #[inline]
1540     pub fn is_empty(&self) -> bool {
1541         self.bit_set.is_empty()
1542     }
1543
1544     #[inline]
1545     pub fn contains(&self, elem: T) -> bool {
1546         let (word_index, mask) = word_index_and_mask(elem);
1547         self.bit_set.words.get(word_index).map_or(false, |word| (word & mask) != 0)
1548     }
1549
1550     #[inline]
1551     pub fn iter(&self) -> BitIter<'_, T> {
1552         self.bit_set.iter()
1553     }
1554
1555     #[inline]
1556     pub fn len(&self) -> usize {
1557         self.bit_set.count()
1558     }
1559 }
1560
1561 impl<T: Idx> From<BitSet<T>> for GrowableBitSet<T> {
1562     fn from(bit_set: BitSet<T>) -> Self {
1563         Self { bit_set }
1564     }
1565 }
1566
1567 /// A fixed-size 2D bit matrix type with a dense representation.
1568 ///
1569 /// `R` and `C` are index types used to identify rows and columns respectively;
1570 /// typically newtyped `usize` wrappers, but they can also just be `usize`.
1571 ///
1572 /// All operations that involve a row and/or column index will panic if the
1573 /// index exceeds the relevant bound.
1574 #[derive(Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
1575 pub struct BitMatrix<R: Idx, C: Idx> {
1576     num_rows: usize,
1577     num_columns: usize,
1578     words: Vec<Word>,
1579     marker: PhantomData<(R, C)>,
1580 }
1581
1582 impl<R: Idx, C: Idx> BitMatrix<R, C> {
1583     /// Creates a new `rows x columns` matrix, initially empty.
1584     pub fn new(num_rows: usize, num_columns: usize) -> BitMatrix<R, C> {
1585         // For every element, we need one bit for every other
1586         // element. Round up to an even number of words.
1587         let words_per_row = num_words(num_columns);
1588         BitMatrix {
1589             num_rows,
1590             num_columns,
1591             words: vec![0; num_rows * words_per_row],
1592             marker: PhantomData,
1593         }
1594     }
1595
1596     /// Creates a new matrix, with `row` used as the value for every row.
1597     pub fn from_row_n(row: &BitSet<C>, num_rows: usize) -> BitMatrix<R, C> {
1598         let num_columns = row.domain_size();
1599         let words_per_row = num_words(num_columns);
1600         assert_eq!(words_per_row, row.words().len());
1601         BitMatrix {
1602             num_rows,
1603             num_columns,
1604             words: iter::repeat(row.words()).take(num_rows).flatten().cloned().collect(),
1605             marker: PhantomData,
1606         }
1607     }
1608
1609     pub fn rows(&self) -> impl Iterator<Item = R> {
1610         (0..self.num_rows).map(R::new)
1611     }
1612
1613     /// The range of bits for a given row.
1614     fn range(&self, row: R) -> (usize, usize) {
1615         let words_per_row = num_words(self.num_columns);
1616         let start = row.index() * words_per_row;
1617         (start, start + words_per_row)
1618     }
1619
1620     /// Sets the cell at `(row, column)` to true. Put another way, insert
1621     /// `column` to the bitset for `row`.
1622     ///
1623     /// Returns `true` if this changed the matrix.
1624     pub fn insert(&mut self, row: R, column: C) -> bool {
1625         assert!(row.index() < self.num_rows && column.index() < self.num_columns);
1626         let (start, _) = self.range(row);
1627         let (word_index, mask) = word_index_and_mask(column);
1628         let words = &mut self.words[..];
1629         let word = words[start + word_index];
1630         let new_word = word | mask;
1631         words[start + word_index] = new_word;
1632         word != new_word
1633     }
1634
1635     /// Do the bits from `row` contain `column`? Put another way, is
1636     /// the matrix cell at `(row, column)` true?  Put yet another way,
1637     /// if the matrix represents (transitive) reachability, can
1638     /// `row` reach `column`?
1639     pub fn contains(&self, row: R, column: C) -> bool {
1640         assert!(row.index() < self.num_rows && column.index() < self.num_columns);
1641         let (start, _) = self.range(row);
1642         let (word_index, mask) = word_index_and_mask(column);
1643         (self.words[start + word_index] & mask) != 0
1644     }
1645
1646     /// Returns those indices that are true in rows `a` and `b`. This
1647     /// is an *O*(*n*) operation where *n* is the number of elements
1648     /// (somewhat independent from the actual size of the
1649     /// intersection, in particular).
1650     pub fn intersect_rows(&self, row1: R, row2: R) -> Vec<C> {
1651         assert!(row1.index() < self.num_rows && row2.index() < self.num_rows);
1652         let (row1_start, row1_end) = self.range(row1);
1653         let (row2_start, row2_end) = self.range(row2);
1654         let mut result = Vec::with_capacity(self.num_columns);
1655         for (base, (i, j)) in (row1_start..row1_end).zip(row2_start..row2_end).enumerate() {
1656             let mut v = self.words[i] & self.words[j];
1657             for bit in 0..WORD_BITS {
1658                 if v == 0 {
1659                     break;
1660                 }
1661                 if v & 0x1 != 0 {
1662                     result.push(C::new(base * WORD_BITS + bit));
1663                 }
1664                 v >>= 1;
1665             }
1666         }
1667         result
1668     }
1669
1670     /// Adds the bits from row `read` to the bits from row `write`, and
1671     /// returns `true` if anything changed.
1672     ///
1673     /// This is used when computing transitive reachability because if
1674     /// you have an edge `write -> read`, because in that case
1675     /// `write` can reach everything that `read` can (and
1676     /// potentially more).
1677     pub fn union_rows(&mut self, read: R, write: R) -> bool {
1678         assert!(read.index() < self.num_rows && write.index() < self.num_rows);
1679         let (read_start, read_end) = self.range(read);
1680         let (write_start, write_end) = self.range(write);
1681         let words = &mut self.words[..];
1682         let mut changed = false;
1683         for (read_index, write_index) in iter::zip(read_start..read_end, write_start..write_end) {
1684             let word = words[write_index];
1685             let new_word = word | words[read_index];
1686             words[write_index] = new_word;
1687             changed |= word != new_word;
1688         }
1689         changed
1690     }
1691
1692     /// Adds the bits from `with` to the bits from row `write`, and
1693     /// returns `true` if anything changed.
1694     pub fn union_row_with(&mut self, with: &BitSet<C>, write: R) -> bool {
1695         assert!(write.index() < self.num_rows);
1696         assert_eq!(with.domain_size(), self.num_columns);
1697         let (write_start, write_end) = self.range(write);
1698         let mut changed = false;
1699         for (read_index, write_index) in iter::zip(0..with.words().len(), write_start..write_end) {
1700             let word = self.words[write_index];
1701             let new_word = word | with.words()[read_index];
1702             self.words[write_index] = new_word;
1703             changed |= word != new_word;
1704         }
1705         changed
1706     }
1707
1708     /// Sets every cell in `row` to true.
1709     pub fn insert_all_into_row(&mut self, row: R) {
1710         assert!(row.index() < self.num_rows);
1711         let (start, end) = self.range(row);
1712         let words = &mut self.words[..];
1713         for index in start..end {
1714             words[index] = !0;
1715         }
1716         clear_excess_bits_in_final_word(self.num_columns, &mut self.words[..end]);
1717     }
1718
1719     /// Gets a slice of the underlying words.
1720     pub fn words(&self) -> &[Word] {
1721         &self.words
1722     }
1723
1724     /// Iterates through all the columns set to true in a given row of
1725     /// the matrix.
1726     pub fn iter(&self, row: R) -> BitIter<'_, C> {
1727         assert!(row.index() < self.num_rows);
1728         let (start, end) = self.range(row);
1729         BitIter::new(&self.words[start..end])
1730     }
1731
1732     /// Returns the number of elements in `row`.
1733     pub fn count(&self, row: R) -> usize {
1734         let (start, end) = self.range(row);
1735         self.words[start..end].iter().map(|e| e.count_ones() as usize).sum()
1736     }
1737 }
1738
1739 impl<R: Idx, C: Idx> fmt::Debug for BitMatrix<R, C> {
1740     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1741         /// Forces its contents to print in regular mode instead of alternate mode.
1742         struct OneLinePrinter<T>(T);
1743         impl<T: fmt::Debug> fmt::Debug for OneLinePrinter<T> {
1744             fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1745                 write!(fmt, "{:?}", self.0)
1746             }
1747         }
1748
1749         write!(fmt, "BitMatrix({}x{}) ", self.num_rows, self.num_columns)?;
1750         let items = self.rows().flat_map(|r| self.iter(r).map(move |c| (r, c)));
1751         fmt.debug_set().entries(items.map(OneLinePrinter)).finish()
1752     }
1753 }
1754
1755 /// A fixed-column-size, variable-row-size 2D bit matrix with a moderately
1756 /// sparse representation.
1757 ///
1758 /// Initially, every row has no explicit representation. If any bit within a
1759 /// row is set, the entire row is instantiated as `Some(<HybridBitSet>)`.
1760 /// Furthermore, any previously uninstantiated rows prior to it will be
1761 /// instantiated as `None`. Those prior rows may themselves become fully
1762 /// instantiated later on if any of their bits are set.
1763 ///
1764 /// `R` and `C` are index types used to identify rows and columns respectively;
1765 /// typically newtyped `usize` wrappers, but they can also just be `usize`.
1766 #[derive(Clone, Debug)]
1767 pub struct SparseBitMatrix<R, C>
1768 where
1769     R: Idx,
1770     C: Idx,
1771 {
1772     num_columns: usize,
1773     rows: IndexVec<R, Option<HybridBitSet<C>>>,
1774 }
1775
1776 impl<R: Idx, C: Idx> SparseBitMatrix<R, C> {
1777     /// Creates a new empty sparse bit matrix with no rows or columns.
1778     pub fn new(num_columns: usize) -> Self {
1779         Self { num_columns, rows: IndexVec::new() }
1780     }
1781
1782     fn ensure_row(&mut self, row: R) -> &mut HybridBitSet<C> {
1783         // Instantiate any missing rows up to and including row `row` with an empty HybridBitSet.
1784         // Then replace row `row` with a full HybridBitSet if necessary.
1785         self.rows.get_or_insert_with(row, || HybridBitSet::new_empty(self.num_columns))
1786     }
1787
1788     /// Sets the cell at `(row, column)` to true. Put another way, insert
1789     /// `column` to the bitset for `row`.
1790     ///
1791     /// Returns `true` if this changed the matrix.
1792     pub fn insert(&mut self, row: R, column: C) -> bool {
1793         self.ensure_row(row).insert(column)
1794     }
1795
1796     /// Sets the cell at `(row, column)` to false. Put another way, delete
1797     /// `column` from the bitset for `row`. Has no effect if `row` does not
1798     /// exist.
1799     ///
1800     /// Returns `true` if this changed the matrix.
1801     pub fn remove(&mut self, row: R, column: C) -> bool {
1802         match self.rows.get_mut(row) {
1803             Some(Some(row)) => row.remove(column),
1804             _ => false,
1805         }
1806     }
1807
1808     /// Sets all columns at `row` to false. Has no effect if `row` does
1809     /// not exist.
1810     pub fn clear(&mut self, row: R) {
1811         if let Some(Some(row)) = self.rows.get_mut(row) {
1812             row.clear();
1813         }
1814     }
1815
1816     /// Do the bits from `row` contain `column`? Put another way, is
1817     /// the matrix cell at `(row, column)` true?  Put yet another way,
1818     /// if the matrix represents (transitive) reachability, can
1819     /// `row` reach `column`?
1820     pub fn contains(&self, row: R, column: C) -> bool {
1821         self.row(row).map_or(false, |r| r.contains(column))
1822     }
1823
1824     /// Adds the bits from row `read` to the bits from row `write`, and
1825     /// returns `true` if anything changed.
1826     ///
1827     /// This is used when computing transitive reachability because if
1828     /// you have an edge `write -> read`, because in that case
1829     /// `write` can reach everything that `read` can (and
1830     /// potentially more).
1831     pub fn union_rows(&mut self, read: R, write: R) -> bool {
1832         if read == write || self.row(read).is_none() {
1833             return false;
1834         }
1835
1836         self.ensure_row(write);
1837         if let (Some(read_row), Some(write_row)) = self.rows.pick2_mut(read, write) {
1838             write_row.union(read_row)
1839         } else {
1840             unreachable!()
1841         }
1842     }
1843
1844     /// Insert all bits in the given row.
1845     pub fn insert_all_into_row(&mut self, row: R) {
1846         self.ensure_row(row).insert_all();
1847     }
1848
1849     pub fn rows(&self) -> impl Iterator<Item = R> {
1850         self.rows.indices()
1851     }
1852
1853     /// Iterates through all the columns set to true in a given row of
1854     /// the matrix.
1855     pub fn iter<'a>(&'a self, row: R) -> impl Iterator<Item = C> + 'a {
1856         self.row(row).into_iter().flat_map(|r| r.iter())
1857     }
1858
1859     pub fn row(&self, row: R) -> Option<&HybridBitSet<C>> {
1860         self.rows.get(row)?.as_ref()
1861     }
1862
1863     /// Intersects `row` with `set`. `set` can be either `BitSet` or
1864     /// `HybridBitSet`. Has no effect if `row` does not exist.
1865     ///
1866     /// Returns true if the row was changed.
1867     pub fn intersect_row<Set>(&mut self, row: R, set: &Set) -> bool
1868     where
1869         HybridBitSet<C>: BitRelations<Set>,
1870     {
1871         match self.rows.get_mut(row) {
1872             Some(Some(row)) => row.intersect(set),
1873             _ => false,
1874         }
1875     }
1876
1877     /// Subtracts `set from `row`. `set` can be either `BitSet` or
1878     /// `HybridBitSet`. Has no effect if `row` does not exist.
1879     ///
1880     /// Returns true if the row was changed.
1881     pub fn subtract_row<Set>(&mut self, row: R, set: &Set) -> bool
1882     where
1883         HybridBitSet<C>: BitRelations<Set>,
1884     {
1885         match self.rows.get_mut(row) {
1886             Some(Some(row)) => row.subtract(set),
1887             _ => false,
1888         }
1889     }
1890
1891     /// Unions `row` with `set`. `set` can be either `BitSet` or
1892     /// `HybridBitSet`.
1893     ///
1894     /// Returns true if the row was changed.
1895     pub fn union_row<Set>(&mut self, row: R, set: &Set) -> bool
1896     where
1897         HybridBitSet<C>: BitRelations<Set>,
1898     {
1899         self.ensure_row(row).union(set)
1900     }
1901 }
1902
1903 #[inline]
1904 fn num_words<T: Idx>(domain_size: T) -> usize {
1905     (domain_size.index() + WORD_BITS - 1) / WORD_BITS
1906 }
1907
1908 #[inline]
1909 fn num_chunks<T: Idx>(domain_size: T) -> usize {
1910     assert!(domain_size.index() > 0);
1911     (domain_size.index() + CHUNK_BITS - 1) / CHUNK_BITS
1912 }
1913
1914 #[inline]
1915 fn word_index_and_mask<T: Idx>(elem: T) -> (usize, Word) {
1916     let elem = elem.index();
1917     let word_index = elem / WORD_BITS;
1918     let mask = 1 << (elem % WORD_BITS);
1919     (word_index, mask)
1920 }
1921
1922 #[inline]
1923 fn chunk_index<T: Idx>(elem: T) -> usize {
1924     elem.index() / CHUNK_BITS
1925 }
1926
1927 #[inline]
1928 fn chunk_word_index_and_mask<T: Idx>(elem: T) -> (usize, Word) {
1929     let chunk_elem = elem.index() % CHUNK_BITS;
1930     word_index_and_mask(chunk_elem)
1931 }
1932
1933 fn clear_excess_bits_in_final_word(domain_size: usize, words: &mut [Word]) {
1934     let num_bits_in_final_word = domain_size % WORD_BITS;
1935     if num_bits_in_final_word > 0 {
1936         let mask = (1 << num_bits_in_final_word) - 1;
1937         words[words.len() - 1] &= mask;
1938     }
1939 }
1940
1941 #[inline]
1942 fn max_bit(word: Word) -> usize {
1943     WORD_BITS - 1 - word.leading_zeros() as usize
1944 }
1945
1946 /// Integral type used to represent the bit set.
1947 pub trait FiniteBitSetTy:
1948     BitAnd<Output = Self>
1949     + BitAndAssign
1950     + BitOrAssign
1951     + Clone
1952     + Copy
1953     + Shl
1954     + Not<Output = Self>
1955     + PartialEq
1956     + Sized
1957 {
1958     /// Size of the domain representable by this type, e.g. 64 for `u64`.
1959     const DOMAIN_SIZE: u32;
1960
1961     /// Value which represents the `FiniteBitSet` having every bit set.
1962     const FILLED: Self;
1963     /// Value which represents the `FiniteBitSet` having no bits set.
1964     const EMPTY: Self;
1965
1966     /// Value for one as the integral type.
1967     const ONE: Self;
1968     /// Value for zero as the integral type.
1969     const ZERO: Self;
1970
1971     /// Perform a checked left shift on the integral type.
1972     fn checked_shl(self, rhs: u32) -> Option<Self>;
1973     /// Perform a checked right shift on the integral type.
1974     fn checked_shr(self, rhs: u32) -> Option<Self>;
1975 }
1976
1977 impl FiniteBitSetTy for u32 {
1978     const DOMAIN_SIZE: u32 = 32;
1979
1980     const FILLED: Self = Self::MAX;
1981     const EMPTY: Self = Self::MIN;
1982
1983     const ONE: Self = 1u32;
1984     const ZERO: Self = 0u32;
1985
1986     fn checked_shl(self, rhs: u32) -> Option<Self> {
1987         self.checked_shl(rhs)
1988     }
1989
1990     fn checked_shr(self, rhs: u32) -> Option<Self> {
1991         self.checked_shr(rhs)
1992     }
1993 }
1994
1995 impl std::fmt::Debug for FiniteBitSet<u32> {
1996     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1997         write!(f, "{:032b}", self.0)
1998     }
1999 }
2000
2001 impl FiniteBitSetTy for u64 {
2002     const DOMAIN_SIZE: u32 = 64;
2003
2004     const FILLED: Self = Self::MAX;
2005     const EMPTY: Self = Self::MIN;
2006
2007     const ONE: Self = 1u64;
2008     const ZERO: Self = 0u64;
2009
2010     fn checked_shl(self, rhs: u32) -> Option<Self> {
2011         self.checked_shl(rhs)
2012     }
2013
2014     fn checked_shr(self, rhs: u32) -> Option<Self> {
2015         self.checked_shr(rhs)
2016     }
2017 }
2018
2019 impl std::fmt::Debug for FiniteBitSet<u64> {
2020     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2021         write!(f, "{:064b}", self.0)
2022     }
2023 }
2024
2025 impl FiniteBitSetTy for u128 {
2026     const DOMAIN_SIZE: u32 = 128;
2027
2028     const FILLED: Self = Self::MAX;
2029     const EMPTY: Self = Self::MIN;
2030
2031     const ONE: Self = 1u128;
2032     const ZERO: Self = 0u128;
2033
2034     fn checked_shl(self, rhs: u32) -> Option<Self> {
2035         self.checked_shl(rhs)
2036     }
2037
2038     fn checked_shr(self, rhs: u32) -> Option<Self> {
2039         self.checked_shr(rhs)
2040     }
2041 }
2042
2043 impl std::fmt::Debug for FiniteBitSet<u128> {
2044     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2045         write!(f, "{:0128b}", self.0)
2046     }
2047 }
2048
2049 /// A fixed-sized bitset type represented by an integer type. Indices outwith than the range
2050 /// representable by `T` are considered set.
2051 #[derive(Copy, Clone, Eq, PartialEq, Decodable, Encodable)]
2052 pub struct FiniteBitSet<T: FiniteBitSetTy>(pub T);
2053
2054 impl<T: FiniteBitSetTy> FiniteBitSet<T> {
2055     /// Creates a new, empty bitset.
2056     pub fn new_empty() -> Self {
2057         Self(T::EMPTY)
2058     }
2059
2060     /// Sets the `index`th bit.
2061     pub fn set(&mut self, index: u32) {
2062         self.0 |= T::ONE.checked_shl(index).unwrap_or(T::ZERO);
2063     }
2064
2065     /// Unsets the `index`th bit.
2066     pub fn clear(&mut self, index: u32) {
2067         self.0 &= !T::ONE.checked_shl(index).unwrap_or(T::ZERO);
2068     }
2069
2070     /// Sets the `i`th to `j`th bits.
2071     pub fn set_range(&mut self, range: Range<u32>) {
2072         let bits = T::FILLED
2073             .checked_shl(range.end - range.start)
2074             .unwrap_or(T::ZERO)
2075             .not()
2076             .checked_shl(range.start)
2077             .unwrap_or(T::ZERO);
2078         self.0 |= bits;
2079     }
2080
2081     /// Is the set empty?
2082     pub fn is_empty(&self) -> bool {
2083         self.0 == T::EMPTY
2084     }
2085
2086     /// Returns the domain size of the bitset.
2087     pub fn within_domain(&self, index: u32) -> bool {
2088         index < T::DOMAIN_SIZE
2089     }
2090
2091     /// Returns if the `index`th bit is set.
2092     pub fn contains(&self, index: u32) -> Option<bool> {
2093         self.within_domain(index)
2094             .then(|| ((self.0.checked_shr(index).unwrap_or(T::ONE)) & T::ONE) == T::ONE)
2095     }
2096 }
2097
2098 impl<T: FiniteBitSetTy> Default for FiniteBitSet<T> {
2099     fn default() -> Self {
2100         Self::new_empty()
2101     }
2102 }