Skip to main content

solar_data_structures/bit_set/
mod.rs

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