bit_set/set.rs
1use crate::{local_prelude::*, util};
2
3#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
4#[cfg_attr(
5 feature = "borsh",
6 derive(borsh::BorshDeserialize, borsh::BorshSerialize)
7)]
8#[cfg_attr(
9 feature = "miniserde",
10 derive(miniserde::Deserialize, miniserde::Serialize)
11)]
12pub struct BitSet<B: BitBlock = u32> {
13 pub(crate) bit_vec: BitVec<B>,
14}
15
16impl<B: BitBlock> Clone for BitSet<B> {
17 fn clone(&self) -> Self {
18 BitSet {
19 bit_vec: self.bit_vec.clone(),
20 }
21 }
22
23 fn clone_from(&mut self, other: &Self) {
24 self.bit_vec.clone_from(&other.bit_vec);
25 }
26}
27
28impl<B: BitBlock> Default for BitSet<B> {
29 #[inline]
30 fn default() -> Self {
31 BitSet {
32 bit_vec: Default::default(),
33 }
34 }
35}
36
37impl<B: BitBlock> FromIterator<usize> for BitSet<B> {
38 fn from_iter<I: IntoIterator<Item = usize>>(iter: I) -> Self {
39 let mut ret = Self::default();
40 ret.extend(iter);
41 ret
42 }
43}
44
45impl<B: BitBlock> Extend<usize> for BitSet<B> {
46 #[inline]
47 fn extend<I: IntoIterator<Item = usize>>(&mut self, iter: I) {
48 for i in iter {
49 self.insert(i);
50 }
51 }
52}
53
54impl<B: BitBlock> PartialOrd for BitSet<B> {
55 #[inline]
56 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
57 Some(self.cmp(other))
58 }
59}
60
61impl<B: BitBlock> Ord for BitSet<B> {
62 #[inline]
63 fn cmp(&self, other: &Self) -> Ordering {
64 self.iter().cmp(other)
65 }
66}
67
68impl<B: BitBlock> PartialEq for BitSet<B> {
69 #[inline]
70 fn eq(&self, other: &Self) -> bool {
71 self.iter().eq(other)
72 }
73}
74
75impl<B: BitBlock> Eq for BitSet<B> {}
76
77impl BitSet<u32> {
78 /// Creates a new empty `BitSet`.
79 ///
80 /// # Examples
81 ///
82 /// ```
83 /// use bit_set::BitSet;
84 ///
85 /// let mut s = BitSet::new();
86 /// ```
87 #[inline]
88 pub fn new() -> Self {
89 Self::default()
90 }
91
92 /// Creates a new `BitSet` with initially no contents, able to
93 /// hold `nbits` elements without resizing.
94 ///
95 /// # Examples
96 ///
97 /// ```
98 /// use bit_set::BitSet;
99 ///
100 /// let mut s = BitSet::with_capacity(100);
101 /// assert!(s.capacity() >= 100);
102 /// ```
103 #[inline]
104 pub fn with_capacity(nbits: usize) -> Self {
105 let bit_vec = BitVec::from_elem(nbits, false);
106 Self::from_bit_vec(bit_vec)
107 }
108
109 /// Creates a new `BitSet` from the given bit vector.
110 ///
111 /// # Examples
112 ///
113 /// ```
114 /// use bit_vec::BitVec;
115 /// use bit_set::BitSet;
116 ///
117 /// let bv = BitVec::from_bytes(&[0b01100000]);
118 /// let s = BitSet::from_bit_vec(bv);
119 ///
120 /// // Print 1, 2 in arbitrary order
121 /// for x in s.iter() {
122 /// println!("{}", x);
123 /// }
124 /// ```
125 #[inline]
126 pub fn from_bit_vec(bit_vec: BitVec) -> Self {
127 BitSet { bit_vec }
128 }
129
130 pub fn from_bytes(bytes: &[u8]) -> Self {
131 BitSet {
132 bit_vec: BitVec::from_bytes(bytes),
133 }
134 }
135}
136
137#[allow(clippy::multiple_inherent_impl)]
138impl<B: BitBlock> BitSet<B> {
139 /// Creates a new empty `BitSet`.
140 ///
141 /// # Examples
142 ///
143 /// ```
144 /// use bit_set::BitSet;
145 ///
146 /// let mut s = <BitSet>::new_general();
147 /// ```
148 #[inline]
149 pub fn new_general() -> Self {
150 Self::default()
151 }
152
153 /// Creates a new `BitSet` with initially no contents, able to
154 /// hold `nbits` elements without resizing.
155 ///
156 /// # Examples
157 ///
158 /// ```
159 /// use bit_set::BitSet;
160 ///
161 /// let mut s = <BitSet>::with_capacity_general(100);
162 /// assert!(s.capacity() >= 100);
163 /// ```
164 #[inline]
165 pub fn with_capacity_general(nbits: usize) -> Self {
166 let bit_vec = BitVec::from_elem_general(nbits, false);
167 Self::from_bit_vec_general(bit_vec)
168 }
169
170 /// Creates a new `BitSet` from the given bit vector.
171 ///
172 /// # Examples
173 ///
174 /// ```
175 /// use bit_vec::BitVec;
176 /// use bit_set::BitSet;
177 ///
178 /// let bv: BitVec<u64> = BitVec::from_bytes_general(&[0b01100000]);
179 /// let s = BitSet::from_bit_vec_general(bv);
180 ///
181 /// // Print 1, 2 in arbitrary order
182 /// for x in s.iter() {
183 /// println!("{}", x);
184 /// }
185 /// ```
186 #[inline]
187 pub fn from_bit_vec_general(bit_vec: BitVec<B>) -> Self {
188 BitSet { bit_vec }
189 }
190
191 pub fn from_bytes_general(bytes: &[u8]) -> Self {
192 BitSet {
193 bit_vec: BitVec::from_bytes_general(bytes),
194 }
195 }
196
197 /// Returns the capacity in bits for this bit vector. Inserting any
198 /// element less than this amount will not trigger a resizing.
199 ///
200 /// # Examples
201 ///
202 /// ```
203 /// use bit_set::BitSet;
204 ///
205 /// let mut s = BitSet::with_capacity(100);
206 /// assert!(s.capacity() >= 100);
207 /// ```
208 #[inline]
209 pub fn capacity(&self) -> usize {
210 self.bit_vec.capacity()
211 }
212
213 /// Reserves capacity for the given `BitSet` to contain `len` distinct elements. In the case
214 /// of `BitSet` this means reallocations will not occur as long as all inserted elements
215 /// are less than `len`.
216 ///
217 /// The collection may reserve more space to avoid frequent reallocations.
218 ///
219 ///
220 /// # Examples
221 ///
222 /// ```
223 /// use bit_set::BitSet;
224 ///
225 /// let mut s = BitSet::new();
226 /// s.reserve_len(10);
227 /// assert!(s.capacity() >= 10);
228 /// ```
229 pub fn reserve_len(&mut self, len: usize) {
230 let cur_len = self.bit_vec.len();
231 if len >= cur_len {
232 self.bit_vec.reserve(len - cur_len);
233 }
234 }
235
236 /// Reserves the minimum capacity for the given `BitSet` to contain `len` distinct elements.
237 /// In the case of `BitSet` this means reallocations will not occur as long as all inserted
238 /// elements are less than `len`.
239 ///
240 /// Note that the allocator may give the collection more space than it requests. Therefore
241 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve_len` if future
242 /// insertions are expected.
243 ///
244 ///
245 /// # Examples
246 ///
247 /// ```
248 /// use bit_set::BitSet;
249 ///
250 /// let mut s = BitSet::new();
251 /// s.reserve_len_exact(10);
252 /// assert!(s.capacity() >= 10);
253 /// ```
254 pub fn reserve_len_exact(&mut self, len: usize) {
255 let cur_len = self.bit_vec.len();
256 if len >= cur_len {
257 self.bit_vec.reserve_exact(len - cur_len);
258 }
259 }
260
261 /// Consumes this set to return the underlying bit vector.
262 ///
263 /// # Examples
264 ///
265 /// ```
266 /// use bit_set::BitSet;
267 ///
268 /// let mut s = BitSet::new();
269 /// s.insert(0);
270 /// s.insert(3);
271 ///
272 /// let bv = s.into_bit_vec();
273 /// assert!(bv[0]);
274 /// assert!(bv[3]);
275 /// ```
276 #[inline]
277 pub fn into_bit_vec(self) -> BitVec<B> {
278 self.bit_vec
279 }
280
281 /// Returns a reference to the underlying bit vector.
282 ///
283 /// # Examples
284 ///
285 /// ```
286 /// use bit_set::BitSet;
287 ///
288 /// let mut set = BitSet::new();
289 /// set.insert(0);
290 ///
291 /// let bv = set.get_ref();
292 /// assert_eq!(bv[0], true);
293 /// ```
294 #[inline]
295 pub fn get_ref(&self) -> &BitVec<B> {
296 &self.bit_vec
297 }
298
299 /// Returns a mutable reference to the underlying bit vector.
300 ///
301 /// # Examples
302 ///
303 /// ```
304 /// use bit_set::BitSet;
305 ///
306 /// let mut set = BitSet::new();
307 /// set.insert(0);
308 /// set.insert(3);
309 ///
310 /// {
311 /// let bv = set.get_mut();
312 /// bv.set(1, true);
313 /// }
314 ///
315 /// assert!(set.contains(0));
316 /// assert!(set.contains(1));
317 /// assert!(set.contains(3));
318 /// ```
319 #[inline]
320 pub fn get_mut(&mut self) -> &mut BitVec<B> {
321 &mut self.bit_vec
322 }
323
324 /// # Safety
325 ///
326 /// Safe and upholds invariant if function `f` does not alter most
327 /// significant bits of the first argument where respective bits
328 /// in the second argument are equal 0.
329 ///
330 /// In other words, this is safe if `f` is XOR, OR, AND, but violates
331 /// invariant if it is XNOR, NAND.
332 ///
333 /// See the safety section below.
334 #[inline]
335 fn other_op<F>(&mut self, other: &Self, mut f: F)
336 where
337 F: FnMut(B, B) -> B,
338 {
339 // Unwrap BitVecs
340 let self_bit_vec = &mut self.bit_vec;
341 let other_bit_vec = &other.bit_vec;
342
343 let self_len = self_bit_vec.len();
344 let other_len = other_bit_vec.len();
345
346 // Expand the vector if necessary
347 if self_len < other_len {
348 self_bit_vec.grow(other_len - self_len, false);
349 }
350
351 // virtually pad other with 0's for equal lengths
352 let other_words = util::match_words(self_bit_vec, other_bit_vec).1;
353
354 debug_assert!(self_bit_vec.len() >= other_bit_vec.len());
355
356 // Apply values found in other
357 for (i, w) in other_words {
358 let old = self_bit_vec.storage()[i];
359 let new = f(old, w);
360 // Safety:
361 // We do not change the underlying Vec's size, so this is always ok.
362 // - What do we do to uphold the invariant for trailing bits?
363 // - We have a debug assert below that guards us against polluting
364 // trailing bits.
365 unsafe {
366 self_bit_vec.storage_mut()[i] = new;
367 }
368 if i == self_bit_vec.storage().len() - 1 && self_bit_vec.len() % B::bits() > 0 {
369 debug_assert!(new >> (self_bit_vec.len() % B::bits()) == B::zero());
370 }
371 }
372 }
373
374 /// Truncates the underlying vector to the least length required.
375 ///
376 /// # Examples
377 ///
378 /// ```
379 /// use bit_set::BitSet;
380 ///
381 /// let mut s = BitSet::new();
382 /// s.insert(3231);
383 /// s.remove(3231);
384 ///
385 /// // Internal storage will probably be bigger than necessary
386 /// println!("old capacity: {}", s.capacity());
387 /// assert!(s.capacity() >= 3231);
388 ///
389 /// // Now should be smaller
390 /// s.shrink_to_fit();
391 /// println!("new capacity: {}", s.capacity());
392 /// ```
393 #[inline]
394 pub fn shrink_to_fit(&mut self) {
395 let bit_vec = &mut self.bit_vec;
396 // Obtain original length
397 let old_len = bit_vec.storage().len();
398 // Obtain coarse trailing zero length
399 let n = bit_vec
400 .storage()
401 .iter()
402 .rev()
403 .take_while(|&&n| n == B::zero())
404 .count();
405 // Truncate away all empty trailing blocks, then shrink_to_fit
406 let trunc_len = old_len - n;
407 // Safety:
408 // Those function calls may seem unsafe, but they are guaranteed
409 // not to introduce any memory unsafety.
410 // We set the correct length as a multiple of `B::bits()`,
411 // thus maintaining the trailing bit invariant.
412 unsafe {
413 bit_vec.storage_mut().truncate(trunc_len);
414 bit_vec.set_len(trunc_len * B::bits());
415 }
416 bit_vec.shrink_to_fit();
417 }
418
419 /// Unions in-place with the specified other bit vector.
420 ///
421 /// # Examples
422 ///
423 /// ```
424 /// use bit_set::BitSet;
425 ///
426 /// let a = 0b01101000;
427 /// let b = 0b10100000;
428 /// let res = 0b11101000;
429 ///
430 /// let mut a = BitSet::from_bytes(&[a]);
431 /// let b = BitSet::from_bytes(&[b]);
432 /// let res = BitSet::from_bytes(&[res]);
433 ///
434 /// a.union_with(&b);
435 /// assert_eq!(a, res);
436 /// ```
437 #[inline]
438 pub fn union_with(&mut self, other: &Self) {
439 self.other_op(other, |w1, w2| w1 | w2);
440 }
441
442 /// Intersects in-place with the specified other bit vector.
443 ///
444 /// # Examples
445 ///
446 /// ```
447 /// use bit_set::BitSet;
448 ///
449 /// let a = 0b01101000;
450 /// let b = 0b10100000;
451 /// let res = 0b00100000;
452 ///
453 /// let mut a = BitSet::from_bytes(&[a]);
454 /// let b = BitSet::from_bytes(&[b]);
455 /// let res = BitSet::from_bytes(&[res]);
456 ///
457 /// a.intersect_with(&b);
458 /// assert_eq!(a, res);
459 /// ```
460 #[inline]
461 pub fn intersect_with(&mut self, other: &Self) {
462 self.other_op(other, |w1, w2| w1 & w2);
463 }
464
465 /// Makes this bit vector the difference with the specified other bit vector
466 /// in-place.
467 ///
468 /// # Examples
469 ///
470 /// ```
471 /// use bit_set::BitSet;
472 ///
473 /// let a = 0b01101000;
474 /// let b = 0b10100000;
475 /// let a_b = 0b01001000; // a - b
476 /// let b_a = 0b10000000; // b - a
477 ///
478 /// let mut bva = BitSet::from_bytes(&[a]);
479 /// let bvb = BitSet::from_bytes(&[b]);
480 /// let bva_b = BitSet::from_bytes(&[a_b]);
481 /// let bvb_a = BitSet::from_bytes(&[b_a]);
482 ///
483 /// bva.difference_with(&bvb);
484 /// assert_eq!(bva, bva_b);
485 ///
486 /// let bva = BitSet::from_bytes(&[a]);
487 /// let mut bvb = BitSet::from_bytes(&[b]);
488 ///
489 /// bvb.difference_with(&bva);
490 /// assert_eq!(bvb, bvb_a);
491 /// ```
492 #[inline]
493 pub fn difference_with(&mut self, other: &Self) {
494 self.other_op(other, |w1, w2| w1 & !w2);
495 }
496
497 /// Makes this bit vector the symmetric difference with the specified other
498 /// bit vector in-place.
499 ///
500 /// # Examples
501 ///
502 /// ```
503 /// use bit_set::BitSet;
504 ///
505 /// let a = 0b01101000;
506 /// let b = 0b10100000;
507 /// let res = 0b11001000;
508 ///
509 /// let mut a = BitSet::from_bytes(&[a]);
510 /// let b = BitSet::from_bytes(&[b]);
511 /// let res = BitSet::from_bytes(&[res]);
512 ///
513 /// a.symmetric_difference_with(&b);
514 /// assert_eq!(a, res);
515 /// ```
516 #[inline]
517 pub fn symmetric_difference_with(&mut self, other: &Self) {
518 self.other_op(other, |w1, w2| w1 ^ w2);
519 }
520
521 /*
522 /// Moves all elements from `other` into `Self`, leaving `other` empty.
523 ///
524 /// # Examples
525 ///
526 /// ```
527 /// use bit_set::BitSet;
528 ///
529 /// let mut a = BitSet::new();
530 /// a.insert(2);
531 /// a.insert(6);
532 ///
533 /// let mut b = BitSet::new();
534 /// b.insert(1);
535 /// b.insert(3);
536 /// b.insert(6);
537 ///
538 /// a.append(&mut b);
539 ///
540 /// assert_eq!(a.len(), 4);
541 /// assert_eq!(b.len(), 0);
542 /// assert_eq!(a, BitSet::from_bytes(&[0b01110010]));
543 /// ```
544 pub fn append(&mut self, other: &mut Self) {
545 self.union_with(other);
546 other.clear();
547 }
548
549 /// Splits the `BitSet` into two at the given key including the key.
550 /// Retains the first part in-place while returning the second part.
551 ///
552 /// # Examples
553 ///
554 /// ```
555 /// use bit_set::BitSet;
556 ///
557 /// let mut a = BitSet::new();
558 /// a.insert(2);
559 /// a.insert(6);
560 /// a.insert(1);
561 /// a.insert(3);
562 ///
563 /// let b = a.split_off(3);
564 ///
565 /// assert_eq!(a.len(), 2);
566 /// assert_eq!(b.len(), 2);
567 /// assert_eq!(a, BitSet::from_bytes(&[0b01100000]));
568 /// assert_eq!(b, BitSet::from_bytes(&[0b00010010]));
569 /// ```
570 pub fn split_off(&mut self, at: usize) -> Self {
571 let mut other = BitSet::new();
572
573 if at == 0 {
574 swap(self, &mut other);
575 return other;
576 } else if at >= self.bit_vec.len() {
577 return other;
578 }
579
580 // Calculate block and bit at which to split
581 let w = at / BITS;
582 let b = at % BITS;
583
584 // Pad `other` with `w` zero blocks,
585 // append `self`'s blocks in the range from `w` to the end to `other`
586 other.bit_vec.storage_mut().extend(repeat(0u32).take(w)
587 .chain(self.bit_vec.storage()[w..].iter().cloned()));
588 other.bit_vec.nbits = self.bit_vec.nbits;
589
590 if b > 0 {
591 other.bit_vec.storage_mut()[w] &= !0 << b;
592 }
593
594 // Sets `bit_vec.len()` and fixes the last block as well
595 self.bit_vec.truncate(at);
596
597 other
598 }
599 */
600
601 /// Counts the number of set bits in this set.
602 ///
603 /// Note that this function scans the set to calculate the number.
604 #[inline]
605 pub fn count(&self) -> usize {
606 self.bit_vec.blocks().fold(0, |acc, n| acc + n.count_ones())
607 }
608
609 /// Counts the number of set bits in this set.
610 ///
611 /// Note that this function scans the set to calculate the number.
612 #[inline]
613 #[deprecated = "use BitVec::count() instead"]
614 pub fn len(&self) -> usize {
615 self.count()
616 }
617
618 /// Returns whether there are no bits set in this set
619 #[inline]
620 pub fn is_empty(&self) -> bool {
621 self.bit_vec.none()
622 }
623
624 /// Removes all elements of this set.
625 ///
626 /// Different from [`reset`] only in that the capacity is preserved.
627 ///
628 /// [`reset`]: Self::reset
629 #[inline]
630 pub fn make_empty(&mut self) {
631 self.bit_vec.fill(false);
632 }
633
634 /// Resets this set to an empty state.
635 ///
636 /// Different from [`make_empty`] only in that the capacity may NOT be preserved.
637 ///
638 /// [`make_empty`]: Self::make_empty
639 #[inline]
640 pub fn reset(&mut self) {
641 self.bit_vec.remove_all();
642 }
643
644 /// Clears all bits in this set
645 #[deprecated(since = "0.9.0", note = "please use `fn make_empty` instead")]
646 #[inline]
647 pub fn clear(&mut self) {
648 self.make_empty();
649 }
650
651 /// Returns `true` if this set contains the specified integer.
652 #[inline]
653 pub fn contains(&self, value: usize) -> bool {
654 let bit_vec = &self.bit_vec;
655 value < bit_vec.len() && bit_vec[value]
656 }
657
658 /// Returns `true` if the set has no elements in common with `other`.
659 /// This is equivalent to checking for an empty intersection.
660 #[inline]
661 pub fn is_disjoint(&self, other: &Self) -> bool {
662 self.intersection(other).next().is_none()
663 }
664
665 /// Returns `true` if the set is a subset of another.
666 #[inline]
667 pub fn is_subset(&self, other: &Self) -> bool {
668 let self_bit_vec = &self.bit_vec;
669 let other_bit_vec = &other.bit_vec;
670 let other_blocks = util::blocks_for_bits::<B>(other_bit_vec.len());
671
672 // Check that `self` intersect `other` is self
673 self_bit_vec.blocks().zip(other_bit_vec.blocks()).all(|(w1, w2)| w1 & w2 == w1) &&
674 // Make sure if `self` has any more blocks than `other`, they're all 0
675 self_bit_vec.blocks().skip(other_blocks).all(|w| w == B::zero())
676 }
677
678 /// Returns `true` if the set is a superset of another.
679 #[inline]
680 pub fn is_superset(&self, other: &Self) -> bool {
681 other.is_subset(self)
682 }
683
684 /// Adds a value to the set. Returns `true` if the value was not already
685 /// present in the set.
686 pub fn insert(&mut self, value: usize) -> bool {
687 if self.contains(value) {
688 return false;
689 }
690
691 // Ensure we have enough space to hold the new element
692 let len = self.bit_vec.len();
693 if value >= len {
694 self.bit_vec.grow(value - len + 1, false);
695 }
696
697 self.bit_vec.set(value, true);
698 true
699 }
700
701 /// Removes a value from the set. Returns `true` if the value was
702 /// present in the set.
703 pub fn remove(&mut self, value: usize) -> bool {
704 if !self.contains(value) {
705 return false;
706 }
707
708 self.bit_vec.set(value, false);
709
710 true
711 }
712
713 /// Excludes `element` and all greater elements from the `BitSet`.
714 pub fn truncate(&mut self, element: usize) {
715 self.bit_vec.truncate(element);
716 }
717}
718
719impl<B: BitBlock> fmt::Debug for BitSet<B> {
720 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
721 fmt.debug_struct("BitSet")
722 .field("bit_vec", &self.bit_vec)
723 .finish()
724 }
725}
726
727impl<B: BitBlock> fmt::Display for BitSet<B> {
728 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
729 fmt.debug_set().entries(self).finish()
730 }
731}
732
733impl<B: BitBlock> hash::Hash for BitSet<B> {
734 fn hash<H: hash::Hasher>(&self, state: &mut H) {
735 for pos in self {
736 pos.hash(state);
737 }
738 }
739}