]> git.lizzy.rs Git - rust.git/blob - src/librustc_index/bit_set.rs
Rollup merge of #73762 - poliorcetics:trait-keyword, r=KodrAus
[rust.git] / src / librustc_index / bit_set.rs
1 use crate::vec::{Idx, IndexVec};
2 use arrayvec::ArrayVec;
3 use std::fmt;
4 use std::iter;
5 use std::marker::PhantomData;
6 use std::mem;
7 use std::slice;
8
9 #[cfg(test)]
10 mod tests;
11
12 pub type Word = u64;
13 pub const WORD_BYTES: usize = mem::size_of::<Word>();
14 pub const WORD_BITS: usize = WORD_BYTES * 8;
15
16 /// A fixed-size bitset type with a dense representation.
17 ///
18 /// NOTE: Use [`GrowableBitSet`] if you need support for resizing after creation.
19 ///
20 /// `T` is an index type, typically a newtyped `usize` wrapper, but it can also
21 /// just be `usize`.
22 ///
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 ///
27 /// [`GrowableBitSet`]: struct.GrowableBitSet.html
28 #[derive(Clone, Eq, PartialEq, RustcDecodable, RustcEncodable)]
29 pub struct BitSet<T: Idx> {
30     domain_size: usize,
31     words: Vec<Word>,
32     marker: PhantomData<T>,
33 }
34
35 impl<T: Idx> BitSet<T> {
36     /// Creates a new, empty bitset with a given `domain_size`.
37     #[inline]
38     pub fn new_empty(domain_size: usize) -> BitSet<T> {
39         let num_words = num_words(domain_size);
40         BitSet { domain_size, words: vec![0; num_words], marker: PhantomData }
41     }
42
43     /// Creates a new, filled bitset with a given `domain_size`.
44     #[inline]
45     pub fn new_filled(domain_size: usize) -> BitSet<T> {
46         let num_words = num_words(domain_size);
47         let mut result = BitSet { domain_size, words: vec![!0; num_words], marker: PhantomData };
48         result.clear_excess_bits();
49         result
50     }
51
52     /// Gets the domain size.
53     pub fn domain_size(&self) -> usize {
54         self.domain_size
55     }
56
57     /// Clear all elements.
58     #[inline]
59     pub fn clear(&mut self) {
60         for word in &mut self.words {
61             *word = 0;
62         }
63     }
64
65     /// Clear excess bits in the final word.
66     fn clear_excess_bits(&mut self) {
67         let num_bits_in_final_word = self.domain_size % WORD_BITS;
68         if num_bits_in_final_word > 0 {
69             let mask = (1 << num_bits_in_final_word) - 1;
70             let final_word_idx = self.words.len() - 1;
71             self.words[final_word_idx] &= mask;
72         }
73     }
74
75     /// Efficiently overwrite `self` with `other`.
76     pub fn overwrite(&mut self, other: &BitSet<T>) {
77         assert!(self.domain_size == other.domain_size);
78         self.words.clone_from_slice(&other.words);
79     }
80
81     /// Count the number of set bits in the set.
82     pub fn count(&self) -> usize {
83         self.words.iter().map(|e| e.count_ones() as usize).sum()
84     }
85
86     /// Returns `true` if `self` contains `elem`.
87     #[inline]
88     pub fn contains(&self, elem: T) -> bool {
89         assert!(elem.index() < self.domain_size);
90         let (word_index, mask) = word_index_and_mask(elem);
91         (self.words[word_index] & mask) != 0
92     }
93
94     /// Is `self` is a (non-strict) superset of `other`?
95     #[inline]
96     pub fn superset(&self, other: &BitSet<T>) -> bool {
97         assert_eq!(self.domain_size, other.domain_size);
98         self.words.iter().zip(&other.words).all(|(a, b)| (a & b) == *b)
99     }
100
101     /// Is the set empty?
102     #[inline]
103     pub fn is_empty(&self) -> bool {
104         self.words.iter().all(|a| *a == 0)
105     }
106
107     /// Insert `elem`. Returns whether the set has changed.
108     #[inline]
109     pub fn insert(&mut self, elem: T) -> bool {
110         assert!(elem.index() < self.domain_size);
111         let (word_index, mask) = word_index_and_mask(elem);
112         let word_ref = &mut self.words[word_index];
113         let word = *word_ref;
114         let new_word = word | mask;
115         *word_ref = new_word;
116         new_word != word
117     }
118
119     /// Sets all bits to true.
120     pub fn insert_all(&mut self) {
121         for word in &mut self.words {
122             *word = !0;
123         }
124         self.clear_excess_bits();
125     }
126
127     /// Returns `true` if the set has changed.
128     #[inline]
129     pub fn remove(&mut self, elem: T) -> bool {
130         assert!(elem.index() < self.domain_size);
131         let (word_index, mask) = word_index_and_mask(elem);
132         let word_ref = &mut self.words[word_index];
133         let word = *word_ref;
134         let new_word = word & !mask;
135         *word_ref = new_word;
136         new_word != word
137     }
138
139     /// Sets `self = self | other` and returns `true` if `self` changed
140     /// (i.e., if new bits were added).
141     pub fn union(&mut self, other: &impl UnionIntoBitSet<T>) -> bool {
142         other.union_into(self)
143     }
144
145     /// Sets `self = self - other` and returns `true` if `self` changed.
146     /// (i.e., if any bits were removed).
147     pub fn subtract(&mut self, other: &impl SubtractFromBitSet<T>) -> bool {
148         other.subtract_from(self)
149     }
150
151     /// Sets `self = self & other` and return `true` if `self` changed.
152     /// (i.e., if any bits were removed).
153     pub fn intersect(&mut self, other: &BitSet<T>) -> bool {
154         assert_eq!(self.domain_size, other.domain_size);
155         bitwise(&mut self.words, &other.words, |a, b| a & b)
156     }
157
158     /// Gets a slice of the underlying words.
159     pub fn words(&self) -> &[Word] {
160         &self.words
161     }
162
163     /// Iterates over the indices of set bits in a sorted order.
164     #[inline]
165     pub fn iter(&self) -> BitIter<'_, T> {
166         BitIter::new(&self.words)
167     }
168
169     /// Duplicates the set as a hybrid set.
170     pub fn to_hybrid(&self) -> HybridBitSet<T> {
171         // Note: we currently don't bother trying to make a Sparse set.
172         HybridBitSet::Dense(self.to_owned())
173     }
174
175     /// Set `self = self | other`. In contrast to `union` returns `true` if the set contains at
176     /// least one bit that is not in `other` (i.e. `other` is not a superset of `self`).
177     ///
178     /// This is an optimization for union of a hybrid bitset.
179     fn reverse_union_sparse(&mut self, sparse: &SparseBitSet<T>) -> bool {
180         assert!(sparse.domain_size == self.domain_size);
181         self.clear_excess_bits();
182
183         let mut not_already = false;
184         // Index of the current word not yet merged.
185         let mut current_index = 0;
186         // Mask of bits that came from the sparse set in the current word.
187         let mut new_bit_mask = 0;
188         for (word_index, mask) in sparse.iter().map(|x| word_index_and_mask(*x)) {
189             // Next bit is in a word not inspected yet.
190             if word_index > current_index {
191                 self.words[current_index] |= new_bit_mask;
192                 // Were there any bits in the old word that did not occur in the sparse set?
193                 not_already |= (self.words[current_index] ^ new_bit_mask) != 0;
194                 // Check all words we skipped for any set bit.
195                 not_already |= self.words[current_index + 1..word_index].iter().any(|&x| x != 0);
196                 // Update next word.
197                 current_index = word_index;
198                 // Reset bit mask, no bits have been merged yet.
199                 new_bit_mask = 0;
200             }
201             // Add bit and mark it as coming from the sparse set.
202             // self.words[word_index] |= mask;
203             new_bit_mask |= mask;
204         }
205         self.words[current_index] |= new_bit_mask;
206         // Any bits in the last inspected word that were not in the sparse set?
207         not_already |= (self.words[current_index] ^ new_bit_mask) != 0;
208         // Any bits in the tail? Note `clear_excess_bits` before.
209         not_already |= self.words[current_index + 1..].iter().any(|&x| x != 0);
210
211         not_already
212     }
213 }
214
215 /// This is implemented by all the bitsets so that BitSet::union() can be
216 /// passed any type of bitset.
217 pub trait UnionIntoBitSet<T: Idx> {
218     // Performs `other = other | self`.
219     fn union_into(&self, other: &mut BitSet<T>) -> bool;
220 }
221
222 /// This is implemented by all the bitsets so that BitSet::subtract() can be
223 /// passed any type of bitset.
224 pub trait SubtractFromBitSet<T: Idx> {
225     // Performs `other = other - self`.
226     fn subtract_from(&self, other: &mut BitSet<T>) -> bool;
227 }
228
229 impl<T: Idx> UnionIntoBitSet<T> for BitSet<T> {
230     fn union_into(&self, other: &mut BitSet<T>) -> bool {
231         assert_eq!(self.domain_size, other.domain_size);
232         bitwise(&mut other.words, &self.words, |a, b| a | b)
233     }
234 }
235
236 impl<T: Idx> SubtractFromBitSet<T> for BitSet<T> {
237     fn subtract_from(&self, other: &mut BitSet<T>) -> bool {
238         assert_eq!(self.domain_size, other.domain_size);
239         bitwise(&mut other.words, &self.words, |a, b| a & !b)
240     }
241 }
242
243 impl<T: Idx> fmt::Debug for BitSet<T> {
244     fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
245         w.debug_list().entries(self.iter()).finish()
246     }
247 }
248
249 impl<T: Idx> ToString for BitSet<T> {
250     fn to_string(&self) -> String {
251         let mut result = String::new();
252         let mut sep = '[';
253
254         // Note: this is a little endian printout of bytes.
255
256         // i tracks how many bits we have printed so far.
257         let mut i = 0;
258         for word in &self.words {
259             let mut word = *word;
260             for _ in 0..WORD_BYTES {
261                 // for each byte in `word`:
262                 let remain = self.domain_size - i;
263                 // If less than a byte remains, then mask just that many bits.
264                 let mask = if remain <= 8 { (1 << remain) - 1 } else { 0xFF };
265                 assert!(mask <= 0xFF);
266                 let byte = word & mask;
267
268                 result.push_str(&format!("{}{:02x}", sep, byte));
269
270                 if remain <= 8 {
271                     break;
272                 }
273                 word >>= 8;
274                 i += 8;
275                 sep = '-';
276             }
277             sep = '|';
278         }
279         result.push(']');
280
281         result
282     }
283 }
284
285 pub struct BitIter<'a, T: Idx> {
286     /// A copy of the current word, but with any already-visited bits cleared.
287     /// (This lets us use `trailing_zeros()` to find the next set bit.) When it
288     /// is reduced to 0, we move onto the next word.
289     word: Word,
290
291     /// The offset (measured in bits) of the current word.
292     offset: usize,
293
294     /// Underlying iterator over the words.
295     iter: slice::Iter<'a, Word>,
296
297     marker: PhantomData<T>,
298 }
299
300 impl<'a, T: Idx> BitIter<'a, T> {
301     #[inline]
302     fn new(words: &'a [Word]) -> BitIter<'a, T> {
303         // We initialize `word` and `offset` to degenerate values. On the first
304         // call to `next()` we will fall through to getting the first word from
305         // `iter`, which sets `word` to the first word (if there is one) and
306         // `offset` to 0. Doing it this way saves us from having to maintain
307         // additional state about whether we have started.
308         BitIter {
309             word: 0,
310             offset: usize::MAX - (WORD_BITS - 1),
311             iter: words.iter(),
312             marker: PhantomData,
313         }
314     }
315 }
316
317 impl<'a, T: Idx> Iterator for BitIter<'a, T> {
318     type Item = T;
319     fn next(&mut self) -> Option<T> {
320         loop {
321             if self.word != 0 {
322                 // Get the position of the next set bit in the current word,
323                 // then clear the bit.
324                 let bit_pos = self.word.trailing_zeros() as usize;
325                 let bit = 1 << bit_pos;
326                 self.word ^= bit;
327                 return Some(T::new(bit_pos + self.offset));
328             }
329
330             // Move onto the next word. `wrapping_add()` is needed to handle
331             // the degenerate initial value given to `offset` in `new()`.
332             let word = self.iter.next()?;
333             self.word = *word;
334             self.offset = self.offset.wrapping_add(WORD_BITS);
335         }
336     }
337 }
338
339 #[inline]
340 fn bitwise<Op>(out_vec: &mut [Word], in_vec: &[Word], op: Op) -> bool
341 where
342     Op: Fn(Word, Word) -> Word,
343 {
344     assert_eq!(out_vec.len(), in_vec.len());
345     let mut changed = false;
346     for (out_elem, in_elem) in out_vec.iter_mut().zip(in_vec.iter()) {
347         let old_val = *out_elem;
348         let new_val = op(old_val, *in_elem);
349         *out_elem = new_val;
350         changed |= old_val != new_val;
351     }
352     changed
353 }
354
355 const SPARSE_MAX: usize = 8;
356
357 /// A fixed-size bitset type with a sparse representation and a maximum of
358 /// `SPARSE_MAX` elements. The elements are stored as a sorted `ArrayVec` with
359 /// no duplicates.
360 ///
361 /// This type is used by `HybridBitSet`; do not use directly.
362 #[derive(Clone, Debug)]
363 pub struct SparseBitSet<T: Idx> {
364     domain_size: usize,
365     elems: ArrayVec<[T; SPARSE_MAX]>,
366 }
367
368 impl<T: Idx> SparseBitSet<T> {
369     fn new_empty(domain_size: usize) -> Self {
370         SparseBitSet { domain_size, elems: ArrayVec::new() }
371     }
372
373     fn len(&self) -> usize {
374         self.elems.len()
375     }
376
377     fn is_empty(&self) -> bool {
378         self.elems.len() == 0
379     }
380
381     fn contains(&self, elem: T) -> bool {
382         assert!(elem.index() < self.domain_size);
383         self.elems.contains(&elem)
384     }
385
386     fn insert(&mut self, elem: T) -> bool {
387         assert!(elem.index() < self.domain_size);
388         let changed = if let Some(i) = self.elems.iter().position(|&e| e >= elem) {
389             if self.elems[i] == elem {
390                 // `elem` is already in the set.
391                 false
392             } else {
393                 // `elem` is smaller than one or more existing elements.
394                 self.elems.insert(i, elem);
395                 true
396             }
397         } else {
398             // `elem` is larger than all existing elements.
399             self.elems.push(elem);
400             true
401         };
402         assert!(self.len() <= SPARSE_MAX);
403         changed
404     }
405
406     fn remove(&mut self, elem: T) -> bool {
407         assert!(elem.index() < self.domain_size);
408         if let Some(i) = self.elems.iter().position(|&e| e == elem) {
409             self.elems.remove(i);
410             true
411         } else {
412             false
413         }
414     }
415
416     fn to_dense(&self) -> BitSet<T> {
417         let mut dense = BitSet::new_empty(self.domain_size);
418         for elem in self.elems.iter() {
419             dense.insert(*elem);
420         }
421         dense
422     }
423
424     fn iter(&self) -> slice::Iter<'_, T> {
425         self.elems.iter()
426     }
427 }
428
429 impl<T: Idx> UnionIntoBitSet<T> for SparseBitSet<T> {
430     fn union_into(&self, other: &mut BitSet<T>) -> bool {
431         assert_eq!(self.domain_size, other.domain_size);
432         let mut changed = false;
433         for elem in self.iter() {
434             changed |= other.insert(*elem);
435         }
436         changed
437     }
438 }
439
440 impl<T: Idx> SubtractFromBitSet<T> for SparseBitSet<T> {
441     fn subtract_from(&self, other: &mut BitSet<T>) -> bool {
442         assert_eq!(self.domain_size, other.domain_size);
443         let mut changed = false;
444         for elem in self.iter() {
445             changed |= other.remove(*elem);
446         }
447         changed
448     }
449 }
450
451 /// A fixed-size bitset type with a hybrid representation: sparse when there
452 /// are up to a `SPARSE_MAX` elements in the set, but dense when there are more
453 /// than `SPARSE_MAX`.
454 ///
455 /// This type is especially efficient for sets that typically have a small
456 /// number of elements, but a large `domain_size`, and are cleared frequently.
457 ///
458 /// `T` is an index type, typically a newtyped `usize` wrapper, but it can also
459 /// just be `usize`.
460 ///
461 /// All operations that involve an element will panic if the element is equal
462 /// to or greater than the domain size. All operations that involve two bitsets
463 /// will panic if the bitsets have differing domain sizes.
464 #[derive(Clone, Debug)]
465 pub enum HybridBitSet<T: Idx> {
466     Sparse(SparseBitSet<T>),
467     Dense(BitSet<T>),
468 }
469
470 impl<T: Idx> HybridBitSet<T> {
471     pub fn new_empty(domain_size: usize) -> Self {
472         HybridBitSet::Sparse(SparseBitSet::new_empty(domain_size))
473     }
474
475     fn domain_size(&self) -> usize {
476         match self {
477             HybridBitSet::Sparse(sparse) => sparse.domain_size,
478             HybridBitSet::Dense(dense) => dense.domain_size,
479         }
480     }
481
482     pub fn clear(&mut self) {
483         let domain_size = self.domain_size();
484         *self = HybridBitSet::new_empty(domain_size);
485     }
486
487     pub fn contains(&self, elem: T) -> bool {
488         match self {
489             HybridBitSet::Sparse(sparse) => sparse.contains(elem),
490             HybridBitSet::Dense(dense) => dense.contains(elem),
491         }
492     }
493
494     pub fn superset(&self, other: &HybridBitSet<T>) -> bool {
495         match (self, other) {
496             (HybridBitSet::Dense(self_dense), HybridBitSet::Dense(other_dense)) => {
497                 self_dense.superset(other_dense)
498             }
499             _ => {
500                 assert!(self.domain_size() == other.domain_size());
501                 other.iter().all(|elem| self.contains(elem))
502             }
503         }
504     }
505
506     pub fn is_empty(&self) -> bool {
507         match self {
508             HybridBitSet::Sparse(sparse) => sparse.is_empty(),
509             HybridBitSet::Dense(dense) => dense.is_empty(),
510         }
511     }
512
513     pub fn insert(&mut self, elem: T) -> bool {
514         // No need to check `elem` against `self.domain_size` here because all
515         // the match cases check it, one way or another.
516         match self {
517             HybridBitSet::Sparse(sparse) if sparse.len() < SPARSE_MAX => {
518                 // The set is sparse and has space for `elem`.
519                 sparse.insert(elem)
520             }
521             HybridBitSet::Sparse(sparse) if sparse.contains(elem) => {
522                 // The set is sparse and does not have space for `elem`, but
523                 // that doesn't matter because `elem` is already present.
524                 false
525             }
526             HybridBitSet::Sparse(sparse) => {
527                 // The set is sparse and full. Convert to a dense set.
528                 let mut dense = sparse.to_dense();
529                 let changed = dense.insert(elem);
530                 assert!(changed);
531                 *self = HybridBitSet::Dense(dense);
532                 changed
533             }
534             HybridBitSet::Dense(dense) => dense.insert(elem),
535         }
536     }
537
538     pub fn insert_all(&mut self) {
539         let domain_size = self.domain_size();
540         match self {
541             HybridBitSet::Sparse(_) => {
542                 *self = HybridBitSet::Dense(BitSet::new_filled(domain_size));
543             }
544             HybridBitSet::Dense(dense) => dense.insert_all(),
545         }
546     }
547
548     pub fn remove(&mut self, elem: T) -> bool {
549         // Note: we currently don't bother going from Dense back to Sparse.
550         match self {
551             HybridBitSet::Sparse(sparse) => sparse.remove(elem),
552             HybridBitSet::Dense(dense) => dense.remove(elem),
553         }
554     }
555
556     pub fn union(&mut self, other: &HybridBitSet<T>) -> bool {
557         match self {
558             HybridBitSet::Sparse(self_sparse) => {
559                 match other {
560                     HybridBitSet::Sparse(other_sparse) => {
561                         // Both sets are sparse. Add the elements in
562                         // `other_sparse` to `self` one at a time. This
563                         // may or may not cause `self` to be densified.
564                         assert_eq!(self.domain_size(), other.domain_size());
565                         let mut changed = false;
566                         for elem in other_sparse.iter() {
567                             changed |= self.insert(*elem);
568                         }
569                         changed
570                     }
571                     HybridBitSet::Dense(other_dense) => {
572                         // `self` is sparse and `other` is dense. To
573                         // merge them, we have two available strategies:
574                         // * Densify `self` then merge other
575                         // * Clone other then integrate bits from `self`
576                         // The second strategy requires dedicated method
577                         // since the usual `union` returns the wrong
578                         // result. In the dedicated case the computation
579                         // is slightly faster if the bits of the sparse
580                         // bitset map to only few words of the dense
581                         // representation, i.e. indices are near each
582                         // other.
583                         //
584                         // Benchmarking seems to suggest that the second
585                         // option is worth it.
586                         let mut new_dense = other_dense.clone();
587                         let changed = new_dense.reverse_union_sparse(self_sparse);
588                         *self = HybridBitSet::Dense(new_dense);
589                         changed
590                     }
591                 }
592             }
593
594             HybridBitSet::Dense(self_dense) => self_dense.union(other),
595         }
596     }
597
598     /// Converts to a dense set, consuming itself in the process.
599     pub fn to_dense(self) -> BitSet<T> {
600         match self {
601             HybridBitSet::Sparse(sparse) => sparse.to_dense(),
602             HybridBitSet::Dense(dense) => dense,
603         }
604     }
605
606     pub fn iter(&self) -> HybridIter<'_, T> {
607         match self {
608             HybridBitSet::Sparse(sparse) => HybridIter::Sparse(sparse.iter()),
609             HybridBitSet::Dense(dense) => HybridIter::Dense(dense.iter()),
610         }
611     }
612 }
613
614 impl<T: Idx> UnionIntoBitSet<T> for HybridBitSet<T> {
615     fn union_into(&self, other: &mut BitSet<T>) -> bool {
616         match self {
617             HybridBitSet::Sparse(sparse) => sparse.union_into(other),
618             HybridBitSet::Dense(dense) => dense.union_into(other),
619         }
620     }
621 }
622
623 impl<T: Idx> SubtractFromBitSet<T> for HybridBitSet<T> {
624     fn subtract_from(&self, other: &mut BitSet<T>) -> bool {
625         match self {
626             HybridBitSet::Sparse(sparse) => sparse.subtract_from(other),
627             HybridBitSet::Dense(dense) => dense.subtract_from(other),
628         }
629     }
630 }
631
632 pub enum HybridIter<'a, T: Idx> {
633     Sparse(slice::Iter<'a, T>),
634     Dense(BitIter<'a, T>),
635 }
636
637 impl<'a, T: Idx> Iterator for HybridIter<'a, T> {
638     type Item = T;
639
640     fn next(&mut self) -> Option<T> {
641         match self {
642             HybridIter::Sparse(sparse) => sparse.next().copied(),
643             HybridIter::Dense(dense) => dense.next(),
644         }
645     }
646 }
647
648 /// A resizable bitset type with a dense representation.
649 ///
650 /// `T` is an index type, typically a newtyped `usize` wrapper, but it can also
651 /// just be `usize`.
652 ///
653 /// All operations that involve an element will panic if the element is equal
654 /// to or greater than the domain size.
655 #[derive(Clone, Debug, PartialEq)]
656 pub struct GrowableBitSet<T: Idx> {
657     bit_set: BitSet<T>,
658 }
659
660 impl<T: Idx> GrowableBitSet<T> {
661     /// Ensure that the set can hold at least `min_domain_size` elements.
662     pub fn ensure(&mut self, min_domain_size: usize) {
663         if self.bit_set.domain_size < min_domain_size {
664             self.bit_set.domain_size = min_domain_size;
665         }
666
667         let min_num_words = num_words(min_domain_size);
668         if self.bit_set.words.len() < min_num_words {
669             self.bit_set.words.resize(min_num_words, 0)
670         }
671     }
672
673     pub fn new_empty() -> GrowableBitSet<T> {
674         GrowableBitSet { bit_set: BitSet::new_empty(0) }
675     }
676
677     pub fn with_capacity(capacity: usize) -> GrowableBitSet<T> {
678         GrowableBitSet { bit_set: BitSet::new_empty(capacity) }
679     }
680
681     /// Returns `true` if the set has changed.
682     #[inline]
683     pub fn insert(&mut self, elem: T) -> bool {
684         self.ensure(elem.index() + 1);
685         self.bit_set.insert(elem)
686     }
687
688     #[inline]
689     pub fn contains(&self, elem: T) -> bool {
690         let (word_index, mask) = word_index_and_mask(elem);
691         if let Some(word) = self.bit_set.words.get(word_index) { (word & mask) != 0 } else { false }
692     }
693 }
694
695 /// A fixed-size 2D bit matrix type with a dense representation.
696 ///
697 /// `R` and `C` are index types used to identify rows and columns respectively;
698 /// typically newtyped `usize` wrappers, but they can also just be `usize`.
699 ///
700 /// All operations that involve a row and/or column index will panic if the
701 /// index exceeds the relevant bound.
702 #[derive(Clone, Eq, PartialEq, RustcDecodable, RustcEncodable)]
703 pub struct BitMatrix<R: Idx, C: Idx> {
704     num_rows: usize,
705     num_columns: usize,
706     words: Vec<Word>,
707     marker: PhantomData<(R, C)>,
708 }
709
710 impl<R: Idx, C: Idx> BitMatrix<R, C> {
711     /// Creates a new `rows x columns` matrix, initially empty.
712     pub fn new(num_rows: usize, num_columns: usize) -> BitMatrix<R, C> {
713         // For every element, we need one bit for every other
714         // element. Round up to an even number of words.
715         let words_per_row = num_words(num_columns);
716         BitMatrix {
717             num_rows,
718             num_columns,
719             words: vec![0; num_rows * words_per_row],
720             marker: PhantomData,
721         }
722     }
723
724     /// Creates a new matrix, with `row` used as the value for every row.
725     pub fn from_row_n(row: &BitSet<C>, num_rows: usize) -> BitMatrix<R, C> {
726         let num_columns = row.domain_size();
727         let words_per_row = num_words(num_columns);
728         assert_eq!(words_per_row, row.words().len());
729         BitMatrix {
730             num_rows,
731             num_columns,
732             words: iter::repeat(row.words()).take(num_rows).flatten().cloned().collect(),
733             marker: PhantomData,
734         }
735     }
736
737     pub fn rows(&self) -> impl Iterator<Item = R> {
738         (0..self.num_rows).map(R::new)
739     }
740
741     /// The range of bits for a given row.
742     fn range(&self, row: R) -> (usize, usize) {
743         let words_per_row = num_words(self.num_columns);
744         let start = row.index() * words_per_row;
745         (start, start + words_per_row)
746     }
747
748     /// Sets the cell at `(row, column)` to true. Put another way, insert
749     /// `column` to the bitset for `row`.
750     ///
751     /// Returns `true` if this changed the matrix.
752     pub fn insert(&mut self, row: R, column: C) -> bool {
753         assert!(row.index() < self.num_rows && column.index() < self.num_columns);
754         let (start, _) = self.range(row);
755         let (word_index, mask) = word_index_and_mask(column);
756         let words = &mut self.words[..];
757         let word = words[start + word_index];
758         let new_word = word | mask;
759         words[start + word_index] = new_word;
760         word != new_word
761     }
762
763     /// Do the bits from `row` contain `column`? Put another way, is
764     /// the matrix cell at `(row, column)` true?  Put yet another way,
765     /// if the matrix represents (transitive) reachability, can
766     /// `row` reach `column`?
767     pub fn contains(&self, row: R, column: C) -> bool {
768         assert!(row.index() < self.num_rows && column.index() < self.num_columns);
769         let (start, _) = self.range(row);
770         let (word_index, mask) = word_index_and_mask(column);
771         (self.words[start + word_index] & mask) != 0
772     }
773
774     /// Returns those indices that are true in rows `a` and `b`. This
775     /// is an O(n) operation where `n` is the number of elements
776     /// (somewhat independent from the actual size of the
777     /// intersection, in particular).
778     pub fn intersect_rows(&self, row1: R, row2: R) -> Vec<C> {
779         assert!(row1.index() < self.num_rows && row2.index() < self.num_rows);
780         let (row1_start, row1_end) = self.range(row1);
781         let (row2_start, row2_end) = self.range(row2);
782         let mut result = Vec::with_capacity(self.num_columns);
783         for (base, (i, j)) in (row1_start..row1_end).zip(row2_start..row2_end).enumerate() {
784             let mut v = self.words[i] & self.words[j];
785             for bit in 0..WORD_BITS {
786                 if v == 0 {
787                     break;
788                 }
789                 if v & 0x1 != 0 {
790                     result.push(C::new(base * WORD_BITS + bit));
791                 }
792                 v >>= 1;
793             }
794         }
795         result
796     }
797
798     /// Adds the bits from row `read` to the bits from row `write`, and
799     /// returns `true` if anything changed.
800     ///
801     /// This is used when computing transitive reachability because if
802     /// you have an edge `write -> read`, because in that case
803     /// `write` can reach everything that `read` can (and
804     /// potentially more).
805     pub fn union_rows(&mut self, read: R, write: R) -> bool {
806         assert!(read.index() < self.num_rows && write.index() < self.num_rows);
807         let (read_start, read_end) = self.range(read);
808         let (write_start, write_end) = self.range(write);
809         let words = &mut self.words[..];
810         let mut changed = false;
811         for (read_index, write_index) in (read_start..read_end).zip(write_start..write_end) {
812             let word = words[write_index];
813             let new_word = word | words[read_index];
814             words[write_index] = new_word;
815             changed |= word != new_word;
816         }
817         changed
818     }
819
820     /// Adds the bits from `with` to the bits from row `write`, and
821     /// returns `true` if anything changed.
822     pub fn union_row_with(&mut self, with: &BitSet<C>, write: R) -> bool {
823         assert!(write.index() < self.num_rows);
824         assert_eq!(with.domain_size(), self.num_columns);
825         let (write_start, write_end) = self.range(write);
826         let mut changed = false;
827         for (read_index, write_index) in (0..with.words().len()).zip(write_start..write_end) {
828             let word = self.words[write_index];
829             let new_word = word | with.words()[read_index];
830             self.words[write_index] = new_word;
831             changed |= word != new_word;
832         }
833         changed
834     }
835
836     /// Sets every cell in `row` to true.
837     pub fn insert_all_into_row(&mut self, row: R) {
838         assert!(row.index() < self.num_rows);
839         let (start, end) = self.range(row);
840         let words = &mut self.words[..];
841         for index in start..end {
842             words[index] = !0;
843         }
844         self.clear_excess_bits(row);
845     }
846
847     /// Clear excess bits in the final word of the row.
848     fn clear_excess_bits(&mut self, row: R) {
849         let num_bits_in_final_word = self.num_columns % WORD_BITS;
850         if num_bits_in_final_word > 0 {
851             let mask = (1 << num_bits_in_final_word) - 1;
852             let (_, end) = self.range(row);
853             let final_word_idx = end - 1;
854             self.words[final_word_idx] &= mask;
855         }
856     }
857
858     /// Gets a slice of the underlying words.
859     pub fn words(&self) -> &[Word] {
860         &self.words
861     }
862
863     /// Iterates through all the columns set to true in a given row of
864     /// the matrix.
865     pub fn iter(&self, row: R) -> BitIter<'_, C> {
866         assert!(row.index() < self.num_rows);
867         let (start, end) = self.range(row);
868         BitIter::new(&self.words[start..end])
869     }
870
871     /// Returns the number of elements in `row`.
872     pub fn count(&self, row: R) -> usize {
873         let (start, end) = self.range(row);
874         self.words[start..end].iter().map(|e| e.count_ones() as usize).sum()
875     }
876 }
877
878 impl<R: Idx, C: Idx> fmt::Debug for BitMatrix<R, C> {
879     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
880         /// Forces its contents to print in regular mode instead of alternate mode.
881         struct OneLinePrinter<T>(T);
882         impl<T: fmt::Debug> fmt::Debug for OneLinePrinter<T> {
883             fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
884                 write!(fmt, "{:?}", self.0)
885             }
886         }
887
888         write!(fmt, "BitMatrix({}x{}) ", self.num_rows, self.num_columns)?;
889         let items = self.rows().flat_map(|r| self.iter(r).map(move |c| (r, c)));
890         fmt.debug_set().entries(items.map(OneLinePrinter)).finish()
891     }
892 }
893
894 /// A fixed-column-size, variable-row-size 2D bit matrix with a moderately
895 /// sparse representation.
896 ///
897 /// Initially, every row has no explicit representation. If any bit within a
898 /// row is set, the entire row is instantiated as `Some(<HybridBitSet>)`.
899 /// Furthermore, any previously uninstantiated rows prior to it will be
900 /// instantiated as `None`. Those prior rows may themselves become fully
901 /// instantiated later on if any of their bits are set.
902 ///
903 /// `R` and `C` are index types used to identify rows and columns respectively;
904 /// typically newtyped `usize` wrappers, but they can also just be `usize`.
905 #[derive(Clone, Debug)]
906 pub struct SparseBitMatrix<R, C>
907 where
908     R: Idx,
909     C: Idx,
910 {
911     num_columns: usize,
912     rows: IndexVec<R, Option<HybridBitSet<C>>>,
913 }
914
915 impl<R: Idx, C: Idx> SparseBitMatrix<R, C> {
916     /// Creates a new empty sparse bit matrix with no rows or columns.
917     pub fn new(num_columns: usize) -> Self {
918         Self { num_columns, rows: IndexVec::new() }
919     }
920
921     fn ensure_row(&mut self, row: R) -> &mut HybridBitSet<C> {
922         // Instantiate any missing rows up to and including row `row` with an
923         // empty HybridBitSet.
924         self.rows.ensure_contains_elem(row, || None);
925
926         // Then replace row `row` with a full HybridBitSet if necessary.
927         let num_columns = self.num_columns;
928         self.rows[row].get_or_insert_with(|| HybridBitSet::new_empty(num_columns))
929     }
930
931     /// Sets the cell at `(row, column)` to true. Put another way, insert
932     /// `column` to the bitset for `row`.
933     ///
934     /// Returns `true` if this changed the matrix.
935     pub fn insert(&mut self, row: R, column: C) -> bool {
936         self.ensure_row(row).insert(column)
937     }
938
939     /// Do the bits from `row` contain `column`? Put another way, is
940     /// the matrix cell at `(row, column)` true?  Put yet another way,
941     /// if the matrix represents (transitive) reachability, can
942     /// `row` reach `column`?
943     pub fn contains(&self, row: R, column: C) -> bool {
944         self.row(row).map_or(false, |r| r.contains(column))
945     }
946
947     /// Adds the bits from row `read` to the bits from row `write`, and
948     /// returns `true` if anything changed.
949     ///
950     /// This is used when computing transitive reachability because if
951     /// you have an edge `write -> read`, because in that case
952     /// `write` can reach everything that `read` can (and
953     /// potentially more).
954     pub fn union_rows(&mut self, read: R, write: R) -> bool {
955         if read == write || self.row(read).is_none() {
956             return false;
957         }
958
959         self.ensure_row(write);
960         if let (Some(read_row), Some(write_row)) = self.rows.pick2_mut(read, write) {
961             write_row.union(read_row)
962         } else {
963             unreachable!()
964         }
965     }
966
967     /// Union a row, `from`, into the `into` row.
968     pub fn union_into_row(&mut self, into: R, from: &HybridBitSet<C>) -> bool {
969         self.ensure_row(into).union(from)
970     }
971
972     /// Insert all bits in the given row.
973     pub fn insert_all_into_row(&mut self, row: R) {
974         self.ensure_row(row).insert_all();
975     }
976
977     pub fn rows(&self) -> impl Iterator<Item = R> {
978         self.rows.indices()
979     }
980
981     /// Iterates through all the columns set to true in a given row of
982     /// the matrix.
983     pub fn iter<'a>(&'a self, row: R) -> impl Iterator<Item = C> + 'a {
984         self.row(row).into_iter().flat_map(|r| r.iter())
985     }
986
987     pub fn row(&self, row: R) -> Option<&HybridBitSet<C>> {
988         if let Some(Some(row)) = self.rows.get(row) { Some(row) } else { None }
989     }
990 }
991
992 #[inline]
993 fn num_words<T: Idx>(domain_size: T) -> usize {
994     (domain_size.index() + WORD_BITS - 1) / WORD_BITS
995 }
996
997 #[inline]
998 fn word_index_and_mask<T: Idx>(elem: T) -> (usize, Word) {
999     let elem = elem.index();
1000     let word_index = elem / WORD_BITS;
1001     let mask = 1 << (elem % WORD_BITS);
1002     (word_index, mask)
1003 }