Skip to main content

rustc_index/
bit_set.rs

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