1#![allow(
2 clippy::let_and_return,
3 clippy::needless_range_loop,
4 clippy::to_string_trait_impl,
5 clippy::use_self
6)]
7
8use smallvec::SmallVec;
9use std::{
10 fmt, iter,
11 marker::PhantomData,
12 ops::{Bound, Range, RangeBounds},
13 rc::Rc,
14 slice,
15};
16
17use Chunk::*;
18
19#[cfg(test)]
20mod tests;
21
22mod into_iter;
23
24type Word = u64;
25type WordVec = SmallVec<[Word; 2]>;
26const WORD_BYTES: usize = size_of::<Word>();
27const WORD_BITS: usize = WORD_BYTES * 8;
28
29const CHUNK_WORDS: usize = 32;
40const CHUNK_BITS: usize = CHUNK_WORDS * WORD_BITS; pub trait BitSetIndex: Copy + 'static + Ord + fmt::Debug + std::hash::Hash {
44 fn from_usize(index: usize) -> Self;
46
47 fn index(self) -> usize;
49}
50
51impl BitSetIndex for usize {
52 #[inline]
53 fn from_usize(index: usize) -> Self {
54 index
55 }
56
57 #[inline]
58 fn index(self) -> usize {
59 self
60 }
61}
62
63type ChunkSize = u16;
66const _: () = assert!(CHUNK_BITS <= ChunkSize::MAX as usize);
67
68pub trait BitRelations<Rhs> {
69 fn union(&mut self, other: &Rhs) -> bool;
70 fn subtract(&mut self, other: &Rhs) -> bool;
71 fn intersect(&mut self, other: &Rhs) -> bool;
72}
73
74macro_rules! bit_relations_inherent_impls {
75 () => {
76 pub fn union<Rhs>(&mut self, other: &Rhs) -> bool
79 where
80 Self: BitRelations<Rhs>,
81 {
82 <Self as BitRelations<Rhs>>::union(self, other)
83 }
84
85 pub fn subtract<Rhs>(&mut self, other: &Rhs) -> bool
88 where
89 Self: BitRelations<Rhs>,
90 {
91 <Self as BitRelations<Rhs>>::subtract(self, other)
92 }
93
94 pub fn intersect<Rhs>(&mut self, other: &Rhs) -> bool
97 where
98 Self: BitRelations<Rhs>,
99 {
100 <Self as BitRelations<Rhs>>::intersect(self, other)
101 }
102 };
103}
104
105#[derive(Eq, PartialEq, Hash)]
122pub struct DenseBitSet<T> {
123 domain_size: usize,
124 words: WordVec,
125 marker: PhantomData<T>,
126}
127
128impl<T> DenseBitSet<T> {
129 pub fn domain_size(&self) -> usize {
131 self.domain_size
132 }
133}
134
135impl<T: BitSetIndex> DenseBitSet<T> {
136 #[inline]
138 pub fn new_empty(domain_size: usize) -> DenseBitSet<T> {
139 let num_words = num_words(domain_size);
140 DenseBitSet { domain_size, words: WordVec::from_elem(0, num_words), marker: PhantomData }
141 }
142
143 #[inline]
145 pub fn new_filled(domain_size: usize) -> DenseBitSet<T> {
146 let num_words = num_words(domain_size);
147 let mut result = DenseBitSet {
148 domain_size,
149 words: WordVec::from_elem(!0, num_words),
150 marker: PhantomData,
151 };
152 result.clear_excess_bits();
153 result
154 }
155
156 #[inline]
158 pub fn clear(&mut self) {
159 self.words.fill(0);
160 }
161
162 #[inline]
164 pub fn clear_to(&mut self, domain_size: usize) {
165 self.domain_size = domain_size;
166 self.words.resize(num_words(domain_size), 0);
167 self.words.fill(0);
168 }
169
170 fn clear_excess_bits(&mut self) {
172 clear_excess_bits_in_final_word(self.domain_size, &mut self.words);
173 }
174
175 pub fn count(&self) -> usize {
177 count_ones(&self.words)
178 }
179
180 #[inline]
182 pub fn contains(&self, elem: T) -> bool {
183 assert!(elem.index() < self.domain_size);
184 let (word_index, mask) = word_index_and_mask(elem);
185 (self.words[word_index] & mask) != 0
186 }
187
188 #[inline]
190 pub fn superset(&self, other: &DenseBitSet<T>) -> bool {
191 assert_eq!(self.domain_size, other.domain_size);
192 self.words.iter().zip(&other.words).all(|(a, b)| (a & b) == *b)
193 }
194
195 #[inline]
197 pub fn is_empty(&self) -> bool {
198 words_are_zero(&self.words)
199 }
200
201 #[inline]
203 pub fn insert(&mut self, elem: T) -> bool {
204 assert!(
205 elem.index() < self.domain_size,
206 "inserting element at index {} but domain size is {}",
207 elem.index(),
208 self.domain_size,
209 );
210 let (word_index, mask) = word_index_and_mask(elem);
211 let word_ref = &mut self.words[word_index];
212 let word = *word_ref;
213 let new_word = word | mask;
214 *word_ref = new_word;
215 new_word != word
216 }
217
218 #[inline]
219 pub fn insert_range(&mut self, elems: impl RangeBounds<T>) {
220 let Some((start, end)) = inclusive_start_end(elems, self.domain_size) else {
221 return;
222 };
223
224 let (start_word_index, start_mask) = word_index_and_mask_usize(start);
225 let (end_word_index, end_mask) = word_index_and_mask_usize(end);
226
227 for word_index in (start_word_index + 1)..end_word_index {
229 self.words[word_index] = !0;
230 }
231
232 if start_word_index != end_word_index {
233 self.words[start_word_index] |= !(start_mask - 1);
237 self.words[end_word_index] |= end_mask | (end_mask - 1);
240 } else {
241 self.words[start_word_index] |= end_mask | (end_mask - start_mask);
242 }
243 }
244
245 pub fn insert_all(&mut self) {
247 self.words.fill(!0);
248 self.clear_excess_bits();
249 }
250
251 #[inline]
253 pub fn contains_any(&self, elems: impl RangeBounds<T>) -> bool {
254 let Some((start, end)) = inclusive_start_end(elems, self.domain_size) else {
255 return false;
256 };
257 let (start_word_index, start_mask) = word_index_and_mask_usize(start);
258 let (end_word_index, end_mask) = word_index_and_mask_usize(end);
259
260 if start_word_index == end_word_index {
261 self.words[start_word_index] & (end_mask | (end_mask - start_mask)) != 0
262 } else {
263 if self.words[start_word_index] & !(start_mask - 1) != 0 {
264 return true;
265 }
266
267 let remaining = start_word_index + 1..end_word_index;
268 if remaining.start <= remaining.end {
269 !words_are_zero(&self.words[remaining])
270 || self.words[end_word_index] & (end_mask | (end_mask - 1)) != 0
271 } else {
272 false
273 }
274 }
275 }
276
277 #[inline]
279 pub fn remove(&mut self, elem: T) -> bool {
280 assert!(elem.index() < self.domain_size);
281 let (word_index, mask) = word_index_and_mask(elem);
282 let word_ref = &mut self.words[word_index];
283 let word = *word_ref;
284 let new_word = word & !mask;
285 *word_ref = new_word;
286 new_word != word
287 }
288
289 #[inline]
291 pub fn iter(&self) -> BitIter<'_, T> {
292 BitIter::new(&self.words)
293 }
294
295 pub fn last_set_in(&self, range: impl RangeBounds<T>) -> Option<T> {
296 let (start, end) = inclusive_start_end(range, self.domain_size)?;
297 let (start_word_index, _) = word_index_and_mask_usize(start);
298 let (end_word_index, end_mask) = word_index_and_mask_usize(end);
299
300 let end_word = self.words[end_word_index] & (end_mask | (end_mask - 1));
301 if end_word != 0 {
302 let pos = max_bit(end_word) + WORD_BITS * end_word_index;
303 if start <= pos {
304 return Some(T::from_usize(pos));
305 }
306 }
307
308 if let Some(offset) =
312 self.words[start_word_index..end_word_index].iter().rposition(|&w| w != 0)
313 {
314 let word_idx = start_word_index + offset;
315 let start_word = self.words[word_idx];
316 let pos = max_bit(start_word) + WORD_BITS * word_idx;
317 if start <= pos {
318 return Some(T::from_usize(pos));
319 }
320 }
321
322 None
323 }
324
325 bit_relations_inherent_impls! {}
326
327 pub fn union_not(&mut self, other: &DenseBitSet<T>) {
332 assert_eq!(self.domain_size, other.domain_size);
333
334 update_words(&mut self.words, &other.words, |a, b| a | !b);
340 self.clear_excess_bits();
343 }
344}
345
346impl<T: BitSetIndex> BitRelations<DenseBitSet<T>> for DenseBitSet<T> {
348 fn union(&mut self, other: &DenseBitSet<T>) -> bool {
349 assert_eq!(self.domain_size, other.domain_size);
350 union_words(&mut self.words, &other.words)
351 }
352
353 fn subtract(&mut self, other: &DenseBitSet<T>) -> bool {
354 assert_eq!(self.domain_size, other.domain_size);
355 subtract_words(&mut self.words, &other.words)
356 }
357
358 fn intersect(&mut self, other: &DenseBitSet<T>) -> bool {
359 assert_eq!(self.domain_size, other.domain_size);
360 intersect_words(&mut self.words, &other.words)
361 }
362}
363
364impl<T: BitSetIndex> From<GrowableBitSet<T>> for DenseBitSet<T> {
365 fn from(bit_set: GrowableBitSet<T>) -> Self {
366 bit_set.bit_set
367 }
368}
369
370impl<T> Clone for DenseBitSet<T> {
371 fn clone(&self) -> Self {
372 DenseBitSet {
373 domain_size: self.domain_size,
374 words: WordVec::from_slice(&self.words),
375 marker: PhantomData,
376 }
377 }
378
379 fn clone_from(&mut self, from: &Self) {
380 self.domain_size = from.domain_size;
381 self.words.clear();
382 self.words.extend_from_slice(&from.words);
383 }
384}
385
386impl<T: BitSetIndex> fmt::Debug for DenseBitSet<T> {
387 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
388 w.debug_list().entries(self.iter()).finish()
389 }
390}
391
392impl<T: BitSetIndex> ToString for DenseBitSet<T> {
393 fn to_string(&self) -> String {
394 let mut result = String::new();
395 let mut sep = '[';
396
397 let mut i = 0;
401 for word in &self.words {
402 let mut word = *word;
403 for _ in 0..WORD_BYTES {
404 let remain = self.domain_size - i;
406 let mask = if remain <= 8 { (1 << remain) - 1 } else { 0xFF };
408 assert!(mask <= 0xFF);
409 let byte = word & mask;
410
411 result.push_str(&format!("{sep}{byte:02x}"));
412
413 if remain <= 8 {
414 break;
415 }
416 word >>= 8;
417 i += 8;
418 sep = '-';
419 }
420 sep = '|';
421 }
422 result.push(']');
423
424 result
425 }
426}
427
428pub struct BitIter<'a, T: BitSetIndex> {
429 word: Word,
433
434 offset: usize,
436
437 iter: slice::Iter<'a, Word>,
439
440 marker: PhantomData<T>,
441}
442
443impl<'a, T: BitSetIndex> BitIter<'a, T> {
444 #[inline]
445 fn new(words: &'a [Word]) -> BitIter<'a, T> {
446 BitIter {
452 word: 0,
453 offset: usize::MAX - (WORD_BITS - 1),
454 iter: words.iter(),
455 marker: PhantomData,
456 }
457 }
458}
459
460impl<'a, T: BitSetIndex> Iterator for BitIter<'a, T> {
461 type Item = T;
462 fn next(&mut self) -> Option<T> {
463 loop {
464 if self.word != 0 {
465 let bit_pos = self.word.trailing_zeros() as usize;
468 self.word ^= 1 << bit_pos;
469 return Some(T::from_usize(bit_pos + self.offset));
470 }
471
472 self.word = *self.iter.next()?;
475 self.offset = self.offset.wrapping_add(WORD_BITS);
476 }
477 }
478}
479
480#[derive(PartialEq, Eq)]
499pub struct ChunkedBitSet<T> {
500 domain_size: usize,
501
502 chunks: Box<[Chunk]>,
505
506 marker: PhantomData<T>,
507}
508
509#[derive(Clone, Debug, PartialEq, Eq)]
514enum Chunk {
515 Zeros { chunk_domain_size: ChunkSize },
517
518 Ones { chunk_domain_size: ChunkSize },
520
521 Mixed {
535 chunk_domain_size: ChunkSize,
536 ones_count: ChunkSize,
543 words: Rc<[Word; CHUNK_WORDS]>,
544 },
545}
546
547#[cfg(target_pointer_width = "64")]
549const _: () = assert!(size_of::<Chunk>() == 16);
550
551impl<T> ChunkedBitSet<T> {
552 pub fn domain_size(&self) -> usize {
553 self.domain_size
554 }
555
556 #[cfg(test)]
557 fn assert_valid(&self) {
558 if self.domain_size == 0 {
559 assert!(self.chunks.is_empty());
560 return;
561 }
562
563 assert!((self.chunks.len() - 1) * CHUNK_BITS <= self.domain_size);
564 assert!(self.chunks.len() * CHUNK_BITS >= self.domain_size);
565 for chunk in self.chunks.iter() {
566 chunk.assert_valid();
567 }
568 }
569}
570
571impl<T: BitSetIndex> ChunkedBitSet<T> {
572 fn new(domain_size: usize, is_empty: bool) -> Self {
574 let chunks = if domain_size == 0 {
575 Box::new([])
576 } else {
577 let num_chunks = domain_size.div_ceil(CHUNK_BITS);
578 let mut last_chunk_domain_size = domain_size % CHUNK_BITS;
579 if last_chunk_domain_size == 0 {
580 last_chunk_domain_size = CHUNK_BITS;
581 };
582
583 let (normal_chunk, final_chunk) = if is_empty {
586 (
587 Zeros { chunk_domain_size: CHUNK_BITS as ChunkSize },
588 Zeros { chunk_domain_size: last_chunk_domain_size as ChunkSize },
589 )
590 } else {
591 (
592 Ones { chunk_domain_size: CHUNK_BITS as ChunkSize },
593 Ones { chunk_domain_size: last_chunk_domain_size as ChunkSize },
594 )
595 };
596 let mut chunks = vec![normal_chunk; num_chunks].into_boxed_slice();
597 *chunks.as_mut().last_mut().unwrap() = final_chunk;
598 chunks
599 };
600 ChunkedBitSet { domain_size, chunks, marker: PhantomData }
601 }
602
603 #[inline]
605 pub fn new_empty(domain_size: usize) -> Self {
606 ChunkedBitSet::new(domain_size, true)
607 }
608
609 #[inline]
611 pub fn new_filled(domain_size: usize) -> Self {
612 ChunkedBitSet::new(domain_size, false)
613 }
614
615 pub fn clear(&mut self) {
616 *self = ChunkedBitSet::new_empty(self.domain_size);
618 }
619
620 #[cfg(test)]
621 fn chunks(&self) -> &[Chunk] {
622 &self.chunks
623 }
624
625 pub fn count(&self) -> usize {
627 self.chunks.iter().map(|chunk| chunk.count()).sum()
628 }
629
630 pub fn is_empty(&self) -> bool {
631 self.chunks.iter().all(|chunk| matches!(chunk, Zeros { .. }))
632 }
633
634 #[inline]
636 pub fn contains(&self, elem: T) -> bool {
637 assert!(elem.index() < self.domain_size);
638 let chunk = &self.chunks[chunk_index(elem)];
639 match &chunk {
640 Zeros { .. } => false,
641 Ones { .. } => true,
642 Mixed { words, .. } => {
643 let (word_index, mask) = chunk_word_index_and_mask(elem);
644 (words[word_index] & mask) != 0
645 }
646 }
647 }
648
649 #[inline]
650 pub fn iter(&self) -> ChunkedBitIter<'_, T> {
651 ChunkedBitIter::new(self)
652 }
653
654 pub fn insert(&mut self, elem: T) -> bool {
656 assert!(elem.index() < self.domain_size);
657 let chunk_index = chunk_index(elem);
658 let chunk = &mut self.chunks[chunk_index];
659 match *chunk {
660 Zeros { chunk_domain_size } => {
661 if chunk_domain_size > 1 {
662 let mut words = {
663 let words = Rc::<[Word; CHUNK_WORDS]>::new([0; CHUNK_WORDS]);
665 words
666 };
667 let words_ref = Rc::get_mut(&mut words).unwrap();
668
669 let (word_index, mask) = chunk_word_index_and_mask(elem);
670 words_ref[word_index] |= mask;
671 *chunk = Mixed { chunk_domain_size, ones_count: 1, words };
672 } else {
673 *chunk = Ones { chunk_domain_size };
674 }
675 true
676 }
677 Ones { .. } => false,
678 Mixed { chunk_domain_size, ref mut ones_count, ref mut words } => {
679 let (word_index, mask) = chunk_word_index_and_mask(elem);
681 if (words[word_index] & mask) == 0 {
682 *ones_count += 1;
683 if *ones_count < chunk_domain_size {
684 let words = Rc::make_mut(words);
685 words[word_index] |= mask;
686 } else {
687 *chunk = Ones { chunk_domain_size };
688 }
689 true
690 } else {
691 false
692 }
693 }
694 }
695 }
696
697 pub fn insert_all(&mut self) {
699 *self = ChunkedBitSet::new_filled(self.domain_size);
701 }
702
703 pub fn remove(&mut self, elem: T) -> bool {
705 assert!(elem.index() < self.domain_size);
706 let chunk_index = chunk_index(elem);
707 let chunk = &mut self.chunks[chunk_index];
708 match *chunk {
709 Zeros { .. } => false,
710 Ones { chunk_domain_size } => {
711 if chunk_domain_size > 1 {
712 let mut words = {
713 let words = Rc::<[Word; CHUNK_WORDS]>::new([0; CHUNK_WORDS]);
715 words
716 };
717 let words_ref = Rc::get_mut(&mut words).unwrap();
718
719 let num_words = num_words(chunk_domain_size as usize);
721 words_ref[..num_words].fill(!0);
722 clear_excess_bits_in_final_word(
723 chunk_domain_size as usize,
724 &mut words_ref[..num_words],
725 );
726 let (word_index, mask) = chunk_word_index_and_mask(elem);
727 words_ref[word_index] &= !mask;
728 *chunk = Mixed { chunk_domain_size, ones_count: chunk_domain_size - 1, words };
729 } else {
730 *chunk = Zeros { chunk_domain_size };
731 }
732 true
733 }
734 Mixed { chunk_domain_size, ref mut ones_count, ref mut words } => {
735 let (word_index, mask) = chunk_word_index_and_mask(elem);
737 if (words[word_index] & mask) != 0 {
738 *ones_count -= 1;
739 if *ones_count > 0 {
740 let words = Rc::make_mut(words);
741 words[word_index] &= !mask;
742 } else {
743 *chunk = Zeros { chunk_domain_size }
744 }
745 true
746 } else {
747 false
748 }
749 }
750 }
751 }
752
753 fn chunk_iter(&self, chunk_index: usize) -> ChunkIter<'_> {
754 match self.chunks.get(chunk_index) {
755 Some(Zeros { .. }) => ChunkIter::Zeros,
756 Some(Ones { chunk_domain_size }) => ChunkIter::Ones(0..*chunk_domain_size as usize),
757 Some(Mixed { chunk_domain_size, words, .. }) => {
758 let num_words = num_words(*chunk_domain_size as usize);
759 ChunkIter::Mixed(BitIter::new(&words[0..num_words]))
760 }
761 None => ChunkIter::Finished,
762 }
763 }
764
765 bit_relations_inherent_impls! {}
766}
767
768impl<T: BitSetIndex> BitRelations<ChunkedBitSet<T>> for ChunkedBitSet<T> {
769 fn union(&mut self, other: &ChunkedBitSet<T>) -> bool {
770 assert_eq!(self.domain_size, other.domain_size);
771
772 let mut changed = false;
773 for (mut self_chunk, other_chunk) in self.chunks.iter_mut().zip(other.chunks.iter()) {
774 match (&mut self_chunk, &other_chunk) {
775 (_, Zeros { .. }) | (Ones { .. }, _) => {}
776 (Zeros { .. }, _) | (Mixed { .. }, Ones { .. }) => {
777 *self_chunk = other_chunk.clone();
779 changed = true;
780 }
781 (
782 Mixed {
783 chunk_domain_size,
784 ones_count: self_chunk_ones_count,
785 words: self_chunk_words,
786 },
787 Mixed { words: other_chunk_words, .. },
788 ) => {
789 let num_words = num_words(*chunk_domain_size as usize);
795
796 if self_chunk_words[0..num_words] == other_chunk_words[0..num_words] {
800 continue;
801 }
802
803 let op = |a, b| a | b;
806 if !would_modify_words(
807 &self_chunk_words[0..num_words],
808 &other_chunk_words[0..num_words],
809 op,
810 ) {
811 continue;
812 }
813
814 let self_chunk_words = Rc::make_mut(self_chunk_words);
816 let has_changed = union_words(
817 &mut self_chunk_words[0..num_words],
818 &other_chunk_words[0..num_words],
819 );
820 debug_assert!(has_changed);
821 *self_chunk_ones_count =
822 count_ones(&self_chunk_words[0..num_words]) as ChunkSize;
823 if *self_chunk_ones_count == *chunk_domain_size {
824 *self_chunk = Ones { chunk_domain_size: *chunk_domain_size };
825 }
826 changed = true;
827 }
828 }
829 }
830 changed
831 }
832
833 fn subtract(&mut self, other: &ChunkedBitSet<T>) -> bool {
834 assert_eq!(self.domain_size, other.domain_size);
835
836 let mut changed = false;
837 for (mut self_chunk, other_chunk) in self.chunks.iter_mut().zip(other.chunks.iter()) {
838 match (&mut self_chunk, &other_chunk) {
839 (Zeros { .. }, _) | (_, Zeros { .. }) => {}
840 (Ones { chunk_domain_size } | Mixed { chunk_domain_size, .. }, Ones { .. }) => {
841 changed = true;
842 *self_chunk = Zeros { chunk_domain_size: *chunk_domain_size };
843 }
844 (
845 Ones { chunk_domain_size },
846 Mixed { ones_count: other_chunk_ones_count, words: other_chunk_words, .. },
847 ) => {
848 changed = true;
849 let num_words = num_words(*chunk_domain_size as usize);
850 debug_assert!(num_words > 0 && num_words <= CHUNK_WORDS);
851 let mut self_chunk_words = **other_chunk_words;
854 for word in self_chunk_words[0..num_words].iter_mut() {
855 *word = !*word;
856 }
857 clear_excess_bits_in_final_word(
858 *chunk_domain_size as usize,
859 &mut self_chunk_words[..num_words],
860 );
861 let self_chunk_ones_count = *chunk_domain_size - *other_chunk_ones_count;
862 debug_assert_eq!(
863 self_chunk_ones_count,
864 count_ones(&self_chunk_words[0..num_words]) as ChunkSize
865 );
866 *self_chunk = Mixed {
867 chunk_domain_size: *chunk_domain_size,
868 ones_count: self_chunk_ones_count,
869 words: Rc::new(self_chunk_words),
870 };
871 }
872 (
873 Mixed {
874 chunk_domain_size,
875 ones_count: self_chunk_ones_count,
876 words: self_chunk_words,
877 },
878 Mixed { words: other_chunk_words, .. },
879 ) => {
880 let num_words = num_words(*chunk_domain_size as usize);
882 let op = |a: Word, b: Word| a & !b;
883 if !would_modify_words(
884 &self_chunk_words[0..num_words],
885 &other_chunk_words[0..num_words],
886 op,
887 ) {
888 continue;
889 }
890
891 let self_chunk_words = Rc::make_mut(self_chunk_words);
892 let has_changed = subtract_words(
893 &mut self_chunk_words[0..num_words],
894 &other_chunk_words[0..num_words],
895 );
896 debug_assert!(has_changed);
897 *self_chunk_ones_count =
898 count_ones(&self_chunk_words[0..num_words]) as ChunkSize;
899 if *self_chunk_ones_count == 0 {
900 *self_chunk = Zeros { chunk_domain_size: *chunk_domain_size };
901 }
902 changed = true;
903 }
904 }
905 }
906 changed
907 }
908
909 fn intersect(&mut self, other: &ChunkedBitSet<T>) -> bool {
910 assert_eq!(self.domain_size, other.domain_size);
911
912 let mut changed = false;
913 for (mut self_chunk, other_chunk) in self.chunks.iter_mut().zip(other.chunks.iter()) {
914 match (&mut self_chunk, &other_chunk) {
915 (Zeros { .. }, _) | (_, Ones { .. }) => {}
916 (Ones { .. }, Zeros { .. } | Mixed { .. }) | (Mixed { .. }, Zeros { .. }) => {
917 changed = true;
918 *self_chunk = other_chunk.clone();
919 }
920 (
921 Mixed {
922 chunk_domain_size,
923 ones_count: self_chunk_ones_count,
924 words: self_chunk_words,
925 },
926 Mixed { words: other_chunk_words, .. },
927 ) => {
928 let num_words = num_words(*chunk_domain_size as usize);
930 let op = |a, b| a & b;
931 if !would_modify_words(
932 &self_chunk_words[0..num_words],
933 &other_chunk_words[0..num_words],
934 op,
935 ) {
936 continue;
937 }
938
939 let self_chunk_words = Rc::make_mut(self_chunk_words);
940 let has_changed = intersect_words(
941 &mut self_chunk_words[0..num_words],
942 &other_chunk_words[0..num_words],
943 );
944 debug_assert!(has_changed);
945 *self_chunk_ones_count =
946 count_ones(&self_chunk_words[0..num_words]) as ChunkSize;
947 if *self_chunk_ones_count == 0 {
948 *self_chunk = Zeros { chunk_domain_size: *chunk_domain_size };
949 }
950 changed = true;
951 }
952 }
953 }
954
955 changed
956 }
957}
958
959impl<T> Clone for ChunkedBitSet<T> {
960 fn clone(&self) -> Self {
961 ChunkedBitSet {
962 domain_size: self.domain_size,
963 chunks: self.chunks.clone(),
964 marker: PhantomData,
965 }
966 }
967
968 fn clone_from(&mut self, from: &Self) {
973 assert_eq!(self.domain_size, from.domain_size);
974 debug_assert_eq!(self.chunks.len(), from.chunks.len());
975
976 self.chunks.clone_from(&from.chunks)
977 }
978}
979
980pub struct ChunkedBitIter<'a, T: BitSetIndex> {
981 bit_set: &'a ChunkedBitSet<T>,
982
983 chunk_index: usize,
985
986 chunk_iter: ChunkIter<'a>,
988}
989
990impl<'a, T: BitSetIndex> ChunkedBitIter<'a, T> {
991 #[inline]
992 fn new(bit_set: &'a ChunkedBitSet<T>) -> ChunkedBitIter<'a, T> {
993 ChunkedBitIter { bit_set, chunk_index: 0, chunk_iter: bit_set.chunk_iter(0) }
994 }
995}
996
997impl<'a, T: BitSetIndex> Iterator for ChunkedBitIter<'a, T> {
998 type Item = T;
999
1000 fn next(&mut self) -> Option<T> {
1001 loop {
1002 match &mut self.chunk_iter {
1003 ChunkIter::Zeros => {}
1004 ChunkIter::Ones(iter) => {
1005 if let Some(next) = iter.next() {
1006 return Some(T::from_usize(next + self.chunk_index * CHUNK_BITS));
1007 }
1008 }
1009 ChunkIter::Mixed(iter) => {
1010 if let Some(next) = iter.next() {
1011 return Some(T::from_usize(next.index() + self.chunk_index * CHUNK_BITS));
1012 }
1013 }
1014 ChunkIter::Finished => return None,
1015 }
1016 self.chunk_index += 1;
1017 self.chunk_iter = self.bit_set.chunk_iter(self.chunk_index);
1018 }
1019 }
1020}
1021
1022impl Chunk {
1023 #[cfg(test)]
1024 fn assert_valid(&self) {
1025 match *self {
1026 Zeros { chunk_domain_size } | Ones { chunk_domain_size } => {
1027 assert!(chunk_domain_size as usize <= CHUNK_BITS);
1028 }
1029 Mixed { chunk_domain_size, ones_count, ref words } => {
1030 assert!(chunk_domain_size as usize <= CHUNK_BITS);
1031 assert!(0 < ones_count && ones_count < chunk_domain_size);
1032
1033 assert_eq!(count_ones(words.as_slice()) as ChunkSize, ones_count);
1035
1036 let num_words = num_words(chunk_domain_size as usize);
1038 if num_words < CHUNK_WORDS {
1039 assert_eq!(count_ones(&words[num_words..]) as ChunkSize, 0);
1040 }
1041 }
1042 }
1043 }
1044
1045 fn count(&self) -> usize {
1047 match *self {
1048 Zeros { .. } => 0,
1049 Ones { chunk_domain_size } => chunk_domain_size as usize,
1050 Mixed { ones_count, .. } => usize::from(ones_count),
1051 }
1052 }
1053}
1054
1055enum ChunkIter<'a> {
1056 Zeros,
1057 Ones(Range<usize>),
1058 Mixed(BitIter<'a, ChunkBitIdx>),
1059 Finished,
1060}
1061
1062#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
1063struct ChunkBitIdx(usize);
1064
1065impl BitSetIndex for ChunkBitIdx {
1066 fn from_usize(index: usize) -> Self {
1067 Self(index)
1068 }
1069
1070 fn index(self) -> usize {
1071 self.0
1072 }
1073}
1074
1075impl<T: BitSetIndex> fmt::Debug for ChunkedBitSet<T> {
1076 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
1077 w.debug_list().entries(self.iter()).finish()
1078 }
1079}
1080
1081#[derive(PartialEq, Eq)]
1093pub enum MixedBitSet<T> {
1094 Small(DenseBitSet<T>),
1095 Large(ChunkedBitSet<T>),
1096}
1097
1098impl<T> MixedBitSet<T> {
1099 pub fn domain_size(&self) -> usize {
1100 match self {
1101 MixedBitSet::Small(set) => set.domain_size(),
1102 MixedBitSet::Large(set) => set.domain_size(),
1103 }
1104 }
1105}
1106
1107impl<T: BitSetIndex> MixedBitSet<T> {
1108 #[inline]
1109 pub fn new_empty(domain_size: usize) -> MixedBitSet<T> {
1110 if domain_size <= CHUNK_BITS {
1111 MixedBitSet::Small(DenseBitSet::new_empty(domain_size))
1112 } else {
1113 MixedBitSet::Large(ChunkedBitSet::new_empty(domain_size))
1114 }
1115 }
1116
1117 #[inline]
1118 pub fn is_empty(&self) -> bool {
1119 match self {
1120 MixedBitSet::Small(set) => set.is_empty(),
1121 MixedBitSet::Large(set) => set.is_empty(),
1122 }
1123 }
1124
1125 #[inline]
1126 pub fn contains(&self, elem: T) -> bool {
1127 match self {
1128 MixedBitSet::Small(set) => set.contains(elem),
1129 MixedBitSet::Large(set) => set.contains(elem),
1130 }
1131 }
1132
1133 #[inline]
1134 pub fn insert(&mut self, elem: T) -> bool {
1135 match self {
1136 MixedBitSet::Small(set) => set.insert(elem),
1137 MixedBitSet::Large(set) => set.insert(elem),
1138 }
1139 }
1140
1141 pub fn insert_all(&mut self) {
1142 match self {
1143 MixedBitSet::Small(set) => set.insert_all(),
1144 MixedBitSet::Large(set) => set.insert_all(),
1145 }
1146 }
1147
1148 #[inline]
1149 pub fn remove(&mut self, elem: T) -> bool {
1150 match self {
1151 MixedBitSet::Small(set) => set.remove(elem),
1152 MixedBitSet::Large(set) => set.remove(elem),
1153 }
1154 }
1155
1156 pub fn iter(&self) -> MixedBitIter<'_, T> {
1157 match self {
1158 MixedBitSet::Small(set) => MixedBitIter::Small(set.iter()),
1159 MixedBitSet::Large(set) => MixedBitIter::Large(set.iter()),
1160 }
1161 }
1162
1163 #[inline]
1164 pub fn clear(&mut self) {
1165 match self {
1166 MixedBitSet::Small(set) => set.clear(),
1167 MixedBitSet::Large(set) => set.clear(),
1168 }
1169 }
1170
1171 bit_relations_inherent_impls! {}
1172}
1173
1174impl<T> Clone for MixedBitSet<T> {
1175 fn clone(&self) -> Self {
1176 match self {
1177 MixedBitSet::Small(set) => MixedBitSet::Small(set.clone()),
1178 MixedBitSet::Large(set) => MixedBitSet::Large(set.clone()),
1179 }
1180 }
1181
1182 fn clone_from(&mut self, from: &Self) {
1187 match (self, from) {
1188 (MixedBitSet::Small(set), MixedBitSet::Small(from)) => set.clone_from(from),
1189 (MixedBitSet::Large(set), MixedBitSet::Large(from)) => set.clone_from(from),
1190 _ => panic!("MixedBitSet size mismatch"),
1191 }
1192 }
1193}
1194
1195impl<T: BitSetIndex> BitRelations<MixedBitSet<T>> for MixedBitSet<T> {
1196 fn union(&mut self, other: &MixedBitSet<T>) -> bool {
1197 match (self, other) {
1198 (MixedBitSet::Small(set), MixedBitSet::Small(other)) => set.union(other),
1199 (MixedBitSet::Large(set), MixedBitSet::Large(other)) => set.union(other),
1200 _ => panic!("MixedBitSet size mismatch"),
1201 }
1202 }
1203
1204 fn subtract(&mut self, other: &MixedBitSet<T>) -> bool {
1205 match (self, other) {
1206 (MixedBitSet::Small(set), MixedBitSet::Small(other)) => set.subtract(other),
1207 (MixedBitSet::Large(set), MixedBitSet::Large(other)) => set.subtract(other),
1208 _ => panic!("MixedBitSet size mismatch"),
1209 }
1210 }
1211
1212 fn intersect(&mut self, _other: &MixedBitSet<T>) -> bool {
1213 unimplemented!("implement if/when necessary");
1214 }
1215}
1216
1217impl<T: BitSetIndex> fmt::Debug for MixedBitSet<T> {
1218 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
1219 match self {
1220 MixedBitSet::Small(set) => set.fmt(w),
1221 MixedBitSet::Large(set) => set.fmt(w),
1222 }
1223 }
1224}
1225
1226pub enum MixedBitIter<'a, T: BitSetIndex> {
1227 Small(BitIter<'a, T>),
1228 Large(ChunkedBitIter<'a, T>),
1229}
1230
1231impl<'a, T: BitSetIndex> Iterator for MixedBitIter<'a, T> {
1232 type Item = T;
1233 fn next(&mut self) -> Option<T> {
1234 match self {
1235 MixedBitIter::Small(iter) => iter.next(),
1236 MixedBitIter::Large(iter) => iter.next(),
1237 }
1238 }
1239}
1240
1241#[derive(Debug, PartialEq)]
1249pub struct GrowableBitSet<T: BitSetIndex> {
1250 bit_set: DenseBitSet<T>,
1251}
1252
1253impl<T: BitSetIndex> Clone for GrowableBitSet<T> {
1254 fn clone(&self) -> Self {
1255 Self { bit_set: self.bit_set.clone() }
1256 }
1257
1258 fn clone_from(&mut self, source: &Self) {
1259 self.bit_set.clone_from(&source.bit_set);
1260 }
1261}
1262
1263impl<T: BitSetIndex> Default for GrowableBitSet<T> {
1264 fn default() -> Self {
1265 GrowableBitSet::new_empty()
1266 }
1267}
1268
1269impl<T: BitSetIndex> GrowableBitSet<T> {
1270 pub fn ensure(&mut self, min_domain_size: usize) {
1272 if self.bit_set.domain_size < min_domain_size {
1273 self.bit_set.domain_size = min_domain_size;
1274 }
1275
1276 let min_num_words = num_words(min_domain_size);
1277 if self.bit_set.words.len() < min_num_words {
1278 self.bit_set.words.resize(min_num_words, 0)
1279 }
1280 }
1281
1282 pub fn new_empty() -> GrowableBitSet<T> {
1283 GrowableBitSet { bit_set: DenseBitSet::new_empty(0) }
1284 }
1285
1286 pub fn with_capacity(capacity: usize) -> GrowableBitSet<T> {
1287 GrowableBitSet { bit_set: DenseBitSet::new_empty(capacity) }
1288 }
1289
1290 #[inline]
1292 pub fn insert(&mut self, elem: T) -> bool {
1293 self.ensure(elem.index() + 1);
1294 self.bit_set.insert(elem)
1295 }
1296
1297 #[inline]
1298 pub fn insert_range(&mut self, elems: Range<T>) {
1299 self.ensure(elems.end.index());
1300 self.bit_set.insert_range(elems);
1301 }
1302
1303 #[inline]
1305 pub fn remove(&mut self, elem: T) -> bool {
1306 self.ensure(elem.index() + 1);
1307 self.bit_set.remove(elem)
1308 }
1309
1310 #[inline]
1311 pub fn clear(&mut self) {
1312 self.bit_set.clear();
1313 }
1314
1315 #[inline]
1316 pub fn count(&self) -> usize {
1317 self.bit_set.count()
1318 }
1319
1320 #[inline]
1321 pub fn is_empty(&self) -> bool {
1322 self.bit_set.is_empty()
1323 }
1324
1325 #[inline]
1326 pub fn contains(&self, elem: T) -> bool {
1327 words_contain(&self.bit_set.words, elem.index())
1328 }
1329
1330 #[inline]
1331 pub fn contains_any(&self, elems: Range<T>) -> bool {
1332 elems.start.index() < self.bit_set.domain_size
1333 && self.bit_set.contains_any(
1334 elems.start..T::from_usize(elems.end.index().min(self.bit_set.domain_size)),
1335 )
1336 }
1337
1338 #[inline]
1339 pub fn iter(&self) -> BitIter<'_, T> {
1340 self.bit_set.iter()
1341 }
1342
1343 #[inline]
1344 pub fn len(&self) -> usize {
1345 self.bit_set.count()
1346 }
1347
1348 bit_relations_inherent_impls! {}
1349}
1350
1351impl<T: BitSetIndex> From<DenseBitSet<T>> for GrowableBitSet<T> {
1352 fn from(bit_set: DenseBitSet<T>) -> Self {
1353 Self { bit_set }
1354 }
1355}
1356
1357impl<T: BitSetIndex> BitRelations<Self> for GrowableBitSet<T> {
1358 fn union(&mut self, other: &Self) -> bool {
1359 self.ensure(other.bit_set.domain_size);
1360 union_words(&mut self.bit_set.words, &other.bit_set.words)
1361 }
1362
1363 fn subtract(&mut self, other: &Self) -> bool {
1364 let len = self.bit_set.words.len().min(other.bit_set.words.len());
1365 subtract_words(&mut self.bit_set.words[..len], &other.bit_set.words[..len])
1366 }
1367
1368 fn intersect(&mut self, other: &Self) -> bool {
1369 let len = self.bit_set.words.len().min(other.bit_set.words.len());
1370 let changed = intersect_words(&mut self.bit_set.words[..len], &other.bit_set.words[..len]);
1371 let truncated = !words_are_zero(&self.bit_set.words[len..]);
1372 self.bit_set.words[len..].fill(0);
1373 changed || truncated
1374 }
1375}
1376
1377#[derive(Clone, Eq, PartialEq, Hash)]
1385pub struct BitMatrix<R: BitSetIndex, C: BitSetIndex> {
1386 num_rows: usize,
1387 num_columns: usize,
1388 words: WordVec,
1389 marker: PhantomData<(R, C)>,
1390}
1391
1392impl<R: BitSetIndex, C: BitSetIndex> BitMatrix<R, C> {
1393 pub fn new(num_rows: usize, num_columns: usize) -> BitMatrix<R, C> {
1395 let words_per_row = num_words(num_columns);
1398 BitMatrix {
1399 num_rows,
1400 num_columns,
1401 words: WordVec::from_elem(0, num_rows * words_per_row),
1402 marker: PhantomData,
1403 }
1404 }
1405
1406 pub fn from_row_n(row: &DenseBitSet<C>, num_rows: usize) -> BitMatrix<R, C> {
1408 let num_columns = row.domain_size();
1409 let words_per_row = num_words(num_columns);
1410 assert_eq!(words_per_row, row.words.len());
1411 BitMatrix {
1412 num_rows,
1413 num_columns,
1414 words: iter::repeat_n(&row.words, num_rows).flatten().cloned().collect(),
1415 marker: PhantomData,
1416 }
1417 }
1418
1419 pub fn rows(&self) -> impl Iterator<Item = R> {
1420 (0..self.num_rows).map(R::from_usize)
1421 }
1422
1423 fn range(&self, row: R) -> (usize, usize) {
1425 let words_per_row = num_words(self.num_columns);
1426 let start = row.index() * words_per_row;
1427 (start, start + words_per_row)
1428 }
1429
1430 pub fn insert(&mut self, row: R, column: C) -> bool {
1435 assert!(row.index() < self.num_rows && column.index() < self.num_columns);
1436 let (start, _) = self.range(row);
1437 let (word_index, mask) = word_index_and_mask(column);
1438 let words = &mut self.words[..];
1439 let word = words[start + word_index];
1440 let new_word = word | mask;
1441 words[start + word_index] = new_word;
1442 word != new_word
1443 }
1444
1445 pub fn remove(&mut self, row: R, column: C) -> bool {
1449 assert!(row.index() < self.num_rows && column.index() < self.num_columns);
1450 let (start, _) = self.range(row);
1451 let (word_index, mask) = word_index_and_mask(column);
1452 let words = &mut self.words[..];
1453 let word = words[start + word_index];
1454 let new_word = word & !mask;
1455 words[start + word_index] = new_word;
1456 word != new_word
1457 }
1458
1459 pub fn contains(&self, row: R, column: C) -> bool {
1464 assert!(row.index() < self.num_rows && column.index() < self.num_columns);
1465 let (start, _) = self.range(row);
1466 let (word_index, mask) = word_index_and_mask(column);
1467 (self.words[start + word_index] & mask) != 0
1468 }
1469
1470 pub fn intersect_rows(&self, row1: R, row2: R) -> Vec<C> {
1475 assert!(row1.index() < self.num_rows && row2.index() < self.num_rows);
1476 let (row1_start, row1_end) = self.range(row1);
1477 let (row2_start, row2_end) = self.range(row2);
1478 let mut result = Vec::with_capacity(self.num_columns);
1479 for (base, (i, j)) in (row1_start..row1_end).zip(row2_start..row2_end).enumerate() {
1480 let mut v = self.words[i] & self.words[j];
1481 for bit in 0..WORD_BITS {
1482 if v == 0 {
1483 break;
1484 }
1485 if v & 0x1 != 0 {
1486 result.push(C::from_usize(base * WORD_BITS + bit));
1487 }
1488 v >>= 1;
1489 }
1490 }
1491 result
1492 }
1493
1494 pub fn union_rows(&mut self, read: R, write: R) -> bool {
1502 assert!(read.index() < self.num_rows && write.index() < self.num_rows);
1503 let (read_start, read_end) = self.range(read);
1504 let (write_start, write_end) = self.range(write);
1505 let words = &mut self.words[..];
1506 let mut changed = 0;
1507 for (read_index, write_index) in iter::zip(read_start..read_end, write_start..write_end) {
1508 let word = words[write_index];
1509 let new_word = word | words[read_index];
1510 words[write_index] = new_word;
1511 changed |= word ^ new_word;
1513 }
1514 changed != 0
1515 }
1516
1517 pub fn union_row_with(&mut self, with: &DenseBitSet<C>, write: R) -> bool {
1520 assert!(write.index() < self.num_rows);
1521 assert_eq!(with.domain_size(), self.num_columns);
1522 let (write_start, write_end) = self.range(write);
1523 union_words(&mut self.words[write_start..write_end], &with.words)
1524 }
1525
1526 pub fn insert_all_into_row(&mut self, row: R) {
1528 assert!(row.index() < self.num_rows);
1529 let (start, end) = self.range(row);
1530 let words = &mut self.words[..];
1531 for index in start..end {
1532 words[index] = !0;
1533 }
1534 clear_excess_bits_in_final_word(self.num_columns, &mut self.words[..end]);
1535 }
1536
1537 pub fn words(&self) -> &[Word] {
1539 &self.words
1540 }
1541
1542 pub fn iter(&self, row: R) -> BitIter<'_, C> {
1545 assert!(row.index() < self.num_rows);
1546 let (start, end) = self.range(row);
1547 BitIter::new(&self.words[start..end])
1548 }
1549
1550 pub fn count(&self, row: R) -> usize {
1552 let (start, end) = self.range(row);
1553 count_ones(&self.words[start..end])
1554 }
1555
1556 pub fn row(&self, row: R) -> BitMatrixRow<'_, C> {
1558 assert!(row.index() < self.num_rows);
1559 let (start, end) = self.range(row);
1560 BitMatrixRow {
1561 num_columns: self.num_columns,
1562 words: &self.words[start..end],
1563 marker: PhantomData,
1564 }
1565 }
1566
1567 pub fn replace_row(&mut self, row: R, with: &DenseBitSet<C>) -> bool {
1569 assert!(row.index() < self.num_rows);
1570 assert_eq!(with.domain_size(), self.num_columns);
1571 let (start, end) = self.range(row);
1572 let words = &mut self.words[start..end];
1573 if *words == *with.words {
1574 return false;
1575 }
1576 words.copy_from_slice(&with.words);
1577 true
1578 }
1579}
1580
1581#[derive(Clone, Copy)]
1585pub struct BitMatrixRow<'a, C> {
1586 num_columns: usize,
1587 words: &'a [Word],
1588 marker: PhantomData<C>,
1589}
1590
1591impl<'a, C: BitSetIndex> BitMatrixRow<'a, C> {
1592 pub fn contains(&self, column: C) -> bool {
1594 words_contain(self.words, column.index())
1595 }
1596
1597 pub fn count(&self) -> usize {
1599 count_ones(self.words)
1600 }
1601
1602 pub fn iter(&self) -> BitIter<'a, C> {
1604 BitIter::new(self.words)
1605 }
1606}
1607
1608impl<'a, C: BitSetIndex> IntoIterator for BitMatrixRow<'a, C> {
1609 type Item = C;
1610 type IntoIter = BitIter<'a, C>;
1611
1612 fn into_iter(self) -> Self::IntoIter {
1613 self.iter()
1614 }
1615}
1616
1617impl<C: BitSetIndex> From<BitMatrixRow<'_, C>> for DenseBitSet<C> {
1618 fn from(row: BitMatrixRow<'_, C>) -> Self {
1619 DenseBitSet {
1620 domain_size: row.num_columns,
1621 words: WordVec::from_slice(row.words),
1622 marker: PhantomData,
1623 }
1624 }
1625}
1626
1627impl<T: BitSetIndex> BitRelations<BitMatrixRow<'_, T>> for DenseBitSet<T> {
1629 fn union(&mut self, other: &BitMatrixRow<'_, T>) -> bool {
1630 assert_eq!(self.domain_size, other.num_columns);
1631 union_words(&mut self.words, other.words)
1632 }
1633
1634 fn subtract(&mut self, other: &BitMatrixRow<'_, T>) -> bool {
1635 assert_eq!(self.domain_size, other.num_columns);
1636 subtract_words(&mut self.words, other.words)
1637 }
1638
1639 fn intersect(&mut self, other: &BitMatrixRow<'_, T>) -> bool {
1640 assert_eq!(self.domain_size, other.num_columns);
1641 intersect_words(&mut self.words, other.words)
1642 }
1643}
1644
1645impl<R: BitSetIndex, C: BitSetIndex> fmt::Debug for BitMatrix<R, C> {
1646 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1647 struct OneLinePrinter<T>(T);
1649 impl<T: fmt::Debug> fmt::Debug for OneLinePrinter<T> {
1650 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1651 write!(fmt, "{:?}", self.0)
1652 }
1653 }
1654
1655 write!(fmt, "BitMatrix({}x{}) ", self.num_rows, self.num_columns)?;
1656 let items = self.rows().flat_map(|r| self.iter(r).map(move |c| (r, c)));
1657 fmt.debug_set().entries(items.map(OneLinePrinter)).finish()
1658 }
1659}
1660
1661#[derive(Clone, Debug)]
1673pub struct SparseBitMatrix<R, C>
1674where
1675 R: BitSetIndex,
1676 C: BitSetIndex,
1677{
1678 num_columns: usize,
1679 rows: Vec<Option<DenseBitSet<C>>>,
1680 marker: PhantomData<R>,
1681}
1682
1683impl<R: BitSetIndex, C: BitSetIndex> SparseBitMatrix<R, C> {
1684 pub fn new(num_columns: usize) -> Self {
1686 Self { num_columns, rows: Vec::new(), marker: PhantomData }
1687 }
1688
1689 fn ensure_row(&mut self, row: R) -> &mut DenseBitSet<C> {
1690 let row = row.index();
1693 if self.rows.len() <= row {
1694 self.rows.resize_with(row + 1, || None);
1695 }
1696 self.rows[row].get_or_insert_with(|| DenseBitSet::new_empty(self.num_columns))
1697 }
1698
1699 pub fn insert(&mut self, row: R, column: C) -> bool {
1704 self.ensure_row(row).insert(column)
1705 }
1706
1707 pub fn remove(&mut self, row: R, column: C) -> bool {
1713 match self.rows.get_mut(row.index()) {
1714 Some(Some(row)) => row.remove(column),
1715 _ => false,
1716 }
1717 }
1718
1719 pub fn clear(&mut self, row: R) {
1722 if let Some(Some(row)) = self.rows.get_mut(row.index()) {
1723 row.clear();
1724 }
1725 }
1726
1727 pub fn contains(&self, row: R, column: C) -> bool {
1732 self.row(row).is_some_and(|r| r.contains(column))
1733 }
1734
1735 pub fn union_rows(&mut self, read: R, write: R) -> bool {
1743 if read == write || self.row(read).is_none() {
1744 return false;
1745 }
1746
1747 self.ensure_row(write);
1748 let Ok([read_row, write_row]) = self.rows.get_disjoint_mut([read.index(), write.index()])
1749 else {
1750 unreachable!()
1751 };
1752 let (Some(read_row), Some(write_row)) = (read_row.as_ref(), write_row.as_mut()) else {
1753 unreachable!()
1754 };
1755 write_row.union(read_row)
1756 }
1757
1758 pub fn insert_all_into_row(&mut self, row: R) {
1760 self.ensure_row(row).insert_all();
1761 }
1762
1763 pub fn rows(&self) -> impl Iterator<Item = R> {
1764 (0..self.rows.len()).map(R::from_usize)
1765 }
1766
1767 pub fn iter(&self, row: R) -> impl Iterator<Item = C> {
1770 self.row(row).into_iter().flat_map(|r| r.iter())
1771 }
1772
1773 pub fn row(&self, row: R) -> Option<&DenseBitSet<C>> {
1774 self.rows.get(row.index())?.as_ref()
1775 }
1776
1777 pub fn intersect_row<Set>(&mut self, row: R, set: &Set) -> bool
1782 where
1783 DenseBitSet<C>: BitRelations<Set>,
1784 {
1785 match self.rows.get_mut(row.index()) {
1786 Some(Some(row)) => row.intersect(set),
1787 _ => false,
1788 }
1789 }
1790
1791 pub fn subtract_row<Set>(&mut self, row: R, set: &Set) -> bool
1796 where
1797 DenseBitSet<C>: BitRelations<Set>,
1798 {
1799 match self.rows.get_mut(row.index()) {
1800 Some(Some(row)) => row.subtract(set),
1801 _ => false,
1802 }
1803 }
1804
1805 pub fn union_row<Set>(&mut self, row: R, set: &Set) -> bool
1810 where
1811 DenseBitSet<C>: BitRelations<Set>,
1812 {
1813 self.ensure_row(row).union(set)
1814 }
1815}
1816
1817#[inline]
1818fn num_words(domain_size: usize) -> usize {
1819 domain_size.div_ceil(WORD_BITS)
1820}
1821
1822#[inline]
1823fn word_index_and_mask<T: BitSetIndex>(elem: T) -> (usize, Word) {
1824 word_index_and_mask_usize(elem.index())
1825}
1826
1827#[inline]
1828fn word_index_and_mask_usize(elem: usize) -> (usize, Word) {
1829 let word_index = elem / WORD_BITS;
1830 let mask = 1 << (elem % WORD_BITS);
1831 (word_index, mask)
1832}
1833
1834#[inline]
1835fn chunk_index<T: BitSetIndex>(elem: T) -> usize {
1836 elem.index() / CHUNK_BITS
1837}
1838
1839#[inline]
1840fn chunk_word_index_and_mask<T: BitSetIndex>(elem: T) -> (usize, Word) {
1841 let chunk_elem = elem.index() % CHUNK_BITS;
1842 word_index_and_mask_usize(chunk_elem)
1843}
1844
1845fn clear_excess_bits_in_final_word(domain_size: usize, words: &mut [Word]) {
1846 let num_bits_in_final_word = domain_size % WORD_BITS;
1847 if num_bits_in_final_word > 0 {
1848 let mask = (1 << num_bits_in_final_word) - 1;
1849 words[words.len() - 1] &= mask;
1850 }
1851}
1852
1853#[inline]
1854fn max_bit(word: Word) -> usize {
1855 WORD_BITS - 1 - word.leading_zeros() as usize
1856}
1857
1858#[inline]
1859fn count_ones(words: &[Word]) -> usize {
1860 words.iter().map(|word| word.count_ones() as usize).sum()
1861}
1862
1863#[inline]
1864fn inclusive_start_end<T: BitSetIndex>(
1865 range: impl RangeBounds<T>,
1866 domain: usize,
1867) -> Option<(usize, usize)> {
1868 let start = match range.start_bound().cloned() {
1870 Bound::Included(start) => start.index(),
1871 Bound::Excluded(start) => start.index() + 1,
1872 Bound::Unbounded => 0,
1873 };
1874 let end = match range.end_bound().cloned() {
1875 Bound::Included(end) => end.index(),
1876 Bound::Excluded(end) => end.index().checked_sub(1)?,
1877 Bound::Unbounded => domain - 1,
1878 };
1879 assert!(end < domain);
1880 if start > end {
1881 return None;
1882 }
1883 Some((start, end))
1884}
1885
1886#[inline]
1899fn update_words<Op>(lhs: &mut [Word], rhs: &[Word], op: Op) -> bool
1900where
1901 Op: Fn(Word, Word) -> Word,
1902{
1903 assert_eq!(lhs.len(), rhs.len());
1904 let mut changed = 0;
1905 for (lhs_slot, &rhs_val) in iter::zip(lhs, rhs) {
1906 let old_val = *lhs_slot;
1907 let new_val = op(old_val, rhs_val);
1908 *lhs_slot = new_val;
1909 changed |= old_val ^ new_val;
1914 }
1915 changed != 0
1916}
1917
1918#[inline]
1923fn union_words(lhs: &mut [Word], rhs: &[Word]) -> bool {
1924 update_words(lhs, rhs, |a, b| a | b)
1925}
1926
1927#[inline]
1929fn subtract_words(lhs: &mut [Word], rhs: &[Word]) -> bool {
1930 update_words(lhs, rhs, |a, b| a & !b)
1931}
1932
1933#[inline]
1935fn intersect_words(lhs: &mut [Word], rhs: &[Word]) -> bool {
1936 update_words(lhs, rhs, |a, b| a & b)
1937}
1938
1939#[inline]
1941fn words_are_zero(words: &[Word]) -> bool {
1942 words.iter().all(|&word| word == 0)
1943}
1944
1945#[inline]
1947fn words_contain(words: &[Word], elem: usize) -> bool {
1948 let (word_index, mask) = word_index_and_mask_usize(elem);
1949 words.get(word_index).is_some_and(|word| (word & mask) != 0)
1950}
1951
1952#[inline]
1955fn would_modify_words<Op>(lhs: &[Word], rhs: &[Word], op: Op) -> bool
1956where
1957 Op: Fn(Word, Word) -> Word,
1958{
1959 assert_eq!(lhs.len(), rhs.len());
1960
1961 const SUBCHUNK_LEN: usize = 64 / size_of::<Word>();
1966 let (lhs_chunks, lhs_tail) = lhs.as_chunks::<SUBCHUNK_LEN>();
1967 let (rhs_chunks, rhs_tail) = rhs.as_chunks::<SUBCHUNK_LEN>();
1968
1969 let would_modify_subchunk = |lhs_chunk: &[Word], rhs_chunk: &[Word]| {
1970 let mut changed = 0;
1971 for (&old_val, &rhs_val) in iter::zip(lhs_chunk, rhs_chunk) {
1972 let new_val = op(old_val, rhs_val);
1973 changed |= old_val ^ new_val;
1976 }
1977 changed != 0
1978 };
1979
1980 for (lhs_chunk, rhs_chunk) in iter::zip(lhs_chunks, rhs_chunks) {
1981 if would_modify_subchunk(lhs_chunk, rhs_chunk) {
1982 return true;
1983 }
1984 }
1985 would_modify_subchunk(lhs_tail, rhs_tail)
1986}