1 use crate::indexed_vec::{Idx, IndexVec};
2 use smallvec::SmallVec;
5 use std::marker::PhantomData;
14 pub const WORD_BYTES: usize = mem::size_of::<Word>();
15 pub const WORD_BITS: usize = WORD_BYTES * 8;
17 /// A fixed-size bitset type with a dense representation. It does not support
18 /// resizing after creation; use `GrowableBitSet` for that.
20 /// `T` is an index type, typically a newtyped `usize` wrapper, but it can also
23 /// All operations that involve an element will panic if the element is equal
24 /// to or greater than the domain size. All operations that involve two bitsets
25 /// will panic if the bitsets have differing domain sizes.
26 #[derive(Clone, Eq, PartialEq, RustcDecodable, RustcEncodable)]
27 pub struct BitSet<T: Idx> {
30 marker: PhantomData<T>,
33 impl<T: Idx> BitSet<T> {
34 /// Creates a new, empty bitset with a given `domain_size`.
36 pub fn new_empty(domain_size: usize) -> BitSet<T> {
37 let num_words = num_words(domain_size);
40 words: vec![0; num_words],
45 /// Creates a new, filled bitset with a given `domain_size`.
47 pub fn new_filled(domain_size: usize) -> BitSet<T> {
48 let num_words = num_words(domain_size);
49 let mut result = BitSet {
51 words: vec![!0; num_words],
54 result.clear_excess_bits();
58 /// Gets the domain size.
59 pub fn domain_size(&self) -> usize {
63 /// Clear all elements.
65 pub fn clear(&mut self) {
66 for word in &mut self.words {
71 /// Clear excess bits in the final word.
72 fn clear_excess_bits(&mut self) {
73 let num_bits_in_final_word = self.domain_size % WORD_BITS;
74 if num_bits_in_final_word > 0 {
75 let mask = (1 << num_bits_in_final_word) - 1;
76 let final_word_idx = self.words.len() - 1;
77 self.words[final_word_idx] &= mask;
81 /// Efficiently overwrite `self` with `other`.
82 pub fn overwrite(&mut self, other: &BitSet<T>) {
83 assert!(self.domain_size == other.domain_size);
84 self.words.clone_from_slice(&other.words);
87 /// Count the number of set bits in the set.
88 pub fn count(&self) -> usize {
89 self.words.iter().map(|e| e.count_ones() as usize).sum()
92 /// Returns `true` if `self` contains `elem`.
94 pub fn contains(&self, elem: T) -> bool {
95 assert!(elem.index() < self.domain_size);
96 let (word_index, mask) = word_index_and_mask(elem);
97 (self.words[word_index] & mask) != 0
100 /// Is `self` is a (non-strict) superset of `other`?
102 pub fn superset(&self, other: &BitSet<T>) -> bool {
103 assert_eq!(self.domain_size, other.domain_size);
104 self.words.iter().zip(&other.words).all(|(a, b)| (a & b) == *b)
107 /// Is the set empty?
109 pub fn is_empty(&self) -> bool {
110 self.words.iter().all(|a| *a == 0)
113 /// Insert `elem`. Returns whether the set has changed.
115 pub fn insert(&mut self, elem: T) -> bool {
116 assert!(elem.index() < self.domain_size);
117 let (word_index, mask) = word_index_and_mask(elem);
118 let word_ref = &mut self.words[word_index];
119 let word = *word_ref;
120 let new_word = word | mask;
121 *word_ref = new_word;
125 /// Sets all bits to true.
126 pub fn insert_all(&mut self) {
127 for word in &mut self.words {
130 self.clear_excess_bits();
133 /// Returns `true` if the set has changed.
135 pub fn remove(&mut self, elem: T) -> bool {
136 assert!(elem.index() < self.domain_size);
137 let (word_index, mask) = word_index_and_mask(elem);
138 let word_ref = &mut self.words[word_index];
139 let word = *word_ref;
140 let new_word = word & !mask;
141 *word_ref = new_word;
145 /// Sets `self = self | other` and returns `true` if `self` changed
146 /// (i.e., if new bits were added).
147 pub fn union(&mut self, other: &impl UnionIntoBitSet<T>) -> bool {
148 other.union_into(self)
151 /// Sets `self = self - other` and returns `true` if `self` changed.
152 /// (i.e., if any bits were removed).
153 pub fn subtract(&mut self, other: &impl SubtractFromBitSet<T>) -> bool {
154 other.subtract_from(self)
157 /// Sets `self = self & other` and return `true` if `self` changed.
158 /// (i.e., if any bits were removed).
159 pub fn intersect(&mut self, other: &BitSet<T>) -> bool {
160 assert_eq!(self.domain_size, other.domain_size);
161 bitwise(&mut self.words, &other.words, |a, b| { a & b })
164 /// Gets a slice of the underlying words.
165 pub fn words(&self) -> &[Word] {
169 /// Iterates over the indices of set bits in a sorted order.
171 pub fn iter(&self) -> BitIter<'_, T> {
174 iter: self.words.iter().enumerate(),
179 /// Duplicates the set as a hybrid set.
180 pub fn to_hybrid(&self) -> HybridBitSet<T> {
181 // Note: we currently don't bother trying to make a Sparse set.
182 HybridBitSet::Dense(self.to_owned())
185 /// Set `self = self | other`. In contrast to `union` returns `true` if the set contains at
186 /// least one bit that is not in `other` (i.e. `other` is not a superset of `self`).
188 /// This is an optimization for union of a hybrid bitset.
189 fn reverse_union_sparse(&mut self, sparse: &SparseBitSet<T>) -> bool {
190 assert!(sparse.domain_size == self.domain_size);
191 self.clear_excess_bits();
193 let mut not_already = false;
194 // Index of the current word not yet merged.
195 let mut current_index = 0;
196 // Mask of bits that came from the sparse set in the current word.
197 let mut new_bit_mask = 0;
198 for (word_index, mask) in sparse.iter().map(|x| word_index_and_mask(*x)) {
199 // Next bit is in a word not inspected yet.
200 if word_index > current_index {
201 self.words[current_index] |= new_bit_mask;
202 // Were there any bits in the old word that did not occur in the sparse set?
203 not_already |= (self.words[current_index] ^ new_bit_mask) != 0;
204 // Check all words we skipped for any set bit.
205 not_already |= self.words[current_index+1..word_index].iter().any(|&x| x != 0);
207 current_index = word_index;
208 // Reset bit mask, no bits have been merged yet.
211 // Add bit and mark it as coming from the sparse set.
212 // self.words[word_index] |= mask;
213 new_bit_mask |= mask;
215 self.words[current_index] |= new_bit_mask;
216 // Any bits in the last inspected word that were not in the sparse set?
217 not_already |= (self.words[current_index] ^ new_bit_mask) != 0;
218 // Any bits in the tail? Note `clear_excess_bits` before.
219 not_already |= self.words[current_index+1..].iter().any(|&x| x != 0);
225 /// This is implemented by all the bitsets so that BitSet::union() can be
226 /// passed any type of bitset.
227 pub trait UnionIntoBitSet<T: Idx> {
228 // Performs `other = other | self`.
229 fn union_into(&self, other: &mut BitSet<T>) -> bool;
232 /// This is implemented by all the bitsets so that BitSet::subtract() can be
233 /// passed any type of bitset.
234 pub trait SubtractFromBitSet<T: Idx> {
235 // Performs `other = other - self`.
236 fn subtract_from(&self, other: &mut BitSet<T>) -> bool;
239 impl<T: Idx> UnionIntoBitSet<T> for BitSet<T> {
240 fn union_into(&self, other: &mut BitSet<T>) -> bool {
241 assert_eq!(self.domain_size, other.domain_size);
242 bitwise(&mut other.words, &self.words, |a, b| { a | b })
246 impl<T: Idx> SubtractFromBitSet<T> for BitSet<T> {
247 fn subtract_from(&self, other: &mut BitSet<T>) -> bool {
248 assert_eq!(self.domain_size, other.domain_size);
249 bitwise(&mut other.words, &self.words, |a, b| { a & !b })
253 impl<T: Idx> fmt::Debug for BitSet<T> {
254 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
256 .entries(self.iter())
261 impl<T: Idx> ToString for BitSet<T> {
262 fn to_string(&self) -> String {
263 let mut result = String::new();
266 // Note: this is a little endian printout of bytes.
268 // i tracks how many bits we have printed so far.
270 for word in &self.words {
271 let mut word = *word;
272 for _ in 0..WORD_BYTES { // for each byte in `word`:
273 let remain = self.domain_size - i;
274 // If less than a byte remains, then mask just that many bits.
275 let mask = if remain <= 8 { (1 << remain) - 1 } else { 0xFF };
276 assert!(mask <= 0xFF);
277 let byte = word & mask;
279 result.push_str(&format!("{}{:02x}", sep, byte));
281 if remain <= 8 { break; }
294 pub struct BitIter<'a, T: Idx> {
295 cur: Option<(Word, usize)>,
296 iter: iter::Enumerate<slice::Iter<'a, Word>>,
297 marker: PhantomData<T>
300 impl<'a, T: Idx> Iterator for BitIter<'a, T> {
302 fn next(&mut self) -> Option<T> {
304 if let Some((ref mut word, offset)) = self.cur {
305 let bit_pos = word.trailing_zeros() as usize;
306 if bit_pos != WORD_BITS {
307 let bit = 1 << bit_pos;
309 return Some(T::new(bit_pos + offset))
313 let (i, word) = self.iter.next()?;
314 self.cur = Some((*word, WORD_BITS * i));
320 fn bitwise<Op>(out_vec: &mut [Word], in_vec: &[Word], op: Op) -> bool
321 where Op: Fn(Word, Word) -> Word
323 assert_eq!(out_vec.len(), in_vec.len());
324 let mut changed = false;
325 for (out_elem, in_elem) in out_vec.iter_mut().zip(in_vec.iter()) {
326 let old_val = *out_elem;
327 let new_val = op(old_val, *in_elem);
329 changed |= old_val != new_val;
334 const SPARSE_MAX: usize = 8;
336 /// A fixed-size bitset type with a sparse representation and a maximum of
337 /// `SPARSE_MAX` elements. The elements are stored as a sorted `SmallVec` with
338 /// no duplicates; although `SmallVec` can spill its elements to the heap, that
339 /// never happens within this type because of the `SPARSE_MAX` limit.
341 /// This type is used by `HybridBitSet`; do not use directly.
342 #[derive(Clone, Debug)]
343 pub struct SparseBitSet<T: Idx> {
345 elems: SmallVec<[T; SPARSE_MAX]>,
348 impl<T: Idx> SparseBitSet<T> {
349 fn new_empty(domain_size: usize) -> Self {
352 elems: SmallVec::new()
356 fn len(&self) -> usize {
360 fn is_empty(&self) -> bool {
361 self.elems.len() == 0
364 fn contains(&self, elem: T) -> bool {
365 assert!(elem.index() < self.domain_size);
366 self.elems.contains(&elem)
369 fn insert(&mut self, elem: T) -> bool {
370 assert!(elem.index() < self.domain_size);
371 let changed = if let Some(i) = self.elems.iter().position(|&e| e >= elem) {
372 if self.elems[i] == elem {
373 // `elem` is already in the set.
376 // `elem` is smaller than one or more existing elements.
377 self.elems.insert(i, elem);
381 // `elem` is larger than all existing elements.
382 self.elems.push(elem);
385 assert!(self.len() <= SPARSE_MAX);
389 fn remove(&mut self, elem: T) -> bool {
390 assert!(elem.index() < self.domain_size);
391 if let Some(i) = self.elems.iter().position(|&e| e == elem) {
392 self.elems.remove(i);
399 fn to_dense(&self) -> BitSet<T> {
400 let mut dense = BitSet::new_empty(self.domain_size);
401 for elem in self.elems.iter() {
407 fn iter(&self) -> slice::Iter<'_, T> {
412 impl<T: Idx> UnionIntoBitSet<T> for SparseBitSet<T> {
413 fn union_into(&self, other: &mut BitSet<T>) -> bool {
414 assert_eq!(self.domain_size, other.domain_size);
415 let mut changed = false;
416 for elem in self.iter() {
417 changed |= other.insert(*elem);
423 impl<T: Idx> SubtractFromBitSet<T> for SparseBitSet<T> {
424 fn subtract_from(&self, other: &mut BitSet<T>) -> bool {
425 assert_eq!(self.domain_size, other.domain_size);
426 let mut changed = false;
427 for elem in self.iter() {
428 changed |= other.remove(*elem);
434 /// A fixed-size bitset type with a hybrid representation: sparse when there
435 /// are up to a `SPARSE_MAX` elements in the set, but dense when there are more
436 /// than `SPARSE_MAX`.
438 /// This type is especially efficient for sets that typically have a small
439 /// number of elements, but a large `domain_size`, and are cleared frequently.
441 /// `T` is an index type, typically a newtyped `usize` wrapper, but it can also
444 /// All operations that involve an element will panic if the element is equal
445 /// to or greater than the domain size. All operations that involve two bitsets
446 /// will panic if the bitsets have differing domain sizes.
447 #[derive(Clone, Debug)]
448 pub enum HybridBitSet<T: Idx> {
449 Sparse(SparseBitSet<T>),
453 impl<T: Idx> HybridBitSet<T> {
454 pub fn new_empty(domain_size: usize) -> Self {
455 HybridBitSet::Sparse(SparseBitSet::new_empty(domain_size))
458 fn domain_size(&self) -> usize {
460 HybridBitSet::Sparse(sparse) => sparse.domain_size,
461 HybridBitSet::Dense(dense) => dense.domain_size,
465 pub fn clear(&mut self) {
466 let domain_size = self.domain_size();
467 *self = HybridBitSet::new_empty(domain_size);
470 pub fn contains(&self, elem: T) -> bool {
472 HybridBitSet::Sparse(sparse) => sparse.contains(elem),
473 HybridBitSet::Dense(dense) => dense.contains(elem),
477 pub fn superset(&self, other: &HybridBitSet<T>) -> bool {
478 match (self, other) {
479 (HybridBitSet::Dense(self_dense), HybridBitSet::Dense(other_dense)) => {
480 self_dense.superset(other_dense)
483 assert!(self.domain_size() == other.domain_size());
484 other.iter().all(|elem| self.contains(elem))
489 pub fn is_empty(&self) -> bool {
491 HybridBitSet::Sparse(sparse) => sparse.is_empty(),
492 HybridBitSet::Dense(dense) => dense.is_empty(),
496 pub fn insert(&mut self, elem: T) -> bool {
497 // No need to check `elem` against `self.domain_size` here because all
498 // the match cases check it, one way or another.
500 HybridBitSet::Sparse(sparse) if sparse.len() < SPARSE_MAX => {
501 // The set is sparse and has space for `elem`.
504 HybridBitSet::Sparse(sparse) if sparse.contains(elem) => {
505 // The set is sparse and does not have space for `elem`, but
506 // that doesn't matter because `elem` is already present.
509 HybridBitSet::Sparse(sparse) => {
510 // The set is sparse and full. Convert to a dense set.
511 let mut dense = sparse.to_dense();
512 let changed = dense.insert(elem);
514 *self = HybridBitSet::Dense(dense);
517 HybridBitSet::Dense(dense) => dense.insert(elem),
521 pub fn insert_all(&mut self) {
522 let domain_size = self.domain_size();
524 HybridBitSet::Sparse(_) => {
525 *self = HybridBitSet::Dense(BitSet::new_filled(domain_size));
527 HybridBitSet::Dense(dense) => dense.insert_all(),
531 pub fn remove(&mut self, elem: T) -> bool {
532 // Note: we currently don't bother going from Dense back to Sparse.
534 HybridBitSet::Sparse(sparse) => sparse.remove(elem),
535 HybridBitSet::Dense(dense) => dense.remove(elem),
539 pub fn union(&mut self, other: &HybridBitSet<T>) -> bool {
541 HybridBitSet::Sparse(self_sparse) => {
543 HybridBitSet::Sparse(other_sparse) => {
544 // Both sets are sparse. Add the elements in
545 // `other_sparse` to `self` one at a time. This
546 // may or may not cause `self` to be densified.
547 assert_eq!(self.domain_size(), other.domain_size());
548 let mut changed = false;
549 for elem in other_sparse.iter() {
550 changed |= self.insert(*elem);
554 HybridBitSet::Dense(other_dense) => {
555 // `self` is sparse and `other` is dense. To
556 // merge them, we have two available strategies:
557 // * Densify `self` then merge other
558 // * Clone other then integrate bits from `self`
559 // The second strategy requires dedicated method
560 // since the usual `union` returns the wrong
561 // result. In the dedicated case the computation
562 // is slightly faster if the bits of the sparse
563 // bitset map to only few words of the dense
564 // representation, i.e. indices are near each
567 // Benchmarking seems to suggest that the second
568 // option is worth it.
569 let mut new_dense = other_dense.clone();
570 let changed = new_dense.reverse_union_sparse(self_sparse);
571 *self = HybridBitSet::Dense(new_dense);
577 HybridBitSet::Dense(self_dense) => self_dense.union(other),
581 /// Converts to a dense set, consuming itself in the process.
582 pub fn to_dense(self) -> BitSet<T> {
584 HybridBitSet::Sparse(sparse) => sparse.to_dense(),
585 HybridBitSet::Dense(dense) => dense,
589 pub fn iter(&self) -> HybridIter<'_, T> {
591 HybridBitSet::Sparse(sparse) => HybridIter::Sparse(sparse.iter()),
592 HybridBitSet::Dense(dense) => HybridIter::Dense(dense.iter()),
597 impl<T: Idx> UnionIntoBitSet<T> for HybridBitSet<T> {
598 fn union_into(&self, other: &mut BitSet<T>) -> bool {
600 HybridBitSet::Sparse(sparse) => sparse.union_into(other),
601 HybridBitSet::Dense(dense) => dense.union_into(other),
606 impl<T: Idx> SubtractFromBitSet<T> for HybridBitSet<T> {
607 fn subtract_from(&self, other: &mut BitSet<T>) -> bool {
609 HybridBitSet::Sparse(sparse) => sparse.subtract_from(other),
610 HybridBitSet::Dense(dense) => dense.subtract_from(other),
615 pub enum HybridIter<'a, T: Idx> {
616 Sparse(slice::Iter<'a, T>),
617 Dense(BitIter<'a, T>),
620 impl<'a, T: Idx> Iterator for HybridIter<'a, T> {
623 fn next(&mut self) -> Option<T> {
625 HybridIter::Sparse(sparse) => sparse.next().map(|e| *e),
626 HybridIter::Dense(dense) => dense.next(),
631 /// A resizable bitset type with a dense representation.
633 /// `T` is an index type, typically a newtyped `usize` wrapper, but it can also
636 /// All operations that involve an element will panic if the element is equal
637 /// to or greater than the domain size.
638 #[derive(Clone, Debug, PartialEq)]
639 pub struct GrowableBitSet<T: Idx> {
643 impl<T: Idx> GrowableBitSet<T> {
644 /// Ensure that the set can hold at least `min_domain_size` elements.
645 pub fn ensure(&mut self, min_domain_size: usize) {
646 if self.bit_set.domain_size < min_domain_size {
647 self.bit_set.domain_size = min_domain_size;
650 let min_num_words = num_words(min_domain_size);
651 if self.bit_set.words.len() < min_num_words {
652 self.bit_set.words.resize(min_num_words, 0)
656 pub fn new_empty() -> GrowableBitSet<T> {
657 GrowableBitSet { bit_set: BitSet::new_empty(0) }
660 pub fn with_capacity(capacity: usize) -> GrowableBitSet<T> {
661 GrowableBitSet { bit_set: BitSet::new_empty(capacity) }
664 /// Returns `true` if the set has changed.
666 pub fn insert(&mut self, elem: T) -> bool {
667 self.ensure(elem.index() + 1);
668 self.bit_set.insert(elem)
672 pub fn contains(&self, elem: T) -> bool {
673 let (word_index, mask) = word_index_and_mask(elem);
674 if let Some(word) = self.bit_set.words.get(word_index) {
682 /// A fixed-size 2D bit matrix type with a dense representation.
684 /// `R` and `C` are index types used to identify rows and columns respectively;
685 /// typically newtyped `usize` wrappers, but they can also just be `usize`.
687 /// All operations that involve a row and/or column index will panic if the
688 /// index exceeds the relevant bound.
689 #[derive(Clone, Debug, Eq, PartialEq, RustcDecodable, RustcEncodable)]
690 pub struct BitMatrix<R: Idx, C: Idx> {
694 marker: PhantomData<(R, C)>,
697 impl<R: Idx, C: Idx> BitMatrix<R, C> {
698 /// Creates a new `rows x columns` matrix, initially empty.
699 pub fn new(num_rows: usize, num_columns: usize) -> BitMatrix<R, C> {
700 // For every element, we need one bit for every other
701 // element. Round up to an even number of words.
702 let words_per_row = num_words(num_columns);
706 words: vec![0; num_rows * words_per_row],
711 /// Creates a new matrix, with `row` used as the value for every row.
712 pub fn from_row_n(row: &BitSet<C>, num_rows: usize) -> BitMatrix<R, C> {
713 let num_columns = row.domain_size();
714 let words_per_row = num_words(num_columns);
715 assert_eq!(words_per_row, row.words().len());
719 words: iter::repeat(row.words()).take(num_rows).flatten().cloned().collect(),
724 pub fn rows(&self) -> impl Iterator<Item = R> {
725 (0..self.num_rows).map(R::new)
728 /// The range of bits for a given row.
729 fn range(&self, row: R) -> (usize, usize) {
730 let words_per_row = num_words(self.num_columns);
731 let start = row.index() * words_per_row;
732 (start, start + words_per_row)
735 /// Sets the cell at `(row, column)` to true. Put another way, insert
736 /// `column` to the bitset for `row`.
738 /// Returns `true` if this changed the matrix.
739 pub fn insert(&mut self, row: R, column: C) -> bool {
740 assert!(row.index() < self.num_rows && column.index() < self.num_columns);
741 let (start, _) = self.range(row);
742 let (word_index, mask) = word_index_and_mask(column);
743 let words = &mut self.words[..];
744 let word = words[start + word_index];
745 let new_word = word | mask;
746 words[start + word_index] = new_word;
750 /// Do the bits from `row` contain `column`? Put another way, is
751 /// the matrix cell at `(row, column)` true? Put yet another way,
752 /// if the matrix represents (transitive) reachability, can
753 /// `row` reach `column`?
754 pub fn contains(&self, row: R, column: C) -> bool {
755 assert!(row.index() < self.num_rows && column.index() < self.num_columns);
756 let (start, _) = self.range(row);
757 let (word_index, mask) = word_index_and_mask(column);
758 (self.words[start + word_index] & mask) != 0
761 /// Returns those indices that are true in rows `a` and `b`. This
762 /// is an O(n) operation where `n` is the number of elements
763 /// (somewhat independent from the actual size of the
764 /// intersection, in particular).
765 pub fn intersect_rows(&self, row1: R, row2: R) -> Vec<C> {
766 assert!(row1.index() < self.num_rows && row2.index() < self.num_rows);
767 let (row1_start, row1_end) = self.range(row1);
768 let (row2_start, row2_end) = self.range(row2);
769 let mut result = Vec::with_capacity(self.num_columns);
770 for (base, (i, j)) in (row1_start..row1_end).zip(row2_start..row2_end).enumerate() {
771 let mut v = self.words[i] & self.words[j];
772 for bit in 0..WORD_BITS {
777 result.push(C::new(base * WORD_BITS + bit));
785 /// Adds the bits from row `read` to the bits from row `write`, and
786 /// returns `true` if anything changed.
788 /// This is used when computing transitive reachability because if
789 /// you have an edge `write -> read`, because in that case
790 /// `write` can reach everything that `read` can (and
791 /// potentially more).
792 pub fn union_rows(&mut self, read: R, write: R) -> bool {
793 assert!(read.index() < self.num_rows && write.index() < self.num_rows);
794 let (read_start, read_end) = self.range(read);
795 let (write_start, write_end) = self.range(write);
796 let words = &mut self.words[..];
797 let mut changed = false;
798 for (read_index, write_index) in (read_start..read_end).zip(write_start..write_end) {
799 let word = words[write_index];
800 let new_word = word | words[read_index];
801 words[write_index] = new_word;
802 changed |= word != new_word;
807 /// Adds the bits from `with` to the bits from row `write`, and
808 /// returns `true` if anything changed.
809 pub fn union_row_with(&mut self, with: &BitSet<C>, write: R) -> bool {
810 assert!(write.index() < self.num_rows);
811 assert_eq!(with.domain_size(), self.num_columns);
812 let (write_start, write_end) = self.range(write);
813 let mut changed = false;
814 for (read_index, write_index) in (0..with.words().len()).zip(write_start..write_end) {
815 let word = self.words[write_index];
816 let new_word = word | with.words()[read_index];
817 self.words[write_index] = new_word;
818 changed |= word != new_word;
823 /// Sets every cell in `row` to true.
824 pub fn insert_all_into_row(&mut self, row: R) {
825 assert!(row.index() < self.num_rows);
826 let (start, end) = self.range(row);
827 let words = &mut self.words[..];
828 for index in start..end {
831 self.clear_excess_bits(row);
834 /// Clear excess bits in the final word of the row.
835 fn clear_excess_bits(&mut self, row: R) {
836 let num_bits_in_final_word = self.num_columns % WORD_BITS;
837 if num_bits_in_final_word > 0 {
838 let mask = (1 << num_bits_in_final_word) - 1;
839 let (_, end) = self.range(row);
840 let final_word_idx = end - 1;
841 self.words[final_word_idx] &= mask;
845 /// Gets a slice of the underlying words.
846 pub fn words(&self) -> &[Word] {
850 /// Iterates through all the columns set to true in a given row of
852 pub fn iter(&self, row: R) -> BitIter<'_, C> {
853 assert!(row.index() < self.num_rows);
854 let (start, end) = self.range(row);
857 iter: self.words[start..end].iter().enumerate(),
862 /// Returns the number of elements in `row`.
863 pub fn count(&self, row: R) -> usize {
864 let (start, end) = self.range(row);
865 self.words[start..end].iter().map(|e| e.count_ones() as usize).sum()
869 /// A fixed-column-size, variable-row-size 2D bit matrix with a moderately
870 /// sparse representation.
872 /// Initially, every row has no explicit representation. If any bit within a
873 /// row is set, the entire row is instantiated as `Some(<HybridBitSet>)`.
874 /// Furthermore, any previously uninstantiated rows prior to it will be
875 /// instantiated as `None`. Those prior rows may themselves become fully
876 /// instantiated later on if any of their bits are set.
878 /// `R` and `C` are index types used to identify rows and columns respectively;
879 /// typically newtyped `usize` wrappers, but they can also just be `usize`.
880 #[derive(Clone, Debug)]
881 pub struct SparseBitMatrix<R, C>
887 rows: IndexVec<R, Option<HybridBitSet<C>>>,
890 impl<R: Idx, C: Idx> SparseBitMatrix<R, C> {
891 /// Creates a new empty sparse bit matrix with no rows or columns.
892 pub fn new(num_columns: usize) -> Self {
895 rows: IndexVec::new(),
899 fn ensure_row(&mut self, row: R) -> &mut HybridBitSet<C> {
900 // Instantiate any missing rows up to and including row `row` with an
901 // empty HybridBitSet.
902 self.rows.ensure_contains_elem(row, || None);
904 // Then replace row `row` with a full HybridBitSet if necessary.
905 let num_columns = self.num_columns;
906 self.rows[row].get_or_insert_with(|| HybridBitSet::new_empty(num_columns))
909 /// Sets the cell at `(row, column)` to true. Put another way, insert
910 /// `column` to the bitset for `row`.
912 /// Returns `true` if this changed the matrix.
913 pub fn insert(&mut self, row: R, column: C) -> bool {
914 self.ensure_row(row).insert(column)
917 /// Do the bits from `row` contain `column`? Put another way, is
918 /// the matrix cell at `(row, column)` true? Put yet another way,
919 /// if the matrix represents (transitive) reachability, can
920 /// `row` reach `column`?
921 pub fn contains(&self, row: R, column: C) -> bool {
922 self.row(row).map_or(false, |r| r.contains(column))
925 /// Adds the bits from row `read` to the bits from row `write`, and
926 /// returns `true` if anything changed.
928 /// This is used when computing transitive reachability because if
929 /// you have an edge `write -> read`, because in that case
930 /// `write` can reach everything that `read` can (and
931 /// potentially more).
932 pub fn union_rows(&mut self, read: R, write: R) -> bool {
933 if read == write || self.row(read).is_none() {
937 self.ensure_row(write);
938 if let (Some(read_row), Some(write_row)) = self.rows.pick2_mut(read, write) {
939 write_row.union(read_row)
945 /// Union a row, `from`, into the `into` row.
946 pub fn union_into_row(&mut self, into: R, from: &HybridBitSet<C>) -> bool {
947 self.ensure_row(into).union(from)
950 /// Insert all bits in the given row.
951 pub fn insert_all_into_row(&mut self, row: R) {
952 self.ensure_row(row).insert_all();
955 pub fn rows(&self) -> impl Iterator<Item = R> {
959 /// Iterates through all the columns set to true in a given row of
961 pub fn iter<'a>(&'a self, row: R) -> impl Iterator<Item = C> + 'a {
962 self.row(row).into_iter().flat_map(|r| r.iter())
965 pub fn row(&self, row: R) -> Option<&HybridBitSet<C>> {
966 if let Some(Some(row)) = self.rows.get(row) {
975 fn num_words<T: Idx>(domain_size: T) -> usize {
976 (domain_size.index() + WORD_BITS - 1) / WORD_BITS
980 fn word_index_and_mask<T: Idx>(elem: T) -> (usize, Word) {
981 let elem = elem.index();
982 let word_index = elem / WORD_BITS;
983 let mask = 1 << (elem % WORD_BITS);
988 fn test_new_filled() {
990 let idx_buf = BitSet::new_filled(i);
991 let elems: Vec<usize> = idx_buf.iter().collect();
992 let expected: Vec<usize> = (0..i).collect();
993 assert_eq!(elems, expected);
998 fn bitset_iter_works() {
999 let mut bitset: BitSet<usize> = BitSet::new_empty(100);
1010 bitset.iter().collect::<Vec<_>>(),
1011 [1, 10, 19, 62, 63, 64, 65, 66, 99]
1016 fn bitset_iter_works_2() {
1017 let mut bitset: BitSet<usize> = BitSet::new_empty(320);
1023 assert_eq!(bitset.iter().collect::<Vec<_>>(), [0, 127, 191, 255, 319]);
1027 fn union_two_sets() {
1028 let mut set1: BitSet<usize> = BitSet::new_empty(65);
1029 let mut set2: BitSet<usize> = BitSet::new_empty(65);
1030 assert!(set1.insert(3));
1031 assert!(!set1.insert(3));
1032 assert!(set2.insert(5));
1033 assert!(set2.insert(64));
1034 assert!(set1.union(&set2));
1035 assert!(!set1.union(&set2));
1036 assert!(set1.contains(3));
1037 assert!(!set1.contains(4));
1038 assert!(set1.contains(5));
1039 assert!(!set1.contains(63));
1040 assert!(set1.contains(64));
1044 fn hybrid_bitset() {
1045 let mut sparse038: HybridBitSet<usize> = HybridBitSet::new_empty(256);
1046 assert!(sparse038.is_empty());
1047 assert!(sparse038.insert(0));
1048 assert!(sparse038.insert(1));
1049 assert!(sparse038.insert(8));
1050 assert!(sparse038.insert(3));
1051 assert!(!sparse038.insert(3));
1052 assert!(sparse038.remove(1));
1053 assert!(!sparse038.is_empty());
1054 assert_eq!(sparse038.iter().collect::<Vec<_>>(), [0, 3, 8]);
1057 if i == 0 || i == 3 || i == 8 {
1058 assert!(sparse038.contains(i));
1060 assert!(!sparse038.contains(i));
1064 let mut sparse01358 = sparse038.clone();
1065 assert!(sparse01358.insert(1));
1066 assert!(sparse01358.insert(5));
1067 assert_eq!(sparse01358.iter().collect::<Vec<_>>(), [0, 1, 3, 5, 8]);
1069 let mut dense10 = HybridBitSet::new_empty(256);
1071 assert!(dense10.insert(i));
1073 assert!(!dense10.is_empty());
1074 assert_eq!(dense10.iter().collect::<Vec<_>>(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1076 let mut dense256 = HybridBitSet::new_empty(256);
1077 assert!(dense256.is_empty());
1078 dense256.insert_all();
1079 assert!(!dense256.is_empty());
1081 assert!(dense256.contains(i));
1084 assert!(sparse038.superset(&sparse038)); // sparse + sparse (self)
1085 assert!(sparse01358.superset(&sparse038)); // sparse + sparse
1086 assert!(dense10.superset(&sparse038)); // dense + sparse
1087 assert!(dense10.superset(&dense10)); // dense + dense (self)
1088 assert!(dense256.superset(&dense10)); // dense + dense
1090 let mut hybrid = sparse038;
1091 assert!(!sparse01358.union(&hybrid)); // no change
1092 assert!(hybrid.union(&sparse01358));
1093 assert!(hybrid.superset(&sparse01358) && sparse01358.superset(&hybrid));
1094 assert!(!dense10.union(&sparse01358));
1095 assert!(!dense256.union(&dense10));
1096 let mut dense = dense10;
1097 assert!(dense.union(&dense256));
1098 assert!(dense.superset(&dense256) && dense256.superset(&dense));
1099 assert!(hybrid.union(&dense256));
1100 assert!(hybrid.superset(&dense256) && dense256.superset(&hybrid));
1102 assert_eq!(dense256.iter().count(), 256);
1103 let mut dense0 = dense256;
1105 assert!(dense0.remove(i));
1107 assert!(!dense0.remove(0));
1108 assert!(dense0.is_empty());
1113 let mut set: GrowableBitSet<usize> = GrowableBitSet::with_capacity(65);
1114 for index in 0..65 {
1115 assert!(set.insert(index));
1116 assert!(!set.insert(index));
1120 // Check if the bits set before growing are still set
1121 for index in 0..65 {
1122 assert!(set.contains(index));
1125 // Check if the new bits are all un-set
1126 for index in 65..128 {
1127 assert!(!set.contains(index));
1130 // Check that we can set all new bits without running out of bounds
1131 for index in 65..128 {
1132 assert!(set.insert(index));
1133 assert!(!set.insert(index));
1138 fn matrix_intersection() {
1139 let mut matrix: BitMatrix<usize, usize> = BitMatrix::new(200, 200);
1141 // (*) Elements reachable from both 2 and 65.
1143 matrix.insert(2, 3);
1144 matrix.insert(2, 6);
1145 matrix.insert(2, 10); // (*)
1146 matrix.insert(2, 64); // (*)
1147 matrix.insert(2, 65);
1148 matrix.insert(2, 130);
1149 matrix.insert(2, 160); // (*)
1151 matrix.insert(64, 133);
1153 matrix.insert(65, 2);
1154 matrix.insert(65, 8);
1155 matrix.insert(65, 10); // (*)
1156 matrix.insert(65, 64); // (*)
1157 matrix.insert(65, 68);
1158 matrix.insert(65, 133);
1159 matrix.insert(65, 160); // (*)
1161 let intersection = matrix.intersect_rows(2, 64);
1162 assert!(intersection.is_empty());
1164 let intersection = matrix.intersect_rows(2, 65);
1165 assert_eq!(intersection, &[10, 64, 160]);
1170 let mut matrix: BitMatrix<usize, usize> = BitMatrix::new(64, 100);
1171 matrix.insert(3, 22);
1172 matrix.insert(3, 75);
1173 matrix.insert(2, 99);
1174 matrix.insert(4, 0);
1175 matrix.union_rows(3, 5);
1176 matrix.insert_all_into_row(6);
1178 let expected = [99];
1179 let mut iter = expected.iter();
1180 for i in matrix.iter(2) {
1181 let j = *iter.next().unwrap();
1184 assert!(iter.next().is_none());
1186 let expected = [22, 75];
1187 let mut iter = expected.iter();
1188 assert_eq!(matrix.count(3), expected.len());
1189 for i in matrix.iter(3) {
1190 let j = *iter.next().unwrap();
1193 assert!(iter.next().is_none());
1196 let mut iter = expected.iter();
1197 assert_eq!(matrix.count(4), expected.len());
1198 for i in matrix.iter(4) {
1199 let j = *iter.next().unwrap();
1202 assert!(iter.next().is_none());
1204 let expected = [22, 75];
1205 let mut iter = expected.iter();
1206 assert_eq!(matrix.count(5), expected.len());
1207 for i in matrix.iter(5) {
1208 let j = *iter.next().unwrap();
1211 assert!(iter.next().is_none());
1213 assert_eq!(matrix.count(6), 100);
1215 for (idx, i) in matrix.iter(6).enumerate() {
1219 assert_eq!(count, 100);
1221 if let Some(i) = matrix.iter(7).next() {
1222 panic!("expected no elements in row, but contains element {:?}", i);
1227 fn sparse_matrix_iter() {
1228 let mut matrix: SparseBitMatrix<usize, usize> = SparseBitMatrix::new(100);
1229 matrix.insert(3, 22);
1230 matrix.insert(3, 75);
1231 matrix.insert(2, 99);
1232 matrix.insert(4, 0);
1233 matrix.union_rows(3, 5);
1235 let expected = [99];
1236 let mut iter = expected.iter();
1237 for i in matrix.iter(2) {
1238 let j = *iter.next().unwrap();
1241 assert!(iter.next().is_none());
1243 let expected = [22, 75];
1244 let mut iter = expected.iter();
1245 for i in matrix.iter(3) {
1246 let j = *iter.next().unwrap();
1249 assert!(iter.next().is_none());
1252 let mut iter = expected.iter();
1253 for i in matrix.iter(4) {
1254 let j = *iter.next().unwrap();
1257 assert!(iter.next().is_none());
1259 let expected = [22, 75];
1260 let mut iter = expected.iter();
1261 for i in matrix.iter(5) {
1262 let j = *iter.next().unwrap();
1265 assert!(iter.next().is_none());
1268 /// Merge dense hybrid set into empty sparse hybrid set.
1270 fn union_hybrid_sparse_empty_to_dense(b: &mut Bencher) {
1271 let mut pre_dense: HybridBitSet<usize> = HybridBitSet::new_empty(256);
1273 assert!(pre_dense.insert(i));
1275 let pre_sparse: HybridBitSet<usize> = HybridBitSet::new_empty(256);
1277 let dense = pre_dense.clone();
1278 let mut sparse = pre_sparse.clone();
1279 sparse.union(&dense);
1283 /// Merge dense hybrid set into full hybrid set with same indices.
1285 fn union_hybrid_sparse_full_to_dense(b: &mut Bencher) {
1286 let mut pre_dense: HybridBitSet<usize> = HybridBitSet::new_empty(256);
1288 assert!(pre_dense.insert(i));
1290 let mut pre_sparse: HybridBitSet<usize> = HybridBitSet::new_empty(256);
1291 for i in 0..SPARSE_MAX {
1292 assert!(pre_sparse.insert(i));
1295 let dense = pre_dense.clone();
1296 let mut sparse = pre_sparse.clone();
1297 sparse.union(&dense);
1301 /// Merge dense hybrid set into full hybrid set with indices over the whole domain.
1303 fn union_hybrid_sparse_domain_to_dense(b: &mut Bencher) {
1304 let mut pre_dense: HybridBitSet<usize> = HybridBitSet::new_empty(SPARSE_MAX*64);
1306 assert!(pre_dense.insert(i));
1308 let mut pre_sparse: HybridBitSet<usize> = HybridBitSet::new_empty(SPARSE_MAX*64);
1309 for i in 0..SPARSE_MAX {
1310 assert!(pre_sparse.insert(i*64));
1313 let dense = pre_dense.clone();
1314 let mut sparse = pre_sparse.clone();
1315 sparse.union(&dense);
1319 /// Merge dense hybrid set into empty hybrid set where the domain is very small.
1321 fn union_hybrid_sparse_empty_small_domain(b: &mut Bencher) {
1322 let mut pre_dense: HybridBitSet<usize> = HybridBitSet::new_empty(SPARSE_MAX);
1323 for i in 0..SPARSE_MAX {
1324 assert!(pre_dense.insert(i));
1326 let pre_sparse: HybridBitSet<usize> = HybridBitSet::new_empty(SPARSE_MAX);
1328 let dense = pre_dense.clone();
1329 let mut sparse = pre_sparse.clone();
1330 sparse.union(&dense);
1334 /// Merge dense hybrid set into full hybrid set where the domain is very small.
1336 fn union_hybrid_sparse_full_small_domain(b: &mut Bencher) {
1337 let mut pre_dense: HybridBitSet<usize> = HybridBitSet::new_empty(SPARSE_MAX);
1338 for i in 0..SPARSE_MAX {
1339 assert!(pre_dense.insert(i));
1341 let mut pre_sparse: HybridBitSet<usize> = HybridBitSet::new_empty(SPARSE_MAX);
1342 for i in 0..SPARSE_MAX {
1343 assert!(pre_sparse.insert(i));
1346 let dense = pre_dense.clone();
1347 let mut sparse = pre_sparse.clone();
1348 sparse.union(&dense);