Skip to main content

rustc_index/
bit_set.rs

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