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