1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use indexed_vec::{Idx, IndexVec};
13 use smallvec::SmallVec;
16 use std::marker::PhantomData;
21 pub const WORD_BYTES: usize = mem::size_of::<Word>();
22 pub const WORD_BITS: usize = WORD_BYTES * 8;
24 /// A fixed-size bitset type with a dense representation. It does not support
25 /// resizing after creation; use `GrowableBitSet` for that.
27 /// `T` is an index type, typically a newtyped `usize` wrapper, but it can also
29 #[derive(Clone, Eq, PartialEq)]
30 pub struct BitSet<T: Idx> {
32 marker: PhantomData<T>,
35 impl<T: Idx> BitSet<T> {
37 pub fn new_empty(domain_size: usize) -> BitSet<T> {
38 let num_words = num_words(domain_size);
40 words: vec![0; num_words],
46 pub fn new_filled(domain_size: usize) -> BitSet<T> {
47 let num_words = num_words(domain_size);
48 let mut result = BitSet {
49 words: vec![!0; num_words],
52 result.clear_above(domain_size);
57 pub fn clear(&mut self) {
58 for word in &mut self.words {
63 /// Sets all elements up to and including `size`.
64 pub fn set_up_to(&mut self, elem: usize) {
65 for word in &mut self.words {
68 self.clear_above(elem);
71 /// Clear all elements above `elem`.
72 fn clear_above(&mut self, elem: usize) {
73 let first_clear_block = elem / WORD_BITS;
75 if first_clear_block < self.words.len() {
76 // Within `first_clear_block`, the `elem % WORD_BITS` LSBs should
78 let mask = (1 << (elem % WORD_BITS)) - 1;
79 self.words[first_clear_block] &= mask;
81 // All the blocks above `first_clear_block` are fully cleared.
82 for word in &mut self.words[first_clear_block + 1..] {
88 /// Efficiently overwrite `self` with `other`. Panics if `self` and `other`
89 /// don't have the same length.
90 pub fn overwrite(&mut self, other: &BitSet<T>) {
91 self.words.clone_from_slice(&other.words);
94 /// Count the number of set bits in the set.
95 pub fn count(&self) -> usize {
96 self.words.iter().map(|e| e.count_ones() as usize).sum()
99 /// True if `self` contains `elem`.
101 pub fn contains(&self, elem: T) -> bool {
102 let (word_index, mask) = word_index_and_mask(elem);
103 (self.words[word_index] & mask) != 0
106 /// True if `self` is a (non-strict) superset of `other`.
108 /// The two sets must have the same domain_size.
110 pub fn superset(&self, other: &BitSet<T>) -> bool {
111 assert_eq!(self.words.len(), other.words.len());
112 self.words.iter().zip(&other.words).all(|(a, b)| (a & b) == *b)
115 /// Is the set empty?
117 pub fn is_empty(&self) -> bool {
118 self.words.iter().all(|a| *a == 0)
121 /// Insert `elem`. Returns true if the set has changed.
123 pub fn insert(&mut self, elem: T) -> bool {
124 let (word_index, mask) = word_index_and_mask(elem);
125 let word_ref = &mut self.words[word_index];
126 let word = *word_ref;
127 let new_word = word | mask;
128 *word_ref = new_word;
132 /// Sets all bits to true.
133 pub fn insert_all(&mut self) {
134 for word in &mut self.words {
139 /// Returns true if the set has changed.
141 pub fn remove(&mut self, elem: T) -> bool {
142 let (word_index, mask) = word_index_and_mask(elem);
143 let word_ref = &mut self.words[word_index];
144 let word = *word_ref;
145 let new_word = word & !mask;
146 *word_ref = new_word;
150 /// Set `self = self | other` and return true if `self` changed
151 /// (i.e., if new bits were added).
152 pub fn union(&mut self, other: &impl UnionIntoBitSet<T>) -> bool {
153 other.union_into(self)
156 /// Set `self = self - other` and return true if `self` changed.
157 /// (i.e., if any bits were removed).
158 pub fn subtract(&mut self, other: &impl SubtractFromBitSet<T>) -> bool {
159 other.subtract_from(self)
162 /// Set `self = self & other` and return true if `self` changed.
163 /// (i.e., if any bits were removed).
164 pub fn intersect(&mut self, other: &BitSet<T>) -> bool {
165 bitwise(&mut self.words, &other.words, |a, b| { a & b })
168 /// Get a slice of the underlying words.
169 pub fn words(&self) -> &[Word] {
173 /// Iterates over the indices of set bits in a sorted order.
175 pub fn iter<'a>(&'a self) -> BitIter<'a, T> {
178 iter: self.words.iter().enumerate(),
183 /// Duplicates the set as a hybrid set.
184 pub fn to_hybrid(&self) -> HybridBitSet<T> {
185 // This domain_size may be slightly larger than the one specified
186 // upon creation, due to rounding up to a whole word. That's ok.
187 let domain_size = self.words.len() * WORD_BITS;
189 // Note: we currently don't bother trying to make a Sparse set.
190 HybridBitSet::Dense(self.to_owned(), domain_size)
193 pub fn to_string(&self, bits: usize) -> String {
194 let mut result = String::new();
197 // Note: this is a little endian printout of bytes.
199 // i tracks how many bits we have printed so far.
201 for word in &self.words {
202 let mut word = *word;
203 for _ in 0..WORD_BYTES { // for each byte in `word`:
204 let remain = bits - i;
205 // If less than a byte remains, then mask just that many bits.
206 let mask = if remain <= 8 { (1 << remain) - 1 } else { 0xFF };
207 assert!(mask <= 0xFF);
208 let byte = word & mask;
210 result.push_str(&format!("{}{:02x}", sep, byte));
212 if remain <= 8 { break; }
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 bitwise(&mut other.words, &self.words, |a, b| { a | b })
245 impl<T: Idx> SubtractFromBitSet<T> for BitSet<T> {
246 fn subtract_from(&self, other: &mut BitSet<T>) -> bool {
247 bitwise(&mut other.words, &self.words, |a, b| { a & !b })
251 impl<T: Idx> fmt::Debug for BitSet<T> {
252 fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
254 .entries(self.iter())
259 impl<T: Idx> rustc_serialize::Encodable for BitSet<T> {
260 fn encode<E: rustc_serialize::Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
261 self.words.encode(encoder)
265 impl<T: Idx> rustc_serialize::Decodable for BitSet<T> {
266 fn decode<D: rustc_serialize::Decoder>(d: &mut D) -> Result<BitSet<T>, D::Error> {
267 let words: Vec<Word> = rustc_serialize::Decodable::decode(d)?;
275 pub struct BitIter<'a, T: Idx> {
276 cur: Option<(Word, usize)>,
277 iter: iter::Enumerate<slice::Iter<'a, Word>>,
278 marker: PhantomData<T>
281 impl<'a, T: Idx> Iterator for BitIter<'a, T> {
283 fn next(&mut self) -> Option<T> {
285 if let Some((ref mut word, offset)) = self.cur {
286 let bit_pos = word.trailing_zeros() as usize;
287 if bit_pos != WORD_BITS {
288 let bit = 1 << bit_pos;
290 return Some(T::new(bit_pos + offset))
294 let (i, word) = self.iter.next()?;
295 self.cur = Some((*word, WORD_BITS * i));
300 pub trait BitSetOperator {
301 /// Combine one bitset into another.
302 fn join<T: Idx>(&self, inout_set: &mut BitSet<T>, in_set: &BitSet<T>) -> bool;
306 fn bitwise<Op>(out_vec: &mut [Word], in_vec: &[Word], op: Op) -> bool
307 where Op: Fn(Word, Word) -> Word
309 assert_eq!(out_vec.len(), in_vec.len());
310 let mut changed = false;
311 for (out_elem, in_elem) in out_vec.iter_mut().zip(in_vec.iter()) {
312 let old_val = *out_elem;
313 let new_val = op(old_val, *in_elem);
315 changed |= old_val != new_val;
320 const SPARSE_MAX: usize = 8;
322 /// A fixed-size bitset type with a sparse representation and a maximum of
323 /// `SPARSE_MAX` elements. The elements are stored as a sorted `SmallVec` with
324 /// no duplicates; although `SmallVec` can spill its elements to the heap, that
325 /// never happens within this type because of the `SPARSE_MAX` limit.
327 /// This type is used by `HybridBitSet`; do not use directly.
328 #[derive(Clone, Debug)]
329 pub struct SparseBitSet<T: Idx>(SmallVec<[T; SPARSE_MAX]>);
331 impl<T: Idx> SparseBitSet<T> {
332 fn new_empty() -> Self {
333 SparseBitSet(SmallVec::new())
336 fn len(&self) -> usize {
340 fn is_empty(&self) -> bool {
344 fn contains(&self, elem: T) -> bool {
345 self.0.contains(&elem)
348 fn insert(&mut self, elem: T) -> bool {
349 assert!(self.len() < SPARSE_MAX);
350 if let Some(i) = self.0.iter().position(|&e| e >= elem) {
351 if self.0[i] == elem {
352 // `elem` is already in the set.
355 // `elem` is smaller than one or more existing elements.
356 self.0.insert(i, elem);
360 // `elem` is larger than all existing elements.
366 fn remove(&mut self, elem: T) -> bool {
367 if let Some(i) = self.0.iter().position(|&e| e == elem) {
375 fn to_dense(&self, domain_size: usize) -> BitSet<T> {
376 let mut dense = BitSet::new_empty(domain_size);
377 for elem in self.0.iter() {
383 fn iter(&self) -> slice::Iter<T> {
388 impl<T: Idx> UnionIntoBitSet<T> for SparseBitSet<T> {
389 fn union_into(&self, other: &mut BitSet<T>) -> bool {
390 let mut changed = false;
391 for elem in self.iter() {
392 changed |= other.insert(*elem);
398 impl<T: Idx> SubtractFromBitSet<T> for SparseBitSet<T> {
399 fn subtract_from(&self, other: &mut BitSet<T>) -> bool {
400 let mut changed = false;
401 for elem in self.iter() {
402 changed |= other.remove(*elem);
408 /// A fixed-size bitset type with a hybrid representation: sparse when there
409 /// are up to a `SPARSE_MAX` elements in the set, but dense when there are more
410 /// than `SPARSE_MAX`.
412 /// This type is especially efficient for sets that typically have a small
413 /// number of elements, but a large `domain_size`, and are cleared frequently.
415 /// `T` is an index type, typically a newtyped `usize` wrapper, but it can also
417 #[derive(Clone, Debug)]
418 pub enum HybridBitSet<T: Idx> {
419 Sparse(SparseBitSet<T>, usize),
420 Dense(BitSet<T>, usize),
423 impl<T: Idx> HybridBitSet<T> {
424 // FIXME: This function is used in conjunction with `mem::replace()` in
425 // several pieces of awful code below. I can't work out how else to appease
426 // the borrow checker.
428 // The cheapest HybridBitSet to construct, which is only used to get
429 // around the borrow checker.
430 HybridBitSet::Sparse(SparseBitSet::new_empty(), 0)
433 pub fn new_empty(domain_size: usize) -> Self {
434 HybridBitSet::Sparse(SparseBitSet::new_empty(), domain_size)
437 pub fn domain_size(&self) -> usize {
439 HybridBitSet::Sparse(_, size) => size,
440 HybridBitSet::Dense(_, size) => size,
444 pub fn clear(&mut self) {
445 let domain_size = self.domain_size();
446 *self = HybridBitSet::new_empty(domain_size);
449 pub fn contains(&self, elem: T) -> bool {
451 HybridBitSet::Sparse(sparse, _) => sparse.contains(elem),
452 HybridBitSet::Dense(dense, _) => dense.contains(elem),
456 pub fn superset(&self, other: &HybridBitSet<T>) -> bool {
457 match (self, other) {
458 (HybridBitSet::Dense(self_dense, _), HybridBitSet::Dense(other_dense, _)) => {
459 self_dense.superset(other_dense)
461 _ => other.iter().all(|elem| self.contains(elem)),
465 pub fn is_empty(&self) -> bool {
467 HybridBitSet::Sparse(sparse, _) => sparse.is_empty(),
468 HybridBitSet::Dense(dense, _) => dense.is_empty(),
472 pub fn insert(&mut self, elem: T) -> bool {
474 HybridBitSet::Sparse(sparse, _) if sparse.len() < SPARSE_MAX => {
475 // The set is sparse and has space for `elem`.
478 HybridBitSet::Sparse(sparse, _) if sparse.contains(elem) => {
479 // The set is sparse and does not have space for `elem`, but
480 // that doesn't matter because `elem` is already present.
483 HybridBitSet::Sparse(_, _) => {
484 // The set is sparse and full. Convert to a dense set.
485 match mem::replace(self, HybridBitSet::dummy()) {
486 HybridBitSet::Sparse(sparse, domain_size) => {
487 let mut dense = sparse.to_dense(domain_size);
488 let changed = dense.insert(elem);
490 *self = HybridBitSet::Dense(dense, domain_size);
497 HybridBitSet::Dense(dense, _) => dense.insert(elem),
501 pub fn insert_all(&mut self) {
502 let domain_size = self.domain_size();
504 HybridBitSet::Sparse(_, _) => {
505 let dense = BitSet::new_filled(domain_size);
506 *self = HybridBitSet::Dense(dense, domain_size);
508 HybridBitSet::Dense(dense, _) => dense.insert_all(),
512 pub fn remove(&mut self, elem: T) -> bool {
513 // Note: we currently don't bother going from Dense back to Sparse.
515 HybridBitSet::Sparse(sparse, _) => sparse.remove(elem),
516 HybridBitSet::Dense(dense, _) => dense.remove(elem),
520 pub fn union(&mut self, other: &HybridBitSet<T>) -> bool {
522 HybridBitSet::Sparse(_, _) => {
524 HybridBitSet::Sparse(other_sparse, _) => {
525 // Both sets are sparse. Add the elements in
526 // `other_sparse` to `self_hybrid` one at a time. This
527 // may or may not cause `self_hybrid` to be densified.
528 let mut self_hybrid = mem::replace(self, HybridBitSet::dummy());
529 let mut changed = false;
530 for elem in other_sparse.iter() {
531 changed |= self_hybrid.insert(*elem);
536 HybridBitSet::Dense(other_dense, _) => {
537 // `self` is sparse and `other` is dense. Densify
538 // `self` and then do the bitwise union.
539 match mem::replace(self, HybridBitSet::dummy()) {
540 HybridBitSet::Sparse(self_sparse, self_domain_size) => {
541 let mut new_dense = self_sparse.to_dense(self_domain_size);
542 let changed = new_dense.union(other_dense);
543 *self = HybridBitSet::Dense(new_dense, self_domain_size);
552 HybridBitSet::Dense(self_dense, _) => self_dense.union(other),
556 /// Converts to a dense set, consuming itself in the process.
557 pub fn to_dense(self) -> BitSet<T> {
559 HybridBitSet::Sparse(sparse, domain_size) => sparse.to_dense(domain_size),
560 HybridBitSet::Dense(dense, _) => dense,
564 pub fn iter(&self) -> HybridIter<T> {
566 HybridBitSet::Sparse(sparse, _) => HybridIter::Sparse(sparse.iter()),
567 HybridBitSet::Dense(dense, _) => HybridIter::Dense(dense.iter()),
572 impl<T: Idx> UnionIntoBitSet<T> for HybridBitSet<T> {
573 fn union_into(&self, other: &mut BitSet<T>) -> bool {
575 HybridBitSet::Sparse(sparse, _) => sparse.union_into(other),
576 HybridBitSet::Dense(dense, _) => dense.union_into(other),
581 impl<T: Idx> SubtractFromBitSet<T> for HybridBitSet<T> {
582 fn subtract_from(&self, other: &mut BitSet<T>) -> bool {
584 HybridBitSet::Sparse(sparse, _) => sparse.subtract_from(other),
585 HybridBitSet::Dense(dense, _) => dense.subtract_from(other),
590 pub enum HybridIter<'a, T: Idx> {
591 Sparse(slice::Iter<'a, T>),
592 Dense(BitIter<'a, T>),
595 impl<'a, T: Idx> Iterator for HybridIter<'a, T> {
598 fn next(&mut self) -> Option<T> {
600 HybridIter::Sparse(sparse) => sparse.next().map(|e| *e),
601 HybridIter::Dense(dense) => dense.next(),
606 /// A resizable bitset type with a dense representation.
608 /// `T` is an index type, typically a newtyped `usize` wrapper, but it can also
610 #[derive(Clone, Debug, PartialEq)]
611 pub struct GrowableBitSet<T: Idx> {
615 impl<T: Idx> GrowableBitSet<T> {
616 pub fn grow(&mut self, domain_size: T) {
617 let num_words = num_words(domain_size);
618 if self.bit_set.words.len() <= num_words {
619 self.bit_set.words.resize(num_words + 1, 0)
623 pub fn new_empty() -> GrowableBitSet<T> {
624 GrowableBitSet { bit_set: BitSet::new_empty(0) }
627 pub fn with_capacity(bits: usize) -> GrowableBitSet<T> {
628 GrowableBitSet { bit_set: BitSet::new_empty(bits) }
631 /// Returns true if the set has changed.
633 pub fn insert(&mut self, elem: T) -> bool {
635 self.bit_set.insert(elem)
639 pub fn contains(&self, elem: T) -> bool {
640 let (word_index, mask) = word_index_and_mask(elem);
641 if let Some(word) = self.bit_set.words.get(word_index) {
649 /// A fixed-size 2D bit matrix type with a dense representation.
651 /// `R` and `C` are index types used to identify rows and columns respectively;
652 /// typically newtyped `usize` wrappers, but they can also just be `usize`.
654 #[derive(Clone, Debug)]
655 pub struct BitMatrix<R: Idx, C: Idx> {
658 marker: PhantomData<(R, C)>,
661 impl<R: Idx, C: Idx> BitMatrix<R, C> {
662 /// Create a new `rows x columns` matrix, initially empty.
663 pub fn new(rows: usize, columns: usize) -> BitMatrix<R, C> {
664 // For every element, we need one bit for every other
665 // element. Round up to an even number of words.
666 let words_per_row = num_words(columns);
669 words: vec![0; rows * words_per_row],
674 /// The range of bits for a given row.
675 fn range(&self, row: R) -> (usize, usize) {
676 let row = row.index();
677 let words_per_row = num_words(self.columns);
678 let start = row * words_per_row;
679 (start, start + words_per_row)
682 /// Sets the cell at `(row, column)` to true. Put another way, insert
683 /// `column` to the bitset for `row`.
685 /// Returns true if this changed the matrix, and false otherwise.
686 pub fn insert(&mut self, row: R, column: R) -> bool {
687 let (start, _) = self.range(row);
688 let (word_index, mask) = word_index_and_mask(column);
689 let words = &mut self.words[..];
690 let word = words[start + word_index];
691 let new_word = word | mask;
692 words[start + word_index] = new_word;
696 /// Do the bits from `row` contain `column`? Put another way, is
697 /// the matrix cell at `(row, column)` true? Put yet another way,
698 /// if the matrix represents (transitive) reachability, can
699 /// `row` reach `column`?
700 pub fn contains(&self, row: R, column: R) -> bool {
701 let (start, _) = self.range(row);
702 let (word_index, mask) = word_index_and_mask(column);
703 (self.words[start + word_index] & mask) != 0
706 /// Returns those indices that are true in rows `a` and `b`. This
707 /// is an O(n) operation where `n` is the number of elements
708 /// (somewhat independent from the actual size of the
709 /// intersection, in particular).
710 pub fn intersect_rows(&self, a: R, b: R) -> Vec<C> {
711 let (a_start, a_end) = self.range(a);
712 let (b_start, b_end) = self.range(b);
713 let mut result = Vec::with_capacity(self.columns);
714 for (base, (i, j)) in (a_start..a_end).zip(b_start..b_end).enumerate() {
715 let mut v = self.words[i] & self.words[j];
716 for bit in 0..WORD_BITS {
721 result.push(C::new(base * WORD_BITS + bit));
729 /// Add the bits from row `read` to the bits from row `write`,
730 /// return true if anything changed.
732 /// This is used when computing transitive reachability because if
733 /// you have an edge `write -> read`, because in that case
734 /// `write` can reach everything that `read` can (and
735 /// potentially more).
736 pub fn union_rows(&mut self, read: R, write: R) -> bool {
737 let (read_start, read_end) = self.range(read);
738 let (write_start, write_end) = self.range(write);
739 let words = &mut self.words[..];
740 let mut changed = false;
741 for (read_index, write_index) in (read_start..read_end).zip(write_start..write_end) {
742 let word = words[write_index];
743 let new_word = word | words[read_index];
744 words[write_index] = new_word;
745 changed |= word != new_word;
750 /// Iterates through all the columns set to true in a given row of
752 pub fn iter<'a>(&'a self, row: R) -> BitIter<'a, C> {
753 let (start, end) = self.range(row);
756 iter: self.words[start..end].iter().enumerate(),
762 /// A fixed-column-size, variable-row-size 2D bit matrix with a moderately
763 /// sparse representation.
765 /// Initially, every row has no explicit representation. If any bit within a
766 /// row is set, the entire row is instantiated as `Some(<HybridBitSet>)`.
767 /// Furthermore, any previously uninstantiated rows prior to it will be
768 /// instantiated as `None`. Those prior rows may themselves become fully
769 /// instantiated later on if any of their bits are set.
771 /// `R` and `C` are index types used to identify rows and columns respectively;
772 /// typically newtyped `usize` wrappers, but they can also just be `usize`.
773 #[derive(Clone, Debug)]
774 pub struct SparseBitMatrix<R, C>
780 rows: IndexVec<R, Option<HybridBitSet<C>>>,
783 impl<R: Idx, C: Idx> SparseBitMatrix<R, C> {
784 /// Create a new empty sparse bit matrix with no rows or columns.
785 pub fn new(num_columns: usize) -> Self {
788 rows: IndexVec::new(),
792 fn ensure_row(&mut self, row: R) -> &mut HybridBitSet<C> {
793 // Instantiate any missing rows up to and including row `row` with an
794 // empty HybridBitSet.
795 self.rows.ensure_contains_elem(row, || None);
797 // Then replace row `row` with a full HybridBitSet if necessary.
798 let num_columns = self.num_columns;
799 self.rows[row].get_or_insert_with(|| HybridBitSet::new_empty(num_columns))
802 /// Sets the cell at `(row, column)` to true. Put another way, insert
803 /// `column` to the bitset for `row`.
805 /// Returns true if this changed the matrix, and false otherwise.
806 pub fn insert(&mut self, row: R, column: C) -> bool {
807 self.ensure_row(row).insert(column)
810 /// Do the bits from `row` contain `column`? Put another way, is
811 /// the matrix cell at `(row, column)` true? Put yet another way,
812 /// if the matrix represents (transitive) reachability, can
813 /// `row` reach `column`?
814 pub fn contains(&self, row: R, column: C) -> bool {
815 self.row(row).map_or(false, |r| r.contains(column))
818 /// Add the bits from row `read` to the bits from row `write`,
819 /// return true if anything changed.
821 /// This is used when computing transitive reachability because if
822 /// you have an edge `write -> read`, because in that case
823 /// `write` can reach everything that `read` can (and
824 /// potentially more).
825 pub fn union_rows(&mut self, read: R, write: R) -> bool {
826 if read == write || self.row(read).is_none() {
830 self.ensure_row(write);
831 if let (Some(read_row), Some(write_row)) = self.rows.pick2_mut(read, write) {
832 write_row.union(read_row)
838 /// Union a row, `from`, into the `into` row.
839 pub fn union_into_row(&mut self, into: R, from: &HybridBitSet<C>) -> bool {
840 self.ensure_row(into).union(from)
843 /// Insert all bits in the given row.
844 pub fn insert_all_into_row(&mut self, row: R) {
845 self.ensure_row(row).insert_all();
848 pub fn rows(&self) -> impl Iterator<Item = R> {
852 /// Iterates through all the columns set to true in a given row of
854 pub fn iter<'a>(&'a self, row: R) -> impl Iterator<Item = C> + 'a {
855 self.row(row).into_iter().flat_map(|r| r.iter())
858 pub fn row(&self, row: R) -> Option<&HybridBitSet<C>> {
859 if let Some(Some(row)) = self.rows.get(row) {
868 fn num_words<T: Idx>(elements: T) -> usize {
869 (elements.index() + WORD_BITS - 1) / WORD_BITS
873 fn word_index_and_mask<T: Idx>(index: T) -> (usize, Word) {
874 let index = index.index();
875 let word_index = index / WORD_BITS;
876 let mask = 1 << (index % WORD_BITS);
881 fn test_clear_above() {
885 let mut idx_buf: BitSet<usize> = BitSet::new_filled(128);
886 idx_buf.clear_above(i);
888 let elems: Vec<usize> = idx_buf.iter().collect();
889 let expected: Vec<usize> = (0..cmp::min(i, 128)).collect();
890 assert_eq!(elems, expected);
895 fn test_set_up_to() {
898 vec![BitSet::new_empty(128), BitSet::new_filled(128)].into_iter()
900 idx_buf.set_up_to(i);
902 let elems: Vec<usize> = idx_buf.iter().collect();
903 let expected: Vec<usize> = (0..i).collect();
904 assert_eq!(elems, expected);
910 fn test_new_filled() {
912 let idx_buf = BitSet::new_filled(i);
913 let elems: Vec<usize> = idx_buf.iter().collect();
914 let expected: Vec<usize> = (0..i).collect();
915 assert_eq!(elems, expected);
920 fn bitset_iter_works() {
921 let mut bitset: BitSet<usize> = BitSet::new_empty(100);
932 bitset.iter().collect::<Vec<_>>(),
933 [1, 10, 19, 62, 63, 64, 65, 66, 99]
938 fn bitset_iter_works_2() {
939 let mut bitset: BitSet<usize> = BitSet::new_empty(319);
945 assert_eq!(bitset.iter().collect::<Vec<_>>(), [0, 127, 191, 255, 319]);
949 fn union_two_sets() {
950 let mut set1: BitSet<usize> = BitSet::new_empty(65);
951 let mut set2: BitSet<usize> = BitSet::new_empty(65);
952 assert!(set1.insert(3));
953 assert!(!set1.insert(3));
954 assert!(set2.insert(5));
955 assert!(set2.insert(64));
956 assert!(set1.union(&set2));
957 assert!(!set1.union(&set2));
958 assert!(set1.contains(3));
959 assert!(!set1.contains(4));
960 assert!(set1.contains(5));
961 assert!(!set1.contains(63));
962 assert!(set1.contains(64));
967 let mut sparse038: HybridBitSet<usize> = HybridBitSet::new_empty(256);
968 assert!(sparse038.is_empty());
969 assert!(sparse038.insert(0));
970 assert!(sparse038.insert(1));
971 assert!(sparse038.insert(8));
972 assert!(sparse038.insert(3));
973 assert!(!sparse038.insert(3));
974 assert!(sparse038.remove(1));
975 assert!(!sparse038.is_empty());
976 assert_eq!(sparse038.iter().collect::<Vec<_>>(), [0, 3, 8]);
979 if i == 0 || i == 3 || i == 8 {
980 assert!(sparse038.contains(i));
982 assert!(!sparse038.contains(i));
986 let mut sparse01358 = sparse038.clone();
987 assert!(sparse01358.insert(1));
988 assert!(sparse01358.insert(5));
989 assert_eq!(sparse01358.iter().collect::<Vec<_>>(), [0, 1, 3, 5, 8]);
991 let mut dense10 = HybridBitSet::new_empty(256);
993 assert!(dense10.insert(i));
995 assert!(!dense10.is_empty());
996 assert_eq!(dense10.iter().collect::<Vec<_>>(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
998 let mut dense256 = HybridBitSet::new_empty(256);
999 assert!(dense256.is_empty());
1000 dense256.insert_all();
1001 assert!(!dense256.is_empty());
1003 assert!(dense256.contains(i));
1006 assert!(sparse038.superset(&sparse038)); // sparse + sparse (self)
1007 assert!(sparse01358.superset(&sparse038)); // sparse + sparse
1008 assert!(dense10.superset(&sparse038)); // dense + sparse
1009 assert!(dense10.superset(&dense10)); // dense + dense (self)
1010 assert!(dense256.superset(&dense10)); // dense + dense
1012 let mut hybrid = sparse038;
1013 assert!(!sparse01358.union(&hybrid)); // no change
1014 assert!(hybrid.union(&sparse01358));
1015 assert!(hybrid.superset(&sparse01358) && sparse01358.superset(&hybrid));
1016 assert!(!dense10.union(&sparse01358));
1017 assert!(!dense256.union(&dense10));
1018 let mut dense = dense10;
1019 assert!(dense.union(&dense256));
1020 assert!(dense.superset(&dense256) && dense256.superset(&dense));
1021 assert!(hybrid.union(&dense256));
1022 assert!(hybrid.superset(&dense256) && dense256.superset(&hybrid));
1024 assert_eq!(dense256.iter().count(), 256);
1025 let mut dense0 = dense256;
1027 assert!(dense0.remove(i));
1029 assert!(!dense0.remove(0));
1030 assert!(dense0.is_empty());
1035 let mut set: GrowableBitSet<usize> = GrowableBitSet::with_capacity(65);
1036 for index in 0..65 {
1037 assert!(set.insert(index));
1038 assert!(!set.insert(index));
1042 // Check if the bits set before growing are still set
1043 for index in 0..65 {
1044 assert!(set.contains(index));
1047 // Check if the new bits are all un-set
1048 for index in 65..128 {
1049 assert!(!set.contains(index));
1052 // Check that we can set all new bits without running out of bounds
1053 for index in 65..128 {
1054 assert!(set.insert(index));
1055 assert!(!set.insert(index));
1060 fn matrix_intersection() {
1061 let mut matrix: BitMatrix<usize, usize> = BitMatrix::new(200, 200);
1063 // (*) Elements reachable from both 2 and 65.
1065 matrix.insert(2, 3);
1066 matrix.insert(2, 6);
1067 matrix.insert(2, 10); // (*)
1068 matrix.insert(2, 64); // (*)
1069 matrix.insert(2, 65);
1070 matrix.insert(2, 130);
1071 matrix.insert(2, 160); // (*)
1073 matrix.insert(64, 133);
1075 matrix.insert(65, 2);
1076 matrix.insert(65, 8);
1077 matrix.insert(65, 10); // (*)
1078 matrix.insert(65, 64); // (*)
1079 matrix.insert(65, 68);
1080 matrix.insert(65, 133);
1081 matrix.insert(65, 160); // (*)
1083 let intersection = matrix.intersect_rows(2, 64);
1084 assert!(intersection.is_empty());
1086 let intersection = matrix.intersect_rows(2, 65);
1087 assert_eq!(intersection, &[10, 64, 160]);
1092 let mut matrix: BitMatrix<usize, usize> = BitMatrix::new(64, 100);
1093 matrix.insert(3, 22);
1094 matrix.insert(3, 75);
1095 matrix.insert(2, 99);
1096 matrix.insert(4, 0);
1097 matrix.union_rows(3, 5);
1099 let expected = [99];
1100 let mut iter = expected.iter();
1101 for i in matrix.iter(2) {
1102 let j = *iter.next().unwrap();
1105 assert!(iter.next().is_none());
1107 let expected = [22, 75];
1108 let mut iter = expected.iter();
1109 for i in matrix.iter(3) {
1110 let j = *iter.next().unwrap();
1113 assert!(iter.next().is_none());
1116 let mut iter = expected.iter();
1117 for i in matrix.iter(4) {
1118 let j = *iter.next().unwrap();
1121 assert!(iter.next().is_none());
1123 let expected = [22, 75];
1124 let mut iter = expected.iter();
1125 for i in matrix.iter(5) {
1126 let j = *iter.next().unwrap();
1129 assert!(iter.next().is_none());
1133 fn sparse_matrix_iter() {
1134 let mut matrix: SparseBitMatrix<usize, usize> = SparseBitMatrix::new(100);
1135 matrix.insert(3, 22);
1136 matrix.insert(3, 75);
1137 matrix.insert(2, 99);
1138 matrix.insert(4, 0);
1139 matrix.union_rows(3, 5);
1141 let expected = [99];
1142 let mut iter = expected.iter();
1143 for i in matrix.iter(2) {
1144 let j = *iter.next().unwrap();
1147 assert!(iter.next().is_none());
1149 let expected = [22, 75];
1150 let mut iter = expected.iter();
1151 for i in matrix.iter(3) {
1152 let j = *iter.next().unwrap();
1155 assert!(iter.next().is_none());
1158 let mut iter = expected.iter();
1159 for i in matrix.iter(4) {
1160 let j = *iter.next().unwrap();
1163 assert!(iter.next().is_none());
1165 let expected = [22, 75];
1166 let mut iter = expected.iter();
1167 for i in matrix.iter(5) {
1168 let j = *iter.next().unwrap();
1171 assert!(iter.next().is_none());