1use std::marker::PhantomData;
2use std::ops::{Bound, Range, RangeBounds};
3use std::rc::Rc;
4use std::{fmt, iter, slice};
5
6use Chunk::*;
7#[cfg(feature = "nightly")]
8use rustc_macros::{Decodable_NoContext, Encodable_NoContext};
9
10use crate::{Idx, IndexVec};
11
12#[cfg(test)]
13mod tests;
14
15type Word = u64;
16const WORD_BYTES: usize = size_of::<Word>();
17const WORD_BITS: usize = WORD_BYTES * 8;
18
19const CHUNK_WORDS: usize = 32;
30const CHUNK_BITS: usize = CHUNK_WORDS * WORD_BITS; type ChunkSize = u16;
35const _: () = if !(CHUNK_BITS <= ChunkSize::MAX as usize) {
::core::panicking::panic("assertion failed: CHUNK_BITS <= ChunkSize::MAX as usize")
}assert!(CHUNK_BITS <= ChunkSize::MAX as usize);
36
37pub trait BitRelations<Rhs> {
38 fn union(&mut self, other: &Rhs) -> bool;
39 fn subtract(&mut self, other: &Rhs) -> bool;
40 fn intersect(&mut self, other: &Rhs) -> bool;
41}
42
43#[inline]
44fn inclusive_start_end<T: Idx>(
45 range: impl RangeBounds<T>,
46 domain: usize,
47) -> Option<(usize, usize)> {
48 let start = match range.start_bound().cloned() {
50 Bound::Included(start) => start.index(),
51 Bound::Excluded(start) => start.index() + 1,
52 Bound::Unbounded => 0,
53 };
54 let end = match range.end_bound().cloned() {
55 Bound::Included(end) => end.index(),
56 Bound::Excluded(end) => end.index().checked_sub(1)?,
57 Bound::Unbounded => domain - 1,
58 };
59 if !(end < domain) {
::core::panicking::panic("assertion failed: end < domain")
};assert!(end < domain);
60 if start > end {
61 return None;
62 }
63 Some((start, end))
64}
65
66macro_rules! bit_relations_inherent_impls {
67 () => {
68 pub fn union<Rhs>(&mut self, other: &Rhs) -> bool
71 where
72 Self: BitRelations<Rhs>,
73 {
74 <Self as BitRelations<Rhs>>::union(self, other)
75 }
76
77 pub fn subtract<Rhs>(&mut self, other: &Rhs) -> bool
80 where
81 Self: BitRelations<Rhs>,
82 {
83 <Self as BitRelations<Rhs>>::subtract(self, other)
84 }
85
86 pub fn intersect<Rhs>(&mut self, other: &Rhs) -> bool
89 where
90 Self: BitRelations<Rhs>,
91 {
92 <Self as BitRelations<Rhs>>::intersect(self, other)
93 }
94 };
95}
96
97#[cfg_attr(feature = "nightly", derive(const _: () =
{
impl<T, __D: ::rustc_serialize::Decoder>
::rustc_serialize::Decodable<__D> for DenseBitSet<T> where
PhantomData<T>: ::rustc_serialize::Decodable<__D> {
fn decode(__decoder: &mut __D) -> Self {
DenseBitSet {
domain_size: ::rustc_serialize::Decodable::decode(__decoder),
words: ::rustc_serialize::Decodable::decode(__decoder),
marker: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable_NoContext, const _: () =
{
impl<T, __E: ::rustc_serialize::Encoder>
::rustc_serialize::Encodable<__E> for DenseBitSet<T> where
PhantomData<T>: ::rustc_serialize::Encodable<__E> {
fn encode(&self, __encoder: &mut __E) {
match *self {
DenseBitSet {
domain_size: ref __binding_0,
words: ref __binding_1,
marker: ref __binding_2 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
}
}
}
}
};Encodable_NoContext))]
115#[derive(#[automatically_derived]
impl<T: ::core::cmp::Eq> ::core::cmp::Eq for DenseBitSet<T> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
let _: ::core::cmp::AssertParamIsEq<Vec<Word>>;
let _: ::core::cmp::AssertParamIsEq<PhantomData<T>>;
}
}Eq, #[automatically_derived]
impl<T: ::core::cmp::PartialEq> ::core::cmp::PartialEq for DenseBitSet<T> {
#[inline]
fn eq(&self, other: &DenseBitSet<T>) -> bool {
self.domain_size == other.domain_size && self.words == other.words &&
self.marker == other.marker
}
}PartialEq, #[automatically_derived]
impl<T: ::core::hash::Hash> ::core::hash::Hash for DenseBitSet<T> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.domain_size, state);
::core::hash::Hash::hash(&self.words, state);
::core::hash::Hash::hash(&self.marker, state)
}
}Hash)]
116pub struct DenseBitSet<T> {
117 domain_size: usize,
118 words: Vec<Word>,
119 marker: PhantomData<T>,
120}
121
122impl<T> DenseBitSet<T> {
123 pub fn domain_size(&self) -> usize {
125 self.domain_size
126 }
127}
128
129impl<T: Idx> DenseBitSet<T> {
130 #[inline]
132 pub fn new_empty(domain_size: usize) -> DenseBitSet<T> {
133 let num_words = num_words(domain_size);
134 DenseBitSet { domain_size, words: ::alloc::vec::from_elem(0, num_words)vec![0; num_words], marker: PhantomData }
135 }
136
137 #[inline]
139 pub fn new_filled(domain_size: usize) -> DenseBitSet<T> {
140 let num_words = num_words(domain_size);
141 let mut result =
142 DenseBitSet { domain_size, words: ::alloc::vec::from_elem(!0, num_words)vec![!0; num_words], marker: PhantomData };
143 result.clear_excess_bits();
144 result
145 }
146
147 #[inline]
149 pub fn clear(&mut self) {
150 self.words.fill(0);
151 }
152
153 fn clear_excess_bits(&mut self) {
155 clear_excess_bits_in_final_word(self.domain_size, &mut self.words);
156 }
157
158 pub fn count(&self) -> usize {
160 count_ones(&self.words)
161 }
162
163 #[inline]
165 pub fn contains(&self, elem: T) -> bool {
166 if !(elem.index() < self.domain_size) {
::core::panicking::panic("assertion failed: elem.index() < self.domain_size")
};assert!(elem.index() < self.domain_size);
167 let (word_index, mask) = word_index_and_mask(elem);
168 (self.words[word_index] & mask) != 0
169 }
170
171 #[inline]
173 pub fn superset(&self, other: &DenseBitSet<T>) -> bool {
174 {
match (&self.domain_size, &other.domain_size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.domain_size, other.domain_size);
175 self.words.iter().zip(&other.words).all(|(a, b)| (a & b) == *b)
176 }
177
178 #[inline]
180 pub fn is_empty(&self) -> bool {
181 self.words.iter().all(|a| *a == 0)
182 }
183
184 #[inline]
186 pub fn insert(&mut self, elem: T) -> bool {
187 if !(elem.index() < self.domain_size) {
{
::core::panicking::panic_fmt(format_args!("inserting element at index {0} but domain size is {1}",
elem.index(), self.domain_size));
}
};assert!(
188 elem.index() < self.domain_size,
189 "inserting element at index {} but domain size is {}",
190 elem.index(),
191 self.domain_size,
192 );
193 let (word_index, mask) = word_index_and_mask(elem);
194 let word_ref = &mut self.words[word_index];
195 let word = *word_ref;
196 let new_word = word | mask;
197 *word_ref = new_word;
198 new_word != word
199 }
200
201 #[inline]
202 pub fn insert_range(&mut self, elems: impl RangeBounds<T>) {
203 let Some((start, end)) = inclusive_start_end(elems, self.domain_size) else {
204 return;
205 };
206
207 let (start_word_index, start_mask) = word_index_and_mask(start);
208 let (end_word_index, end_mask) = word_index_and_mask(end);
209
210 for word_index in (start_word_index + 1)..end_word_index {
212 self.words[word_index] = !0;
213 }
214
215 if start_word_index != end_word_index {
216 self.words[start_word_index] |= !(start_mask - 1);
220 self.words[end_word_index] |= end_mask | (end_mask - 1);
223 } else {
224 self.words[start_word_index] |= end_mask | (end_mask - start_mask);
225 }
226 }
227
228 pub fn insert_all(&mut self) {
230 self.words.fill(!0);
231 self.clear_excess_bits();
232 }
233
234 #[inline]
236 pub fn contains_any(&self, elems: impl RangeBounds<T>) -> bool {
237 let Some((start, end)) = inclusive_start_end(elems, self.domain_size) else {
238 return false;
239 };
240 let (start_word_index, start_mask) = word_index_and_mask(start);
241 let (end_word_index, end_mask) = word_index_and_mask(end);
242
243 if start_word_index == end_word_index {
244 self.words[start_word_index] & (end_mask | (end_mask - start_mask)) != 0
245 } else {
246 if self.words[start_word_index] & !(start_mask - 1) != 0 {
247 return true;
248 }
249
250 let remaining = start_word_index + 1..end_word_index;
251 if remaining.start <= remaining.end {
252 self.words[remaining].iter().any(|&w| w != 0)
253 || self.words[end_word_index] & (end_mask | (end_mask - 1)) != 0
254 } else {
255 false
256 }
257 }
258 }
259
260 #[inline]
262 pub fn remove(&mut self, elem: T) -> bool {
263 if !(elem.index() < self.domain_size) {
::core::panicking::panic("assertion failed: elem.index() < self.domain_size")
};assert!(elem.index() < self.domain_size);
264 let (word_index, mask) = word_index_and_mask(elem);
265 let word_ref = &mut self.words[word_index];
266 let word = *word_ref;
267 let new_word = word & !mask;
268 *word_ref = new_word;
269 new_word != word
270 }
271
272 #[inline]
274 pub fn iter(&self) -> BitIter<'_, T> {
275 BitIter::new(&self.words)
276 }
277
278 pub fn first_set_at_or_after(&self, elem: T) -> Option<T> {
280 if !(elem.index() < self.domain_size) {
::core::panicking::panic("assertion failed: elem.index() < self.domain_size")
};assert!(elem.index() < self.domain_size);
281 let (mut word_index, mask) = word_index_and_mask(elem);
282 let mut word = self.words[word_index] & !(mask - 1);
284 loop {
285 if word != 0 {
286 return Some(T::new(WORD_BITS * word_index + word.trailing_zeros() as usize));
287 }
288 word_index += 1;
289 word = *self.words.get(word_index)?;
290 }
291 }
292
293 pub fn last_set_in(&self, range: impl RangeBounds<T>) -> Option<T> {
294 let (start, end) = inclusive_start_end(range, self.domain_size)?;
295 let (start_word_index, _) = word_index_and_mask(start);
296 let (end_word_index, end_mask) = word_index_and_mask(end);
297
298 let end_word = self.words[end_word_index] & (end_mask | (end_mask - 1));
299 if end_word != 0 {
300 let pos = max_bit(end_word) + WORD_BITS * end_word_index;
301 if start <= pos {
302 return Some(T::new(pos));
303 }
304 }
305
306 if let Some(offset) =
310 self.words[start_word_index..end_word_index].iter().rposition(|&w| w != 0)
311 {
312 let word_idx = start_word_index + offset;
313 let start_word = self.words[word_idx];
314 let pos = max_bit(start_word) + WORD_BITS * word_idx;
315 if start <= pos {
316 return Some(T::new(pos));
317 }
318 }
319
320 None
321 }
322
323 pub fn union<Rhs>(&mut self, other: &Rhs) -> bool where
Self: BitRelations<Rhs> {
<Self as BitRelations<Rhs>>::union(self, other)
}
pub fn subtract<Rhs>(&mut self, other: &Rhs) -> bool where
Self: BitRelations<Rhs> {
<Self as BitRelations<Rhs>>::subtract(self, other)
}
pub fn intersect<Rhs>(&mut self, other: &Rhs) -> bool where
Self: BitRelations<Rhs> {
<Self as BitRelations<Rhs>>::intersect(self, other)
}bit_relations_inherent_impls! {}
324
325 pub fn union_not(&mut self, other: &DenseBitSet<T>) {
330 {
match (&self.domain_size, &other.domain_size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.domain_size, other.domain_size);
331
332 update_words(&mut self.words, &other.words, |a, b| a | !b);
338 self.clear_excess_bits();
341 }
342}
343
344impl<T: Idx> BitRelations<DenseBitSet<T>> for DenseBitSet<T> {
346 fn union(&mut self, other: &DenseBitSet<T>) -> bool {
347 {
match (&self.domain_size, &other.domain_size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.domain_size, other.domain_size);
348 update_words(&mut self.words, &other.words, |a, b| a | b)
349 }
350
351 fn subtract(&mut self, other: &DenseBitSet<T>) -> bool {
352 {
match (&self.domain_size, &other.domain_size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.domain_size, other.domain_size);
353 update_words(&mut self.words, &other.words, |a, b| a & !b)
354 }
355
356 fn intersect(&mut self, other: &DenseBitSet<T>) -> bool {
357 {
match (&self.domain_size, &other.domain_size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.domain_size, other.domain_size);
358 update_words(&mut self.words, &other.words, |a, b| a & b)
359 }
360}
361
362impl<T: Idx> From<GrowableBitSet<T>> for DenseBitSet<T> {
363 fn from(bit_set: GrowableBitSet<T>) -> Self {
364 bit_set.bit_set
365 }
366}
367
368impl<T> Clone for DenseBitSet<T> {
369 fn clone(&self) -> Self {
370 DenseBitSet {
371 domain_size: self.domain_size,
372 words: self.words.clone(),
373 marker: PhantomData,
374 }
375 }
376
377 fn clone_from(&mut self, from: &Self) {
378 self.domain_size = from.domain_size;
379 self.words.clone_from(&from.words);
380 }
381}
382
383impl<T: Idx> fmt::Debug for DenseBitSet<T> {
384 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
385 w.debug_list().entries(self.iter()).finish()
386 }
387}
388
389impl<T: Idx> ToString for DenseBitSet<T> {
390 fn to_string(&self) -> String {
391 let mut result = String::new();
392 let mut sep = '[';
393
394 let mut i = 0;
398 for word in &self.words {
399 let mut word = *word;
400 for _ in 0..WORD_BYTES {
401 let remain = self.domain_size - i;
403 let mask = if remain <= 8 { (1 << remain) - 1 } else { 0xFF };
405 if !(mask <= 0xFF) {
::core::panicking::panic("assertion failed: mask <= 0xFF")
};assert!(mask <= 0xFF);
406 let byte = word & mask;
407
408 result.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1:02x}", sep, byte))
})format!("{sep}{byte:02x}"));
409
410 if remain <= 8 {
411 break;
412 }
413 word >>= 8;
414 i += 8;
415 sep = '-';
416 }
417 sep = '|';
418 }
419 result.push(']');
420
421 result
422 }
423}
424
425pub struct BitIter<'a, T: Idx> {
426 word: Word,
430
431 offset: usize,
433
434 iter: slice::Iter<'a, Word>,
436
437 marker: PhantomData<T>,
438}
439
440impl<'a, T: Idx> BitIter<'a, T> {
441 #[inline]
442 fn new(words: &'a [Word]) -> BitIter<'a, T> {
443 BitIter {
449 word: 0,
450 offset: usize::MAX - (WORD_BITS - 1),
451 iter: words.iter(),
452 marker: PhantomData,
453 }
454 }
455}
456
457impl<'a, T: Idx> Iterator for BitIter<'a, T> {
458 type Item = T;
459 fn next(&mut self) -> Option<T> {
460 loop {
461 if self.word != 0 {
462 let bit_pos = self.word.trailing_zeros() as usize;
465 self.word ^= 1 << bit_pos;
466 return Some(T::new(bit_pos + self.offset));
467 }
468
469 self.word = *self.iter.next()?;
472 self.offset = self.offset.wrapping_add(WORD_BITS);
473 }
474 }
475}
476
477#[derive(#[automatically_derived]
impl<T: ::core::cmp::PartialEq> ::core::cmp::PartialEq for ChunkedBitSet<T> {
#[inline]
fn eq(&self, other: &ChunkedBitSet<T>) -> bool {
self.domain_size == other.domain_size && self.chunks == other.chunks
&& self.marker == other.marker
}
}PartialEq, #[automatically_derived]
impl<T: ::core::cmp::Eq> ::core::cmp::Eq for ChunkedBitSet<T> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
let _: ::core::cmp::AssertParamIsEq<Box<[Chunk]>>;
let _: ::core::cmp::AssertParamIsEq<PhantomData<T>>;
}
}Eq)]
496pub struct ChunkedBitSet<T> {
497 domain_size: usize,
498
499 chunks: Box<[Chunk]>,
502
503 marker: PhantomData<T>,
504}
505
506#[derive(#[automatically_derived]
impl ::core::clone::Clone for Chunk {
#[inline]
fn clone(&self) -> Chunk {
match self {
Chunk::Zeros { chunk_domain_size: __self_0 } =>
Chunk::Zeros {
chunk_domain_size: ::core::clone::Clone::clone(__self_0),
},
Chunk::Ones { chunk_domain_size: __self_0 } =>
Chunk::Ones {
chunk_domain_size: ::core::clone::Clone::clone(__self_0),
},
Chunk::Mixed {
chunk_domain_size: __self_0,
ones_count: __self_1,
words: __self_2 } =>
Chunk::Mixed {
chunk_domain_size: ::core::clone::Clone::clone(__self_0),
ones_count: ::core::clone::Clone::clone(__self_1),
words: ::core::clone::Clone::clone(__self_2),
},
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Chunk {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Chunk::Zeros { chunk_domain_size: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Zeros",
"chunk_domain_size", &__self_0),
Chunk::Ones { chunk_domain_size: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Ones",
"chunk_domain_size", &__self_0),
Chunk::Mixed {
chunk_domain_size: __self_0,
ones_count: __self_1,
words: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f, "Mixed",
"chunk_domain_size", __self_0, "ones_count", __self_1,
"words", &__self_2),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for Chunk {
#[inline]
fn eq(&self, other: &Chunk) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(Chunk::Zeros { chunk_domain_size: __self_0 }, Chunk::Zeros {
chunk_domain_size: __arg1_0 }) => __self_0 == __arg1_0,
(Chunk::Ones { chunk_domain_size: __self_0 }, Chunk::Ones {
chunk_domain_size: __arg1_0 }) => __self_0 == __arg1_0,
(Chunk::Mixed {
chunk_domain_size: __self_0,
ones_count: __self_1,
words: __self_2 }, Chunk::Mixed {
chunk_domain_size: __arg1_0,
ones_count: __arg1_1,
words: __arg1_2 }) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1 &&
__self_2 == __arg1_2,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Chunk {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ChunkSize>;
let _: ::core::cmp::AssertParamIsEq<Rc<[Word; CHUNK_WORDS]>>;
}
}Eq)]
511enum Chunk {
512 Zeros { chunk_domain_size: ChunkSize },
514
515 Ones { chunk_domain_size: ChunkSize },
517
518 Mixed {
532 chunk_domain_size: ChunkSize,
533 ones_count: ChunkSize,
540 words: Rc<[Word; CHUNK_WORDS]>,
541 },
542}
543
544#[cfg(target_pointer_width = "64")]
546const _: [(); 16] = [(); ::std::mem::size_of::<Chunk>()];crate::static_assert_size!(Chunk, 16);
547
548impl<T> ChunkedBitSet<T> {
549 pub fn domain_size(&self) -> usize {
550 self.domain_size
551 }
552
553 #[cfg(test)]
554 fn assert_valid(&self) {
555 if self.domain_size == 0 {
556 assert!(self.chunks.is_empty());
557 return;
558 }
559
560 assert!((self.chunks.len() - 1) * CHUNK_BITS <= self.domain_size);
561 assert!(self.chunks.len() * CHUNK_BITS >= self.domain_size);
562 for chunk in self.chunks.iter() {
563 chunk.assert_valid();
564 }
565 }
566}
567
568impl<T: Idx> ChunkedBitSet<T> {
569 fn new(domain_size: usize, is_empty: bool) -> Self {
571 let chunks = if domain_size == 0 {
572 Box::new([])
573 } else {
574 let num_chunks = domain_size.index().div_ceil(CHUNK_BITS);
575 let mut last_chunk_domain_size = domain_size % CHUNK_BITS;
576 if last_chunk_domain_size == 0 {
577 last_chunk_domain_size = CHUNK_BITS;
578 };
579
580 let (normal_chunk, final_chunk) = if is_empty {
583 (
584 Zeros { chunk_domain_size: CHUNK_BITS as ChunkSize },
585 Zeros { chunk_domain_size: last_chunk_domain_size as ChunkSize },
586 )
587 } else {
588 (
589 Ones { chunk_domain_size: CHUNK_BITS as ChunkSize },
590 Ones { chunk_domain_size: last_chunk_domain_size as ChunkSize },
591 )
592 };
593 let mut chunks = ::alloc::vec::from_elem(normal_chunk, num_chunks)vec![normal_chunk; num_chunks].into_boxed_slice();
594 *chunks.as_mut().last_mut().unwrap() = final_chunk;
595 chunks
596 };
597 ChunkedBitSet { domain_size, chunks, marker: PhantomData }
598 }
599
600 #[inline]
602 pub fn new_empty(domain_size: usize) -> Self {
603 ChunkedBitSet::new(domain_size, true)
604 }
605
606 #[inline]
608 pub fn new_filled(domain_size: usize) -> Self {
609 ChunkedBitSet::new(domain_size, false)
610 }
611
612 pub fn clear(&mut self) {
613 *self = ChunkedBitSet::new_empty(self.domain_size);
615 }
616
617 #[cfg(test)]
618 fn chunks(&self) -> &[Chunk] {
619 &self.chunks
620 }
621
622 pub fn count(&self) -> usize {
624 self.chunks.iter().map(|chunk| chunk.count()).sum()
625 }
626
627 pub fn is_empty(&self) -> bool {
628 self.chunks.iter().all(|chunk| #[allow(non_exhaustive_omitted_patterns)] match chunk {
Zeros { .. } => true,
_ => false,
}matches!(chunk, Zeros { .. }))
629 }
630
631 #[inline]
633 pub fn contains(&self, elem: T) -> bool {
634 if !(elem.index() < self.domain_size) {
::core::panicking::panic("assertion failed: elem.index() < self.domain_size")
};assert!(elem.index() < self.domain_size);
635 let chunk = &self.chunks[chunk_index(elem)];
636 match &chunk {
637 Zeros { .. } => false,
638 Ones { .. } => true,
639 Mixed { words, .. } => {
640 let (word_index, mask) = chunk_word_index_and_mask(elem);
641 (words[word_index] & mask) != 0
642 }
643 }
644 }
645
646 #[inline]
647 pub fn iter(&self) -> ChunkedBitIter<'_, T> {
648 ChunkedBitIter::new(self)
649 }
650
651 pub fn insert(&mut self, elem: T) -> bool {
653 if !(elem.index() < self.domain_size) {
::core::panicking::panic("assertion failed: elem.index() < self.domain_size")
};assert!(elem.index() < self.domain_size);
654 let chunk_index = chunk_index(elem);
655 let chunk = &mut self.chunks[chunk_index];
656 match *chunk {
657 Zeros { chunk_domain_size } => {
658 if chunk_domain_size > 1 {
659 let mut words = {
660 let words = Rc::<[Word; CHUNK_WORDS]>::new_zeroed();
662 unsafe { words.assume_init() }
664 };
665 let words_ref = Rc::get_mut(&mut words).unwrap();
666
667 let (word_index, mask) = chunk_word_index_and_mask(elem);
668 words_ref[word_index] |= mask;
669 *chunk = Mixed { chunk_domain_size, ones_count: 1, words };
670 } else {
671 *chunk = Ones { chunk_domain_size };
672 }
673 true
674 }
675 Ones { .. } => false,
676 Mixed { chunk_domain_size, ref mut ones_count, ref mut words } => {
677 let (word_index, mask) = chunk_word_index_and_mask(elem);
679 if (words[word_index] & mask) == 0 {
680 *ones_count += 1;
681 if *ones_count < chunk_domain_size {
682 let words = Rc::make_mut(words);
683 words[word_index] |= mask;
684 } else {
685 *chunk = Ones { chunk_domain_size };
686 }
687 true
688 } else {
689 false
690 }
691 }
692 }
693 }
694
695 pub fn insert_all(&mut self) {
697 *self = ChunkedBitSet::new_filled(self.domain_size);
699 }
700
701 pub fn remove(&mut self, elem: T) -> bool {
703 if !(elem.index() < self.domain_size) {
::core::panicking::panic("assertion failed: elem.index() < self.domain_size")
};assert!(elem.index() < self.domain_size);
704 let chunk_index = chunk_index(elem);
705 let chunk = &mut self.chunks[chunk_index];
706 match *chunk {
707 Zeros { .. } => false,
708 Ones { chunk_domain_size } => {
709 if chunk_domain_size > 1 {
710 let mut words = {
711 let words = Rc::<[Word; CHUNK_WORDS]>::new_zeroed();
713 unsafe { words.assume_init() }
715 };
716 let words_ref = Rc::get_mut(&mut words).unwrap();
717
718 let num_words = num_words(chunk_domain_size as usize);
720 words_ref[..num_words].fill(!0);
721 clear_excess_bits_in_final_word(
722 chunk_domain_size as usize,
723 &mut words_ref[..num_words],
724 );
725 let (word_index, mask) = chunk_word_index_and_mask(elem);
726 words_ref[word_index] &= !mask;
727 *chunk = Mixed { chunk_domain_size, ones_count: chunk_domain_size - 1, words };
728 } else {
729 *chunk = Zeros { chunk_domain_size };
730 }
731 true
732 }
733 Mixed { chunk_domain_size, ref mut ones_count, ref mut words } => {
734 let (word_index, mask) = chunk_word_index_and_mask(elem);
736 if (words[word_index] & mask) != 0 {
737 *ones_count -= 1;
738 if *ones_count > 0 {
739 let words = Rc::make_mut(words);
740 words[word_index] &= !mask;
741 } else {
742 *chunk = Zeros { chunk_domain_size }
743 }
744 true
745 } else {
746 false
747 }
748 }
749 }
750 }
751
752 fn chunk_iter(&self, chunk_index: usize) -> ChunkIter<'_> {
753 match self.chunks.get(chunk_index) {
754 Some(Zeros { .. }) => ChunkIter::Zeros,
755 Some(Ones { chunk_domain_size }) => ChunkIter::Ones(0..*chunk_domain_size as usize),
756 Some(Mixed { chunk_domain_size, words, .. }) => {
757 let num_words = num_words(*chunk_domain_size as usize);
758 ChunkIter::Mixed(BitIter::new(&words[0..num_words]))
759 }
760 None => ChunkIter::Finished,
761 }
762 }
763
764 pub fn union<Rhs>(&mut self, other: &Rhs) -> bool where
Self: BitRelations<Rhs> {
<Self as BitRelations<Rhs>>::union(self, other)
}
pub fn subtract<Rhs>(&mut self, other: &Rhs) -> bool where
Self: BitRelations<Rhs> {
<Self as BitRelations<Rhs>>::subtract(self, other)
}
pub fn intersect<Rhs>(&mut self, other: &Rhs) -> bool where
Self: BitRelations<Rhs> {
<Self as BitRelations<Rhs>>::intersect(self, other)
}bit_relations_inherent_impls! {}
765}
766
767impl<T: Idx> BitRelations<ChunkedBitSet<T>> for ChunkedBitSet<T> {
768 fn union(&mut self, other: &ChunkedBitSet<T>) -> bool {
769 {
match (&self.domain_size, &other.domain_size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.domain_size, other.domain_size);
770
771 let mut changed = false;
772 for (mut self_chunk, other_chunk) in self.chunks.iter_mut().zip(other.chunks.iter()) {
773 match (&mut self_chunk, &other_chunk) {
774 (_, Zeros { .. }) | (Ones { .. }, _) => {}
775 (Zeros { .. }, _) | (Mixed { .. }, Ones { .. }) => {
776 *self_chunk = other_chunk.clone();
778 changed = true;
779 }
780 (
781 Mixed {
782 chunk_domain_size,
783 ones_count: self_chunk_ones_count,
784 words: self_chunk_words,
785 },
786 Mixed { words: other_chunk_words, .. },
787 ) => {
788 let num_words = num_words(*chunk_domain_size as usize);
794
795 if self_chunk_words[0..num_words] == other_chunk_words[0..num_words] {
799 continue;
800 }
801
802 let op = |a, b| a | b;
805 if !would_modify_words(
806 &self_chunk_words[0..num_words],
807 &other_chunk_words[0..num_words],
808 op,
809 ) {
810 continue;
811 }
812
813 let self_chunk_words = Rc::make_mut(self_chunk_words);
815 let has_changed = update_words(
816 &mut self_chunk_words[0..num_words],
817 &other_chunk_words[0..num_words],
818 op,
819 );
820 if true {
if !has_changed {
::core::panicking::panic("assertion failed: has_changed")
};
};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 {
match (&self.domain_size, &other.domain_size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.domain_size, other.domain_size);
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 if true {
if !(num_words > 0 && num_words <= CHUNK_WORDS) {
::core::panicking::panic("assertion failed: num_words > 0 && num_words <= CHUNK_WORDS")
};
};debug_assert!(num_words > 0 && num_words <= CHUNK_WORDS);
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 if true {
{
match (&self_chunk_ones_count,
&(count_ones(&self_chunk_words[0..num_words]) as ChunkSize)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(
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 = update_words(
893 &mut self_chunk_words[0..num_words],
894 &other_chunk_words[0..num_words],
895 op,
896 );
897 if true {
if !has_changed {
::core::panicking::panic("assertion failed: has_changed")
};
};debug_assert!(has_changed);
898 *self_chunk_ones_count =
899 count_ones(&self_chunk_words[0..num_words]) as ChunkSize;
900 if *self_chunk_ones_count == 0 {
901 *self_chunk = Zeros { chunk_domain_size: *chunk_domain_size };
902 }
903 changed = true;
904 }
905 }
906 }
907 changed
908 }
909
910 fn intersect(&mut self, other: &ChunkedBitSet<T>) -> bool {
911 {
match (&self.domain_size, &other.domain_size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.domain_size, other.domain_size);
912
913 let mut changed = false;
914 for (mut self_chunk, other_chunk) in self.chunks.iter_mut().zip(other.chunks.iter()) {
915 match (&mut self_chunk, &other_chunk) {
916 (Zeros { .. }, _) | (_, Ones { .. }) => {}
917 (Ones { .. }, Zeros { .. } | Mixed { .. }) | (Mixed { .. }, Zeros { .. }) => {
918 changed = true;
919 *self_chunk = other_chunk.clone();
920 }
921 (
922 Mixed {
923 chunk_domain_size,
924 ones_count: self_chunk_ones_count,
925 words: self_chunk_words,
926 },
927 Mixed { words: other_chunk_words, .. },
928 ) => {
929 let num_words = num_words(*chunk_domain_size as usize);
931 let op = |a, b| a & b;
932 if !would_modify_words(
933 &self_chunk_words[0..num_words],
934 &other_chunk_words[0..num_words],
935 op,
936 ) {
937 continue;
938 }
939
940 let self_chunk_words = Rc::make_mut(self_chunk_words);
941 let has_changed = update_words(
942 &mut self_chunk_words[0..num_words],
943 &other_chunk_words[0..num_words],
944 op,
945 );
946 if true {
if !has_changed {
::core::panicking::panic("assertion failed: has_changed")
};
};debug_assert!(has_changed);
947 *self_chunk_ones_count =
948 count_ones(&self_chunk_words[0..num_words]) as ChunkSize;
949 if *self_chunk_ones_count == 0 {
950 *self_chunk = Zeros { chunk_domain_size: *chunk_domain_size };
951 }
952 changed = true;
953 }
954 }
955 }
956
957 changed
958 }
959}
960
961impl<T> Clone for ChunkedBitSet<T> {
962 fn clone(&self) -> Self {
963 ChunkedBitSet {
964 domain_size: self.domain_size,
965 chunks: self.chunks.clone(),
966 marker: PhantomData,
967 }
968 }
969
970 fn clone_from(&mut self, from: &Self) {
975 {
match (&self.domain_size, &from.domain_size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.domain_size, from.domain_size);
976 if true {
{
match (&self.chunks.len(), &from.chunks.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(self.chunks.len(), from.chunks.len());
977
978 self.chunks.clone_from(&from.chunks)
979 }
980}
981
982pub struct ChunkedBitIter<'a, T: Idx> {
983 bit_set: &'a ChunkedBitSet<T>,
984
985 chunk_index: usize,
987
988 chunk_iter: ChunkIter<'a>,
990}
991
992impl<'a, T: Idx> ChunkedBitIter<'a, T> {
993 #[inline]
994 fn new(bit_set: &'a ChunkedBitSet<T>) -> ChunkedBitIter<'a, T> {
995 ChunkedBitIter { bit_set, chunk_index: 0, chunk_iter: bit_set.chunk_iter(0) }
996 }
997}
998
999impl<'a, T: Idx> Iterator for ChunkedBitIter<'a, T> {
1000 type Item = T;
1001
1002 fn next(&mut self) -> Option<T> {
1003 loop {
1004 match &mut self.chunk_iter {
1005 ChunkIter::Zeros => {}
1006 ChunkIter::Ones(iter) => {
1007 if let Some(next) = iter.next() {
1008 return Some(T::new(next + self.chunk_index * CHUNK_BITS));
1009 }
1010 }
1011 ChunkIter::Mixed(iter) => {
1012 if let Some(next) = iter.next() {
1013 return Some(T::new(next + self.chunk_index * CHUNK_BITS));
1014 }
1015 }
1016 ChunkIter::Finished => return None,
1017 }
1018 self.chunk_index += 1;
1019 self.chunk_iter = self.bit_set.chunk_iter(self.chunk_index);
1020 }
1021 }
1022}
1023
1024impl Chunk {
1025 #[cfg(test)]
1026 fn assert_valid(&self) {
1027 match *self {
1028 Zeros { chunk_domain_size } | Ones { chunk_domain_size } => {
1029 assert!(chunk_domain_size as usize <= CHUNK_BITS);
1030 }
1031 Mixed { chunk_domain_size, ones_count, ref words } => {
1032 assert!(chunk_domain_size as usize <= CHUNK_BITS);
1033 assert!(0 < ones_count && ones_count < chunk_domain_size);
1034
1035 assert_eq!(count_ones(words.as_slice()) as ChunkSize, ones_count);
1037
1038 let num_words = num_words(chunk_domain_size as usize);
1040 if num_words < CHUNK_WORDS {
1041 assert_eq!(count_ones(&words[num_words..]) as ChunkSize, 0);
1042 }
1043 }
1044 }
1045 }
1046
1047 fn count(&self) -> usize {
1049 match *self {
1050 Zeros { .. } => 0,
1051 Ones { chunk_domain_size } => chunk_domain_size as usize,
1052 Mixed { ones_count, .. } => usize::from(ones_count),
1053 }
1054 }
1055}
1056
1057enum ChunkIter<'a> {
1058 Zeros,
1059 Ones(Range<usize>),
1060 Mixed(BitIter<'a, usize>),
1061 Finished,
1062}
1063
1064impl<T: Idx> fmt::Debug for ChunkedBitSet<T> {
1065 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
1066 w.debug_list().entries(self.iter()).finish()
1067 }
1068}
1069
1070#[inline]
1083fn update_words<Op>(lhs: &mut [Word], rhs: &[Word], op: Op) -> bool
1084where
1085 Op: Fn(Word, Word) -> Word,
1086{
1087 {
match (&lhs.len(), &rhs.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(lhs.len(), rhs.len());
1088 let mut changed = 0;
1089 for (lhs_slot, &rhs_val) in iter::zip(lhs, rhs) {
1090 let old_val = *lhs_slot;
1091 let new_val = op(old_val, rhs_val);
1092 *lhs_slot = new_val;
1093 changed |= old_val ^ new_val;
1098 }
1099 changed != 0
1100}
1101
1102#[inline]
1105fn would_modify_words<Op>(lhs: &[Word], rhs: &[Word], op: Op) -> bool
1106where
1107 Op: Fn(Word, Word) -> Word,
1108{
1109 {
match (&lhs.len(), &rhs.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(lhs.len(), rhs.len());
1110
1111 const SUBCHUNK_LEN: usize = 64 / size_of::<Word>();
1116 let (lhs_chunks, lhs_tail) = lhs.as_chunks::<SUBCHUNK_LEN>();
1117 let (rhs_chunks, rhs_tail) = rhs.as_chunks::<SUBCHUNK_LEN>();
1118
1119 let would_modify_subchunk = |lhs_chunk: &[Word], rhs_chunk: &[Word]| {
1120 let mut changed = 0;
1121 for (&old_val, &rhs_val) in iter::zip(lhs_chunk, rhs_chunk) {
1122 let new_val = op(old_val, rhs_val);
1123 changed |= old_val ^ new_val;
1126 }
1127 changed != 0
1128 };
1129
1130 for (lhs_chunk, rhs_chunk) in iter::zip(lhs_chunks, rhs_chunks) {
1131 if would_modify_subchunk(lhs_chunk, rhs_chunk) {
1132 return true;
1133 }
1134 }
1135 would_modify_subchunk(lhs_tail, rhs_tail)
1136}
1137
1138#[derive(#[automatically_derived]
impl<T: ::core::cmp::PartialEq> ::core::cmp::PartialEq for MixedBitSet<T> {
#[inline]
fn eq(&self, other: &MixedBitSet<T>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(MixedBitSet::Small(__self_0), MixedBitSet::Small(__arg1_0))
=> __self_0 == __arg1_0,
(MixedBitSet::Large(__self_0), MixedBitSet::Large(__arg1_0))
=> __self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl<T: ::core::cmp::Eq> ::core::cmp::Eq for MixedBitSet<T> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<DenseBitSet<T>>;
let _: ::core::cmp::AssertParamIsEq<ChunkedBitSet<T>>;
}
}Eq)]
1150pub enum MixedBitSet<T> {
1151 Small(DenseBitSet<T>),
1152 Large(ChunkedBitSet<T>),
1153}
1154
1155impl<T> MixedBitSet<T> {
1156 pub fn domain_size(&self) -> usize {
1157 match self {
1158 MixedBitSet::Small(set) => set.domain_size(),
1159 MixedBitSet::Large(set) => set.domain_size(),
1160 }
1161 }
1162}
1163
1164impl<T: Idx> MixedBitSet<T> {
1165 #[inline]
1166 pub fn new_empty(domain_size: usize) -> MixedBitSet<T> {
1167 if domain_size <= CHUNK_BITS {
1168 MixedBitSet::Small(DenseBitSet::new_empty(domain_size))
1169 } else {
1170 MixedBitSet::Large(ChunkedBitSet::new_empty(domain_size))
1171 }
1172 }
1173
1174 #[inline]
1175 pub fn is_empty(&self) -> bool {
1176 match self {
1177 MixedBitSet::Small(set) => set.is_empty(),
1178 MixedBitSet::Large(set) => set.is_empty(),
1179 }
1180 }
1181
1182 #[inline]
1183 pub fn contains(&self, elem: T) -> bool {
1184 match self {
1185 MixedBitSet::Small(set) => set.contains(elem),
1186 MixedBitSet::Large(set) => set.contains(elem),
1187 }
1188 }
1189
1190 #[inline]
1191 pub fn insert(&mut self, elem: T) -> bool {
1192 match self {
1193 MixedBitSet::Small(set) => set.insert(elem),
1194 MixedBitSet::Large(set) => set.insert(elem),
1195 }
1196 }
1197
1198 pub fn insert_all(&mut self) {
1199 match self {
1200 MixedBitSet::Small(set) => set.insert_all(),
1201 MixedBitSet::Large(set) => set.insert_all(),
1202 }
1203 }
1204
1205 #[inline]
1206 pub fn remove(&mut self, elem: T) -> bool {
1207 match self {
1208 MixedBitSet::Small(set) => set.remove(elem),
1209 MixedBitSet::Large(set) => set.remove(elem),
1210 }
1211 }
1212
1213 pub fn iter(&self) -> MixedBitIter<'_, T> {
1214 match self {
1215 MixedBitSet::Small(set) => MixedBitIter::Small(set.iter()),
1216 MixedBitSet::Large(set) => MixedBitIter::Large(set.iter()),
1217 }
1218 }
1219
1220 #[inline]
1221 pub fn clear(&mut self) {
1222 match self {
1223 MixedBitSet::Small(set) => set.clear(),
1224 MixedBitSet::Large(set) => set.clear(),
1225 }
1226 }
1227
1228 pub fn union<Rhs>(&mut self, other: &Rhs) -> bool where
Self: BitRelations<Rhs> {
<Self as BitRelations<Rhs>>::union(self, other)
}
pub fn subtract<Rhs>(&mut self, other: &Rhs) -> bool where
Self: BitRelations<Rhs> {
<Self as BitRelations<Rhs>>::subtract(self, other)
}
pub fn intersect<Rhs>(&mut self, other: &Rhs) -> bool where
Self: BitRelations<Rhs> {
<Self as BitRelations<Rhs>>::intersect(self, other)
}bit_relations_inherent_impls! {}
1229}
1230
1231impl<T> Clone for MixedBitSet<T> {
1232 fn clone(&self) -> Self {
1233 match self {
1234 MixedBitSet::Small(set) => MixedBitSet::Small(set.clone()),
1235 MixedBitSet::Large(set) => MixedBitSet::Large(set.clone()),
1236 }
1237 }
1238
1239 fn clone_from(&mut self, from: &Self) {
1244 match (self, from) {
1245 (MixedBitSet::Small(set), MixedBitSet::Small(from)) => set.clone_from(from),
1246 (MixedBitSet::Large(set), MixedBitSet::Large(from)) => set.clone_from(from),
1247 _ => { ::core::panicking::panic_fmt(format_args!("MixedBitSet size mismatch")); }panic!("MixedBitSet size mismatch"),
1248 }
1249 }
1250}
1251
1252impl<T: Idx> BitRelations<MixedBitSet<T>> for MixedBitSet<T> {
1253 fn union(&mut self, other: &MixedBitSet<T>) -> bool {
1254 match (self, other) {
1255 (MixedBitSet::Small(set), MixedBitSet::Small(other)) => set.union(other),
1256 (MixedBitSet::Large(set), MixedBitSet::Large(other)) => set.union(other),
1257 _ => { ::core::panicking::panic_fmt(format_args!("MixedBitSet size mismatch")); }panic!("MixedBitSet size mismatch"),
1258 }
1259 }
1260
1261 fn subtract(&mut self, other: &MixedBitSet<T>) -> bool {
1262 match (self, other) {
1263 (MixedBitSet::Small(set), MixedBitSet::Small(other)) => set.subtract(other),
1264 (MixedBitSet::Large(set), MixedBitSet::Large(other)) => set.subtract(other),
1265 _ => { ::core::panicking::panic_fmt(format_args!("MixedBitSet size mismatch")); }panic!("MixedBitSet size mismatch"),
1266 }
1267 }
1268
1269 fn intersect(&mut self, _other: &MixedBitSet<T>) -> bool {
1270 {
::core::panicking::panic_fmt(format_args!("not implemented: {0}",
format_args!("implement if/when necessary")));
};unimplemented!("implement if/when necessary");
1271 }
1272}
1273
1274impl<T: Idx> fmt::Debug for MixedBitSet<T> {
1275 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
1276 match self {
1277 MixedBitSet::Small(set) => set.fmt(w),
1278 MixedBitSet::Large(set) => set.fmt(w),
1279 }
1280 }
1281}
1282
1283pub enum MixedBitIter<'a, T: Idx> {
1284 Small(BitIter<'a, T>),
1285 Large(ChunkedBitIter<'a, T>),
1286}
1287
1288impl<'a, T: Idx> Iterator for MixedBitIter<'a, T> {
1289 type Item = T;
1290 fn next(&mut self) -> Option<T> {
1291 match self {
1292 MixedBitIter::Small(iter) => iter.next(),
1293 MixedBitIter::Large(iter) => iter.next(),
1294 }
1295 }
1296}
1297
1298#[derive(#[automatically_derived]
impl<T: ::core::fmt::Debug + Idx> ::core::fmt::Debug for GrowableBitSet<T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"GrowableBitSet", "bit_set", &&self.bit_set)
}
}Debug, #[automatically_derived]
impl<T: ::core::cmp::PartialEq + Idx> ::core::cmp::PartialEq for
GrowableBitSet<T> {
#[inline]
fn eq(&self, other: &GrowableBitSet<T>) -> bool {
self.bit_set == other.bit_set
}
}PartialEq)]
1306pub struct GrowableBitSet<T: Idx> {
1307 bit_set: DenseBitSet<T>,
1308}
1309
1310impl<T: Idx> Clone for GrowableBitSet<T> {
1312 fn clone(&self) -> Self {
1313 Self { bit_set: self.bit_set.clone() }
1314 }
1315
1316 fn clone_from(&mut self, source: &Self) {
1317 self.bit_set.clone_from(&source.bit_set);
1318 }
1319}
1320
1321impl<T: Idx> Default for GrowableBitSet<T> {
1322 fn default() -> Self {
1323 GrowableBitSet::new_empty()
1324 }
1325}
1326
1327impl<T: Idx> GrowableBitSet<T> {
1328 pub fn ensure(&mut self, min_domain_size: usize) {
1330 if self.bit_set.domain_size < min_domain_size {
1331 self.bit_set.domain_size = min_domain_size;
1332 }
1333
1334 let min_num_words = num_words(min_domain_size);
1335 if self.bit_set.words.len() < min_num_words {
1336 self.bit_set.words.resize(min_num_words, 0)
1337 }
1338 }
1339
1340 pub fn new_empty() -> GrowableBitSet<T> {
1341 GrowableBitSet { bit_set: DenseBitSet::new_empty(0) }
1342 }
1343
1344 pub fn with_capacity(capacity: usize) -> GrowableBitSet<T> {
1345 GrowableBitSet { bit_set: DenseBitSet::new_empty(capacity) }
1346 }
1347
1348 #[inline]
1350 pub fn insert(&mut self, elem: T) -> bool {
1351 self.ensure(elem.index() + 1);
1352 self.bit_set.insert(elem)
1353 }
1354
1355 #[inline]
1356 pub fn insert_range(&mut self, elems: Range<T>) {
1357 self.ensure(elems.end.index());
1358 self.bit_set.insert_range(elems);
1359 }
1360
1361 #[inline]
1363 pub fn remove(&mut self, elem: T) -> bool {
1364 self.ensure(elem.index() + 1);
1365 self.bit_set.remove(elem)
1366 }
1367
1368 #[inline]
1369 pub fn clear(&mut self) {
1370 self.bit_set.clear();
1371 }
1372
1373 #[inline]
1374 pub fn count(&self) -> usize {
1375 self.bit_set.count()
1376 }
1377
1378 #[inline]
1379 pub fn is_empty(&self) -> bool {
1380 self.bit_set.is_empty()
1381 }
1382
1383 #[inline]
1384 pub fn contains(&self, elem: T) -> bool {
1385 let (word_index, mask) = word_index_and_mask(elem);
1386 self.bit_set.words.get(word_index).is_some_and(|word| (word & mask) != 0)
1387 }
1388
1389 #[inline]
1390 pub fn contains_any(&self, elems: Range<T>) -> bool {
1391 elems.start.index() < self.bit_set.domain_size
1392 && self
1393 .bit_set
1394 .contains_any(elems.start..T::new(elems.end.index().min(self.bit_set.domain_size)))
1395 }
1396
1397 #[inline]
1398 pub fn iter(&self) -> BitIter<'_, T> {
1399 self.bit_set.iter()
1400 }
1401
1402 #[inline]
1403 pub fn len(&self) -> usize {
1404 self.bit_set.count()
1405 }
1406}
1407
1408impl<T: Idx> From<DenseBitSet<T>> for GrowableBitSet<T> {
1409 fn from(bit_set: DenseBitSet<T>) -> Self {
1410 Self { bit_set }
1411 }
1412}
1413
1414#[cfg_attr(feature = "nightly", derive(const _: () =
{
impl<R: Idx, C: Idx, __D: ::rustc_serialize::Decoder>
::rustc_serialize::Decodable<__D> for BitMatrix<R, C> where
PhantomData<(R, C)>: ::rustc_serialize::Decodable<__D> {
fn decode(__decoder: &mut __D) -> Self {
BitMatrix {
num_rows: ::rustc_serialize::Decodable::decode(__decoder),
num_columns: ::rustc_serialize::Decodable::decode(__decoder),
words: ::rustc_serialize::Decodable::decode(__decoder),
marker: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable_NoContext, const _: () =
{
impl<R: Idx, C: Idx, __E: ::rustc_serialize::Encoder>
::rustc_serialize::Encodable<__E> for BitMatrix<R, C> where
PhantomData<(R, C)>: ::rustc_serialize::Encodable<__E> {
fn encode(&self, __encoder: &mut __E) {
match *self {
BitMatrix {
num_rows: ref __binding_0,
num_columns: ref __binding_1,
words: ref __binding_2,
marker: ref __binding_3 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
}
}
}
}
};Encodable_NoContext))]
1422#[derive(#[automatically_derived]
impl<R: ::core::clone::Clone + Idx, C: ::core::clone::Clone + Idx>
::core::clone::Clone for BitMatrix<R, C> {
#[inline]
fn clone(&self) -> BitMatrix<R, C> {
BitMatrix {
num_rows: ::core::clone::Clone::clone(&self.num_rows),
num_columns: ::core::clone::Clone::clone(&self.num_columns),
words: ::core::clone::Clone::clone(&self.words),
marker: ::core::clone::Clone::clone(&self.marker),
}
}
}Clone, #[automatically_derived]
impl<R: ::core::cmp::Eq + Idx, C: ::core::cmp::Eq + Idx> ::core::cmp::Eq for
BitMatrix<R, C> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
let _: ::core::cmp::AssertParamIsEq<Vec<Word>>;
let _: ::core::cmp::AssertParamIsEq<PhantomData<(R, C)>>;
}
}Eq, #[automatically_derived]
impl<R: ::core::cmp::PartialEq + Idx, C: ::core::cmp::PartialEq + Idx>
::core::cmp::PartialEq for BitMatrix<R, C> {
#[inline]
fn eq(&self, other: &BitMatrix<R, C>) -> bool {
self.num_rows == other.num_rows &&
self.num_columns == other.num_columns &&
self.words == other.words && self.marker == other.marker
}
}PartialEq, #[automatically_derived]
impl<R: ::core::hash::Hash + Idx, C: ::core::hash::Hash + Idx>
::core::hash::Hash for BitMatrix<R, C> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.num_rows, state);
::core::hash::Hash::hash(&self.num_columns, state);
::core::hash::Hash::hash(&self.words, state);
::core::hash::Hash::hash(&self.marker, state)
}
}Hash)]
1423pub struct BitMatrix<R: Idx, C: Idx> {
1424 num_rows: usize,
1425 num_columns: usize,
1426 words: Vec<Word>,
1427 marker: PhantomData<(R, C)>,
1428}
1429
1430impl<R: Idx, C: Idx> BitMatrix<R, C> {
1431 pub fn new(num_rows: usize, num_columns: usize) -> BitMatrix<R, C> {
1433 let words_per_row = num_words(num_columns);
1436 BitMatrix {
1437 num_rows,
1438 num_columns,
1439 words: ::alloc::vec::from_elem(0, num_rows * words_per_row)vec![0; num_rows * words_per_row],
1440 marker: PhantomData,
1441 }
1442 }
1443
1444 pub fn from_row_n(row: &DenseBitSet<C>, num_rows: usize) -> BitMatrix<R, C> {
1446 let num_columns = row.domain_size();
1447 let words_per_row = num_words(num_columns);
1448 {
match (&words_per_row, &row.words.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(words_per_row, row.words.len());
1449 BitMatrix {
1450 num_rows,
1451 num_columns,
1452 words: iter::repeat_n(&row.words, num_rows).flatten().cloned().collect(),
1453 marker: PhantomData,
1454 }
1455 }
1456
1457 pub fn rows(&self) -> impl Iterator<Item = R> {
1458 (0..self.num_rows).map(R::new)
1459 }
1460
1461 fn range(&self, row: R) -> (usize, usize) {
1463 let words_per_row = num_words(self.num_columns);
1464 let start = row.index() * words_per_row;
1465 (start, start + words_per_row)
1466 }
1467
1468 pub fn insert(&mut self, row: R, column: C) -> bool {
1473 if !(row.index() < self.num_rows && column.index() < self.num_columns) {
::core::panicking::panic("assertion failed: row.index() < self.num_rows && column.index() < self.num_columns")
};assert!(row.index() < self.num_rows && column.index() < self.num_columns);
1474 let (start, _) = self.range(row);
1475 let (word_index, mask) = word_index_and_mask(column);
1476 let words = &mut self.words[..];
1477 let word = words[start + word_index];
1478 let new_word = word | mask;
1479 words[start + word_index] = new_word;
1480 word != new_word
1481 }
1482
1483 pub fn contains(&self, row: R, column: C) -> bool {
1488 if !(row.index() < self.num_rows && column.index() < self.num_columns) {
::core::panicking::panic("assertion failed: row.index() < self.num_rows && column.index() < self.num_columns")
};assert!(row.index() < self.num_rows && column.index() < self.num_columns);
1489 let (start, _) = self.range(row);
1490 let (word_index, mask) = word_index_and_mask(column);
1491 (self.words[start + word_index] & mask) != 0
1492 }
1493
1494 pub fn intersect_rows(&self, row1: R, row2: R) -> Vec<C> {
1499 if !(row1.index() < self.num_rows && row2.index() < self.num_rows) {
::core::panicking::panic("assertion failed: row1.index() < self.num_rows && row2.index() < self.num_rows")
};assert!(row1.index() < self.num_rows && row2.index() < self.num_rows);
1500 let (row1_start, row1_end) = self.range(row1);
1501 let (row2_start, row2_end) = self.range(row2);
1502 let mut result = Vec::with_capacity(self.num_columns);
1503 for (base, (i, j)) in (row1_start..row1_end).zip(row2_start..row2_end).enumerate() {
1504 let mut v = self.words[i] & self.words[j];
1505 for bit in 0..WORD_BITS {
1506 if v == 0 {
1507 break;
1508 }
1509 if v & 0x1 != 0 {
1510 result.push(C::new(base * WORD_BITS + bit));
1511 }
1512 v >>= 1;
1513 }
1514 }
1515 result
1516 }
1517
1518 pub fn union_rows(&mut self, read: R, write: R) -> bool {
1526 if !(read.index() < self.num_rows && write.index() < self.num_rows) {
::core::panicking::panic("assertion failed: read.index() < self.num_rows && write.index() < self.num_rows")
};assert!(read.index() < self.num_rows && write.index() < self.num_rows);
1527 let (read_start, read_end) = self.range(read);
1528 let (write_start, write_end) = self.range(write);
1529 let words = &mut self.words[..];
1530 let mut changed = 0;
1531 for (read_index, write_index) in iter::zip(read_start..read_end, write_start..write_end) {
1532 let word = words[write_index];
1533 let new_word = word | words[read_index];
1534 words[write_index] = new_word;
1535 changed |= word ^ new_word;
1537 }
1538 changed != 0
1539 }
1540
1541 pub fn union_row_with(&mut self, with: &DenseBitSet<C>, write: R) -> bool {
1544 if !(write.index() < self.num_rows) {
::core::panicking::panic("assertion failed: write.index() < self.num_rows")
};assert!(write.index() < self.num_rows);
1545 {
match (&with.domain_size(), &self.num_columns) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(with.domain_size(), self.num_columns);
1546 let (write_start, write_end) = self.range(write);
1547 update_words(&mut self.words[write_start..write_end], &with.words, |a, b| a | b)
1548 }
1549
1550 pub fn insert_all_into_row(&mut self, row: R) {
1552 if !(row.index() < self.num_rows) {
::core::panicking::panic("assertion failed: row.index() < self.num_rows")
};assert!(row.index() < self.num_rows);
1553 let (start, end) = self.range(row);
1554 let words = &mut self.words[..];
1555 for index in start..end {
1556 words[index] = !0;
1557 }
1558 clear_excess_bits_in_final_word(self.num_columns, &mut self.words[..end]);
1559 }
1560
1561 pub fn words(&self) -> &[Word] {
1563 &self.words
1564 }
1565
1566 pub fn iter(&self, row: R) -> BitIter<'_, C> {
1569 if !(row.index() < self.num_rows) {
::core::panicking::panic("assertion failed: row.index() < self.num_rows")
};assert!(row.index() < self.num_rows);
1570 let (start, end) = self.range(row);
1571 BitIter::new(&self.words[start..end])
1572 }
1573
1574 pub fn count(&self, row: R) -> usize {
1576 let (start, end) = self.range(row);
1577 count_ones(&self.words[start..end])
1578 }
1579}
1580
1581impl<R: Idx, C: Idx> fmt::Debug for BitMatrix<R, C> {
1582 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1583 struct OneLinePrinter<T>(T);
1585 impl<T: fmt::Debug> fmt::Debug for OneLinePrinter<T> {
1586 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1587 fmt.write_fmt(format_args!("{0:?}", self.0))write!(fmt, "{:?}", self.0)
1588 }
1589 }
1590
1591 fmt.write_fmt(format_args!("BitMatrix({0}x{1}) ", self.num_rows,
self.num_columns))write!(fmt, "BitMatrix({}x{}) ", self.num_rows, self.num_columns)?;
1592 let items = self.rows().flat_map(|r| self.iter(r).map(move |c| (r, c)));
1593 fmt.debug_set().entries(items.map(OneLinePrinter)).finish()
1594 }
1595}
1596
1597#[derive(#[automatically_derived]
impl<R: ::core::clone::Clone, C: ::core::clone::Clone> ::core::clone::Clone
for SparseBitMatrix<R, C> where R: Idx, C: Idx {
#[inline]
fn clone(&self) -> SparseBitMatrix<R, C> {
SparseBitMatrix {
num_columns: ::core::clone::Clone::clone(&self.num_columns),
rows: ::core::clone::Clone::clone(&self.rows),
}
}
}Clone, #[automatically_derived]
impl<R: ::core::fmt::Debug, C: ::core::fmt::Debug> ::core::fmt::Debug for
SparseBitMatrix<R, C> where R: Idx, C: Idx {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"SparseBitMatrix", "num_columns", &self.num_columns, "rows",
&&self.rows)
}
}Debug)]
1609pub struct SparseBitMatrix<R, C>
1610where
1611 R: Idx,
1612 C: Idx,
1613{
1614 num_columns: usize,
1615 rows: IndexVec<R, Option<DenseBitSet<C>>>,
1616}
1617
1618impl<R: Idx, C: Idx> SparseBitMatrix<R, C> {
1619 pub fn new(num_columns: usize) -> Self {
1621 Self { num_columns, rows: IndexVec::new() }
1622 }
1623
1624 fn ensure_row(&mut self, row: R) -> &mut DenseBitSet<C> {
1625 self.rows.get_or_insert_with(row, || DenseBitSet::new_empty(self.num_columns))
1628 }
1629
1630 pub fn insert(&mut self, row: R, column: C) -> bool {
1635 self.ensure_row(row).insert(column)
1636 }
1637
1638 pub fn remove(&mut self, row: R, column: C) -> bool {
1644 match self.rows.get_mut(row) {
1645 Some(Some(row)) => row.remove(column),
1646 _ => false,
1647 }
1648 }
1649
1650 pub fn clear(&mut self, row: R) {
1653 if let Some(Some(row)) = self.rows.get_mut(row) {
1654 row.clear();
1655 }
1656 }
1657
1658 pub fn contains(&self, row: R, column: C) -> bool {
1663 self.row(row).is_some_and(|r| r.contains(column))
1664 }
1665
1666 pub fn union_rows(&mut self, read: R, write: R) -> bool {
1674 if read == write || self.row(read).is_none() {
1675 return false;
1676 }
1677
1678 self.ensure_row(write);
1679 if let (Some(read_row), Some(write_row)) = self.rows.pick2_mut(read, write) {
1680 write_row.union(read_row)
1681 } else {
1682 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1683 }
1684 }
1685
1686 pub fn insert_all_into_row(&mut self, row: R) {
1688 self.ensure_row(row).insert_all();
1689 }
1690
1691 pub fn rows(&self) -> impl Iterator<Item = R> {
1692 self.rows.indices()
1693 }
1694
1695 pub fn iter(&self, row: R) -> impl Iterator<Item = C> {
1698 self.row(row).into_iter().flat_map(|r| r.iter())
1699 }
1700
1701 pub fn row(&self, row: R) -> Option<&DenseBitSet<C>> {
1702 self.rows.get(row)?.as_ref()
1703 }
1704
1705 pub fn intersect_row<Set>(&mut self, row: R, set: &Set) -> bool
1710 where
1711 DenseBitSet<C>: BitRelations<Set>,
1712 {
1713 match self.rows.get_mut(row) {
1714 Some(Some(row)) => row.intersect(set),
1715 _ => false,
1716 }
1717 }
1718
1719 pub fn subtract_row<Set>(&mut self, row: R, set: &Set) -> bool
1724 where
1725 DenseBitSet<C>: BitRelations<Set>,
1726 {
1727 match self.rows.get_mut(row) {
1728 Some(Some(row)) => row.subtract(set),
1729 _ => false,
1730 }
1731 }
1732
1733 pub fn union_row<Set>(&mut self, row: R, set: &Set) -> bool
1738 where
1739 DenseBitSet<C>: BitRelations<Set>,
1740 {
1741 self.ensure_row(row).union(set)
1742 }
1743}
1744
1745#[inline]
1746fn num_words<T: Idx>(domain_size: T) -> usize {
1747 domain_size.index().div_ceil(WORD_BITS)
1748}
1749
1750#[inline]
1751fn word_index_and_mask<T: Idx>(elem: T) -> (usize, Word) {
1752 let elem = elem.index();
1753 let word_index = elem / WORD_BITS;
1754 let mask = 1 << (elem % WORD_BITS);
1755 (word_index, mask)
1756}
1757
1758#[inline]
1759fn chunk_index<T: Idx>(elem: T) -> usize {
1760 elem.index() / CHUNK_BITS
1761}
1762
1763#[inline]
1764fn chunk_word_index_and_mask<T: Idx>(elem: T) -> (usize, Word) {
1765 let chunk_elem = elem.index() % CHUNK_BITS;
1766 word_index_and_mask(chunk_elem)
1767}
1768
1769fn clear_excess_bits_in_final_word(domain_size: usize, words: &mut [Word]) {
1770 let num_bits_in_final_word = domain_size % WORD_BITS;
1771 if num_bits_in_final_word > 0 {
1772 let mask = (1 << num_bits_in_final_word) - 1;
1773 words[words.len() - 1] &= mask;
1774 }
1775}
1776
1777#[inline]
1778fn max_bit(word: Word) -> usize {
1779 WORD_BITS - 1 - word.leading_zeros() as usize
1780}
1781
1782#[inline]
1783fn count_ones(words: &[Word]) -> usize {
1784 words.iter().map(|word| word.count_ones() as usize).sum()
1785}