1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! An implementation of a set using a bit vector as an underlying
12 //! representation for holding unsigned numerical elements.
14 //! It should also be noted that the amount of storage necessary for holding a
15 //! set of objects is proportional to the maximum of the objects when viewed
21 //! use bit_set::BitSet;
23 //! // It's a regular set
24 //! let mut s = BitSet::new();
31 //! if !s.contains(7) {
32 //! println!("There is no 7");
35 //! // Can initialize from a `BitVec`
36 //! let other = BitSet::from_bytes(&[0b11010000]);
38 //! s.union_with(&other);
40 //! // Print 0, 1, 3 in some order
41 //! for x in s.iter() {
42 //! println!("{}", x);
45 //! // Can convert back to a `BitVec`
46 //! let bv = s.into_bit_vec();
51 #![cfg_attr(all(test, feature = "nightly"), feature(test))]
53 #[cfg(all(test, feature = "nightly"))]
55 #[cfg(feature = "serde")]
57 #[cfg(all(test, feature = "nightly"))]
64 use bit_vec::{BitBlock, BitVec, Blocks};
66 use core::cmp::Ordering;
69 use core::iter::{self, Chain, Enumerate, FromIterator, Repeat, Skip, Take};
71 #[cfg(feature = "serde")]
72 use serde2::{Deserialize, Deserializer, Serialize, Serializer};
74 type MatchWords<'a, B> = Chain<Enumerate<Blocks<'a, B>>, Skip<Take<Enumerate<Repeat<B>>>>>;
76 /// Computes how many blocks are needed to store that many bits
77 fn blocks_for_bits<B: BitBlock>(bits: usize) -> usize {
78 // If we want 17 bits, dividing by 32 will produce 0. So we add 1 to make sure we
79 // reserve enough. But if we want exactly a multiple of 32, this will actually allocate
80 // one too many. So we need to check if that's the case. We can do that by computing if
81 // bitwise AND by `32 - 1` is 0. But LLVM should be able to optimize the semantically
82 // superior modulo operator on a power of two to this.
84 // Note that we can technically avoid this branch with the expression
85 // `(nbits + BITS - 1) / 32::BITS`, but if nbits is almost usize::MAX this will overflow.
86 if bits % B::bits() == 0 {
93 // Take two BitVec's, and return iterators of their words, where the shorter one
94 // has been padded with 0's
95 fn match_words<'a, 'b, B: BitBlock>(
98 ) -> (MatchWords<'a, B>, MatchWords<'b, B>) {
99 let a_len = a.storage().len();
100 let b_len = b.storage().len();
102 // have to uselessly pretend to pad the longer one for type matching
107 .chain(iter::repeat(B::zero()).enumerate().take(b_len).skip(a_len)),
110 .chain(iter::repeat(B::zero()).enumerate().take(0).skip(0)),
116 .chain(iter::repeat(B::zero()).enumerate().take(0).skip(0)),
119 .chain(iter::repeat(B::zero()).enumerate().take(a_len).skip(b_len)),
124 pub struct BitSet<B = u32> {
128 impl<B: BitBlock> Clone for BitSet<B> {
129 fn clone(&self) -> Self {
131 bit_vec: self.bit_vec.clone(),
135 fn clone_from(&mut self, other: &Self) {
136 self.bit_vec.clone_from(&other.bit_vec);
140 impl<B: BitBlock> Default for BitSet<B> {
142 fn default() -> Self {
144 bit_vec: Default::default(),
149 impl<B: BitBlock> FromIterator<usize> for BitSet<B> {
150 fn from_iter<I: IntoIterator<Item = usize>>(iter: I) -> Self {
151 let mut ret = Self::default();
157 impl<B: BitBlock> Extend<usize> for BitSet<B> {
159 fn extend<I: IntoIterator<Item = usize>>(&mut self, iter: I) {
166 impl<B: BitBlock> PartialOrd for BitSet<B> {
168 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
169 self.iter().partial_cmp(other)
173 impl<B: BitBlock> Ord for BitSet<B> {
175 fn cmp(&self, other: &Self) -> Ordering {
176 self.iter().cmp(other)
180 impl<B: BitBlock> PartialEq for BitSet<B> {
182 fn eq(&self, other: &Self) -> bool {
183 self.iter().eq(other)
187 impl<B: BitBlock> Eq for BitSet<B> {}
190 /// Creates a new empty `BitSet`.
195 /// use bit_set::BitSet;
197 /// let mut s = BitSet::new();
200 pub fn new() -> Self {
204 /// Creates a new `BitSet` with initially no contents, able to
205 /// hold `nbits` elements without resizing.
210 /// use bit_set::BitSet;
212 /// let mut s = BitSet::with_capacity(100);
213 /// assert!(s.capacity() >= 100);
216 pub fn with_capacity(nbits: usize) -> Self {
217 let bit_vec = BitVec::from_elem(nbits, false);
218 Self::from_bit_vec(bit_vec)
221 /// Creates a new `BitSet` from the given bit vector.
226 /// extern crate bit_vec;
227 /// extern crate bit_set;
230 /// use bit_vec::BitVec;
231 /// use bit_set::BitSet;
233 /// let bv = BitVec::from_bytes(&[0b01100000]);
234 /// let s = BitSet::from_bit_vec(bv);
236 /// // Print 1, 2 in arbitrary order
237 /// for x in s.iter() {
238 /// println!("{}", x);
243 pub fn from_bit_vec(bit_vec: BitVec) -> Self {
247 pub fn from_bytes(bytes: &[u8]) -> Self {
249 bit_vec: BitVec::from_bytes(bytes),
254 impl<B: BitBlock> BitSet<B> {
255 /// Returns the capacity in bits for this bit vector. Inserting any
256 /// element less than this amount will not trigger a resizing.
261 /// use bit_set::BitSet;
263 /// let mut s = BitSet::with_capacity(100);
264 /// assert!(s.capacity() >= 100);
267 pub fn capacity(&self) -> usize {
268 self.bit_vec.capacity()
271 /// Reserves capacity for the given `BitSet` to contain `len` distinct elements. In the case
272 /// of `BitSet` this means reallocations will not occur as long as all inserted elements
273 /// are less than `len`.
275 /// The collection may reserve more space to avoid frequent reallocations.
281 /// use bit_set::BitSet;
283 /// let mut s = BitSet::new();
284 /// s.reserve_len(10);
285 /// assert!(s.capacity() >= 10);
287 pub fn reserve_len(&mut self, len: usize) {
288 let cur_len = self.bit_vec.len();
290 self.bit_vec.reserve(len - cur_len);
294 /// Reserves the minimum capacity for the given `BitSet` to contain `len` distinct elements.
295 /// In the case of `BitSet` this means reallocations will not occur as long as all inserted
296 /// elements are less than `len`.
298 /// Note that the allocator may give the collection more space than it requests. Therefore
299 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve_len` if future
300 /// insertions are expected.
306 /// use bit_set::BitSet;
308 /// let mut s = BitSet::new();
309 /// s.reserve_len_exact(10);
310 /// assert!(s.capacity() >= 10);
312 pub fn reserve_len_exact(&mut self, len: usize) {
313 let cur_len = self.bit_vec.len();
315 self.bit_vec.reserve_exact(len - cur_len);
319 /// Consumes this set to return the underlying bit vector.
324 /// use bit_set::BitSet;
326 /// let mut s = BitSet::new();
330 /// let bv = s.into_bit_vec();
335 pub fn into_bit_vec(self) -> BitVec<B> {
339 /// Returns a reference to the underlying bit vector.
344 /// use bit_set::BitSet;
346 /// let mut s = BitSet::new();
349 /// let bv = s.get_ref();
350 /// assert_eq!(bv[0], true);
353 pub fn get_ref(&self) -> &BitVec<B> {
358 fn other_op<F>(&mut self, other: &Self, mut f: F)
363 let self_bit_vec = &mut self.bit_vec;
364 let other_bit_vec = &other.bit_vec;
366 let self_len = self_bit_vec.len();
367 let other_len = other_bit_vec.len();
369 // Expand the vector if necessary
370 if self_len < other_len {
371 self_bit_vec.grow(other_len - self_len, false);
374 // virtually pad other with 0's for equal lengths
376 let (_, result) = match_words(self_bit_vec, other_bit_vec);
380 // Apply values found in other
381 for (i, w) in other_words {
382 let old = self_bit_vec.storage()[i];
385 self_bit_vec.storage_mut()[i] = new;
390 /// Truncates the underlying vector to the least length required.
395 /// use bit_set::BitSet;
397 /// let mut s = BitSet::new();
398 /// s.insert(32183231);
399 /// s.remove(32183231);
401 /// // Internal storage will probably be bigger than necessary
402 /// println!("old capacity: {}", s.capacity());
404 /// // Now should be smaller
405 /// s.shrink_to_fit();
406 /// println!("new capacity: {}", s.capacity());
409 pub fn shrink_to_fit(&mut self) {
410 let bit_vec = &mut self.bit_vec;
411 // Obtain original length
412 let old_len = bit_vec.storage().len();
413 // Obtain coarse trailing zero length
418 .take_while(|&&n| n == B::zero())
420 // Truncate away all empty trailing blocks, then shrink_to_fit
421 let trunc_len = old_len - n;
423 bit_vec.storage_mut().truncate(trunc_len);
424 bit_vec.set_len(trunc_len * B::bits());
425 bit_vec.shrink_to_fit();
429 /// Iterator over each usize stored in the `BitSet`.
434 /// use bit_set::BitSet;
436 /// let s = BitSet::from_bytes(&[0b01001010]);
438 /// // Print 1, 4, 6 in arbitrary order
439 /// for x in s.iter() {
440 /// println!("{}", x);
444 pub fn iter(&self) -> Iter<B> {
445 Iter(BlockIter::from_blocks(self.bit_vec.blocks()))
448 /// Iterator over each usize stored in `self` union `other`.
449 /// See [union_with](#method.union_with) for an efficient in-place version.
454 /// use bit_set::BitSet;
456 /// let a = BitSet::from_bytes(&[0b01101000]);
457 /// let b = BitSet::from_bytes(&[0b10100000]);
459 /// // Print 0, 1, 2, 4 in arbitrary order
460 /// for x in a.union(&b) {
461 /// println!("{}", x);
465 pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, B> {
466 fn or<B: BitBlock>(w1: B, w2: B) -> B {
470 Union(BlockIter::from_blocks(TwoBitPositions {
471 set: self.bit_vec.blocks(),
472 other: other.bit_vec.blocks(),
477 /// Iterator over each usize stored in `self` intersect `other`.
478 /// See [intersect_with](#method.intersect_with) for an efficient in-place version.
483 /// use bit_set::BitSet;
485 /// let a = BitSet::from_bytes(&[0b01101000]);
486 /// let b = BitSet::from_bytes(&[0b10100000]);
489 /// for x in a.intersection(&b) {
490 /// println!("{}", x);
494 pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, B> {
495 fn bitand<B: BitBlock>(w1: B, w2: B) -> B {
498 let min = cmp::min(self.bit_vec.len(), other.bit_vec.len());
501 BlockIter::from_blocks(TwoBitPositions {
502 set: self.bit_vec.blocks(),
503 other: other.bit_vec.blocks(),
510 /// Iterator over each usize stored in the `self` setminus `other`.
511 /// See [difference_with](#method.difference_with) for an efficient in-place version.
516 /// use bit_set::BitSet;
518 /// let a = BitSet::from_bytes(&[0b01101000]);
519 /// let b = BitSet::from_bytes(&[0b10100000]);
521 /// // Print 1, 4 in arbitrary order
522 /// for x in a.difference(&b) {
523 /// println!("{}", x);
526 /// // Note that difference is not symmetric,
527 /// // and `b - a` means something else.
529 /// for x in b.difference(&a) {
530 /// println!("{}", x);
534 pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, B> {
535 fn diff<B: BitBlock>(w1: B, w2: B) -> B {
539 Difference(BlockIter::from_blocks(TwoBitPositions {
540 set: self.bit_vec.blocks(),
541 other: other.bit_vec.blocks(),
546 /// Iterator over each usize stored in the symmetric difference of `self` and `other`.
547 /// See [symmetric_difference_with](#method.symmetric_difference_with) for
548 /// an efficient in-place version.
553 /// use bit_set::BitSet;
555 /// let a = BitSet::from_bytes(&[0b01101000]);
556 /// let b = BitSet::from_bytes(&[0b10100000]);
558 /// // Print 0, 1, 4 in arbitrary order
559 /// for x in a.symmetric_difference(&b) {
560 /// println!("{}", x);
564 pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> SymmetricDifference<'a, B> {
565 fn bitxor<B: BitBlock>(w1: B, w2: B) -> B {
569 SymmetricDifference(BlockIter::from_blocks(TwoBitPositions {
570 set: self.bit_vec.blocks(),
571 other: other.bit_vec.blocks(),
576 /// Unions in-place with the specified other bit vector.
581 /// use bit_set::BitSet;
583 /// let a = 0b01101000;
584 /// let b = 0b10100000;
585 /// let res = 0b11101000;
587 /// let mut a = BitSet::from_bytes(&[a]);
588 /// let b = BitSet::from_bytes(&[b]);
589 /// let res = BitSet::from_bytes(&[res]);
591 /// a.union_with(&b);
592 /// assert_eq!(a, res);
595 pub fn union_with(&mut self, other: &Self) {
596 self.other_op(other, |w1, w2| w1 | w2);
599 /// Intersects in-place with the specified other bit vector.
604 /// use bit_set::BitSet;
606 /// let a = 0b01101000;
607 /// let b = 0b10100000;
608 /// let res = 0b00100000;
610 /// let mut a = BitSet::from_bytes(&[a]);
611 /// let b = BitSet::from_bytes(&[b]);
612 /// let res = BitSet::from_bytes(&[res]);
614 /// a.intersect_with(&b);
615 /// assert_eq!(a, res);
618 pub fn intersect_with(&mut self, other: &Self) {
619 self.other_op(other, |w1, w2| w1 & w2);
622 /// Makes this bit vector the difference with the specified other bit vector
628 /// use bit_set::BitSet;
630 /// let a = 0b01101000;
631 /// let b = 0b10100000;
632 /// let a_b = 0b01001000; // a - b
633 /// let b_a = 0b10000000; // b - a
635 /// let mut bva = BitSet::from_bytes(&[a]);
636 /// let bvb = BitSet::from_bytes(&[b]);
637 /// let bva_b = BitSet::from_bytes(&[a_b]);
638 /// let bvb_a = BitSet::from_bytes(&[b_a]);
640 /// bva.difference_with(&bvb);
641 /// assert_eq!(bva, bva_b);
643 /// let bva = BitSet::from_bytes(&[a]);
644 /// let mut bvb = BitSet::from_bytes(&[b]);
646 /// bvb.difference_with(&bva);
647 /// assert_eq!(bvb, bvb_a);
650 pub fn difference_with(&mut self, other: &Self) {
651 self.other_op(other, |w1, w2| w1 & !w2);
654 /// Makes this bit vector the symmetric difference with the specified other
655 /// bit vector in-place.
660 /// use bit_set::BitSet;
662 /// let a = 0b01101000;
663 /// let b = 0b10100000;
664 /// let res = 0b11001000;
666 /// let mut a = BitSet::from_bytes(&[a]);
667 /// let b = BitSet::from_bytes(&[b]);
668 /// let res = BitSet::from_bytes(&[res]);
670 /// a.symmetric_difference_with(&b);
671 /// assert_eq!(a, res);
674 pub fn symmetric_difference_with(&mut self, other: &Self) {
675 self.other_op(other, |w1, w2| w1 ^ w2);
679 /// Moves all elements from `other` into `Self`, leaving `other` empty.
684 /// use bit_set::BitSet;
686 /// let mut a = BitSet::new();
690 /// let mut b = BitSet::new();
695 /// a.append(&mut b);
697 /// assert_eq!(a.len(), 4);
698 /// assert_eq!(b.len(), 0);
699 /// assert_eq!(a, BitSet::from_bytes(&[0b01110010]));
701 pub fn append(&mut self, other: &mut Self) {
702 self.union_with(other);
706 /// Splits the `BitSet` into two at the given key including the key.
707 /// Retains the first part in-place while returning the second part.
712 /// use bit_set::BitSet;
714 /// let mut a = BitSet::new();
720 /// let b = a.split_off(3);
722 /// assert_eq!(a.len(), 2);
723 /// assert_eq!(b.len(), 2);
724 /// assert_eq!(a, BitSet::from_bytes(&[0b01100000]));
725 /// assert_eq!(b, BitSet::from_bytes(&[0b00010010]));
727 pub fn split_off(&mut self, at: usize) -> Self {
728 let mut other = BitSet::new();
731 swap(self, &mut other);
733 } else if at >= self.bit_vec.len() {
737 // Calculate block and bit at which to split
741 // Pad `other` with `w` zero blocks,
742 // append `self`'s blocks in the range from `w` to the end to `other`
743 other.bit_vec.storage_mut().extend(repeat(0u32).take(w)
744 .chain(self.bit_vec.storage()[w..].iter().cloned()));
745 other.bit_vec.nbits = self.bit_vec.nbits;
748 other.bit_vec.storage_mut()[w] &= !0 << b;
751 // Sets `bit_vec.len()` and fixes the last block as well
752 self.bit_vec.truncate(at);
758 /// Returns the number of set bits in this set.
760 pub fn len(&self) -> usize {
763 .fold(0, |acc, n| acc + n.count_ones() as usize)
766 /// Returns whether there are no bits set in this set
768 pub fn is_empty(&self) -> bool {
772 /// Clears all bits in this set
774 pub fn clear(&mut self) {
775 self.bit_vec.clear();
778 /// Returns `true` if this set contains the specified integer.
780 pub fn contains(&self, value: usize) -> bool {
781 let bit_vec = &self.bit_vec;
782 value < bit_vec.len() && bit_vec[value]
785 /// Returns `true` if the set has no elements in common with `other`.
786 /// This is equivalent to checking for an empty intersection.
788 pub fn is_disjoint(&self, other: &Self) -> bool {
789 self.intersection(other).next().is_none()
792 /// Returns `true` if the set is a subset of another.
794 pub fn is_subset(&self, other: &Self) -> bool {
795 let self_bit_vec = &self.bit_vec;
796 let other_bit_vec = &other.bit_vec;
797 let other_blocks = blocks_for_bits::<B>(other_bit_vec.len());
799 // Check that `self` intersect `other` is self
800 self_bit_vec.blocks().zip(other_bit_vec.blocks()).all(|(w1, w2)| w1 & w2 == w1) &&
801 // Make sure if `self` has any more blocks than `other`, they're all 0
802 self_bit_vec.blocks().skip(other_blocks).all(|w| w == B::zero())
805 /// Returns `true` if the set is a superset of another.
807 pub fn is_superset(&self, other: &Self) -> bool {
808 other.is_subset(self)
811 /// Adds a value to the set. Returns `true` if the value was not already
812 /// present in the set.
813 pub fn insert(&mut self, value: usize) -> bool {
814 if self.contains(value) {
818 // Ensure we have enough space to hold the new element
819 let len = self.bit_vec.len();
821 self.bit_vec.grow(value - len + 1, false)
824 self.bit_vec.set(value, true);
828 /// Removes a value from the set. Returns `true` if the value was
829 /// present in the set.
830 pub fn remove(&mut self, value: usize) -> bool {
831 if !self.contains(value) {
835 self.bit_vec.set(value, false);
841 impl<B: BitBlock> fmt::Debug for BitSet<B> {
842 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
843 fmt.debug_set().entries(self).finish()
847 impl<B: BitBlock> hash::Hash for BitSet<B> {
848 fn hash<H: hash::Hasher>(&self, state: &mut H) {
855 #[cfg(feature = "serde")]
856 impl<B: BitBlock + Serialize> Serialize for BitSet<B> {
857 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
858 self.bit_vec.serialize(serializer)
862 #[cfg(feature = "serde")]
863 impl<'de, B: BitBlock + Deserialize<'de>> Deserialize<'de> for BitSet<B> {
864 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
866 bit_vec: BitVec::deserialize(deserializer)?,
872 struct BlockIter<T, B> {
878 impl<T, B: BitBlock> BlockIter<T, B>
880 T: Iterator<Item = B>,
882 fn from_blocks(mut blocks: T) -> BlockIter<T, B> {
883 let h = blocks.next().unwrap_or_else(B::zero);
892 /// An iterator combining two `BitSet` iterators.
894 struct TwoBitPositions<'a, B: 'a> {
896 other: Blocks<'a, B>,
897 merge: fn(B, B) -> B,
900 /// An iterator for `BitSet`.
902 pub struct Iter<'a, B: 'a>(BlockIter<Blocks<'a, B>, B>);
904 pub struct Union<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
906 pub struct Intersection<'a, B: 'a>(Take<BlockIter<TwoBitPositions<'a, B>, B>>);
908 pub struct Difference<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
910 pub struct SymmetricDifference<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
912 impl<'a, T, B: BitBlock> Iterator for BlockIter<T, B>
914 T: Iterator<Item = B>,
918 fn next(&mut self) -> Option<usize> {
919 while self.head == B::zero() {
920 match self.tail.next() {
921 Some(w) => self.head = w,
924 self.head_offset += B::bits();
927 // from the current block, isolate the
928 // LSB and subtract 1, producing k:
929 // a block with a number of set bits
930 // equal to the index of the LSB
931 let k = (self.head & (!self.head + B::one())) - B::one();
932 // update block, removing the LSB
933 self.head = self.head & (self.head - B::one());
934 // return offset + (index of LSB)
935 Some(self.head_offset + (B::count_ones(k) as usize))
939 fn size_hint(&self) -> (usize, Option<usize>) {
940 match self.tail.size_hint() {
941 (_, Some(h)) => (0, Some(1 + h * B::bits())),
947 impl<'a, B: BitBlock> Iterator for TwoBitPositions<'a, B> {
950 fn next(&mut self) -> Option<B> {
951 match (self.set.next(), self.other.next()) {
952 (Some(a), Some(b)) => Some((self.merge)(a, b)),
953 (Some(a), None) => Some((self.merge)(a, B::zero())),
954 (None, Some(b)) => Some((self.merge)(B::zero(), b)),
960 fn size_hint(&self) -> (usize, Option<usize>) {
961 let (a, au) = self.set.size_hint();
962 let (b, bu) = self.other.size_hint();
964 let upper = match (au, bu) {
965 (Some(au), Some(bu)) => Some(cmp::max(au, bu)),
969 (cmp::max(a, b), upper)
973 impl<'a, B: BitBlock> Iterator for Iter<'a, B> {
977 fn next(&mut self) -> Option<usize> {
981 fn size_hint(&self) -> (usize, Option<usize>) {
986 impl<'a, B: BitBlock> Iterator for Union<'a, B> {
990 fn next(&mut self) -> Option<usize> {
994 fn size_hint(&self) -> (usize, Option<usize>) {
999 impl<'a, B: BitBlock> Iterator for Intersection<'a, B> {
1003 fn next(&mut self) -> Option<usize> {
1007 fn size_hint(&self) -> (usize, Option<usize>) {
1012 impl<'a, B: BitBlock> Iterator for Difference<'a, B> {
1016 fn next(&mut self) -> Option<usize> {
1020 fn size_hint(&self) -> (usize, Option<usize>) {
1025 impl<'a, B: BitBlock> Iterator for SymmetricDifference<'a, B> {
1029 fn next(&mut self) -> Option<usize> {
1033 fn size_hint(&self) -> (usize, Option<usize>) {
1038 impl<'a, B: BitBlock> IntoIterator for &'a BitSet<B> {
1040 type IntoIter = Iter<'a, B>;
1042 fn into_iter(self) -> Iter<'a, B> {
1050 use bit_vec::BitVec;
1051 use std::cmp::Ordering::{Equal, Greater, Less};
1055 fn test_bit_set_show() {
1056 let mut s = BitSet::new();
1061 assert_eq!("{1, 2, 10, 50}", format!("{:?}", s));
1065 fn test_bit_set_from_usizes() {
1066 let usizes = vec![0, 2, 2, 3];
1067 let a: BitSet = usizes.into_iter().collect();
1068 let mut b = BitSet::new();
1076 fn test_bit_set_iterator() {
1077 let usizes = vec![0, 2, 2, 3];
1078 let bit_vec: BitSet = usizes.into_iter().collect();
1080 let idxs: Vec<_> = bit_vec.iter().collect();
1081 assert_eq!(idxs, [0, 2, 3]);
1083 let long: BitSet = (0..10000).filter(|&n| n % 2 == 0).collect();
1084 let real: Vec<_> = (0..10000 / 2).map(|x| x * 2).collect();
1086 let idxs: Vec<_> = long.iter().collect();
1087 assert_eq!(idxs, real);
1091 fn test_bit_set_frombit_vec_init() {
1092 let bools = [true, false];
1093 let lengths = [10, 64, 100];
1095 for &l in &lengths {
1096 let bitset = BitSet::from_bit_vec(BitVec::from_elem(l, b));
1097 assert_eq!(bitset.contains(1), b);
1098 assert_eq!(bitset.contains(l - 1), b);
1099 assert!(!bitset.contains(l));
1105 fn test_bit_vec_masking() {
1106 let b = BitVec::from_elem(140, true);
1107 let mut bs = BitSet::from_bit_vec(b);
1108 assert!(bs.contains(139));
1109 assert!(!bs.contains(140));
1110 assert!(bs.insert(150));
1111 assert!(!bs.contains(140));
1112 assert!(!bs.contains(149));
1113 assert!(bs.contains(150));
1114 assert!(!bs.contains(151));
1118 fn test_bit_set_basic() {
1119 let mut b = BitSet::new();
1120 assert!(b.insert(3));
1121 assert!(!b.insert(3));
1122 assert!(b.contains(3));
1123 assert!(b.insert(4));
1124 assert!(!b.insert(4));
1125 assert!(b.contains(3));
1126 assert!(b.insert(400));
1127 assert!(!b.insert(400));
1128 assert!(b.contains(400));
1129 assert_eq!(b.len(), 3);
1133 fn test_bit_set_intersection() {
1134 let mut a = BitSet::new();
1135 let mut b = BitSet::new();
1137 assert!(a.insert(11));
1138 assert!(a.insert(1));
1139 assert!(a.insert(3));
1140 assert!(a.insert(77));
1141 assert!(a.insert(103));
1142 assert!(a.insert(5));
1144 assert!(b.insert(2));
1145 assert!(b.insert(11));
1146 assert!(b.insert(77));
1147 assert!(b.insert(5));
1148 assert!(b.insert(3));
1150 let expected = [3, 5, 11, 77];
1151 let actual: Vec<_> = a.intersection(&b).collect();
1152 assert_eq!(actual, expected);
1156 fn test_bit_set_difference() {
1157 let mut a = BitSet::new();
1158 let mut b = BitSet::new();
1160 assert!(a.insert(1));
1161 assert!(a.insert(3));
1162 assert!(a.insert(5));
1163 assert!(a.insert(200));
1164 assert!(a.insert(500));
1166 assert!(b.insert(3));
1167 assert!(b.insert(200));
1169 let expected = [1, 5, 500];
1170 let actual: Vec<_> = a.difference(&b).collect();
1171 assert_eq!(actual, expected);
1175 fn test_bit_set_symmetric_difference() {
1176 let mut a = BitSet::new();
1177 let mut b = BitSet::new();
1179 assert!(a.insert(1));
1180 assert!(a.insert(3));
1181 assert!(a.insert(5));
1182 assert!(a.insert(9));
1183 assert!(a.insert(11));
1185 assert!(b.insert(3));
1186 assert!(b.insert(9));
1187 assert!(b.insert(14));
1188 assert!(b.insert(220));
1190 let expected = [1, 5, 11, 14, 220];
1191 let actual: Vec<_> = a.symmetric_difference(&b).collect();
1192 assert_eq!(actual, expected);
1196 fn test_bit_set_union() {
1197 let mut a = BitSet::new();
1198 let mut b = BitSet::new();
1199 assert!(a.insert(1));
1200 assert!(a.insert(3));
1201 assert!(a.insert(5));
1202 assert!(a.insert(9));
1203 assert!(a.insert(11));
1204 assert!(a.insert(160));
1205 assert!(a.insert(19));
1206 assert!(a.insert(24));
1207 assert!(a.insert(200));
1209 assert!(b.insert(1));
1210 assert!(b.insert(5));
1211 assert!(b.insert(9));
1212 assert!(b.insert(13));
1213 assert!(b.insert(19));
1215 let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160, 200];
1216 let actual: Vec<_> = a.union(&b).collect();
1217 assert_eq!(actual, expected);
1221 fn test_bit_set_subset() {
1222 let mut set1 = BitSet::new();
1223 let mut set2 = BitSet::new();
1225 assert!(set1.is_subset(&set2)); // {} {}
1227 assert!(set1.is_subset(&set2)); // {} { 1 }
1229 assert!(set1.is_subset(&set2)); // {} { 1, 2 }
1231 assert!(set1.is_subset(&set2)); // { 2 } { 1, 2 }
1233 assert!(!set1.is_subset(&set2)); // { 2, 3 } { 1, 2 }
1235 assert!(set1.is_subset(&set2)); // { 2, 3 } { 1, 2, 3 }
1237 assert!(set1.is_subset(&set2)); // { 2, 3 } { 1, 2, 3, 4 }
1239 assert!(set1.is_subset(&set2)); // { 2, 3 } { 2, 3, 4 }
1241 assert!(!set1.is_subset(&set2)); // { 2, 3 } { 2, 4 }
1243 assert!(set1.is_subset(&set2)); // { 2 } { 2, 4 }
1247 fn test_bit_set_is_disjoint() {
1248 let a = BitSet::from_bytes(&[0b10100010]);
1249 let b = BitSet::from_bytes(&[0b01000000]);
1250 let c = BitSet::new();
1251 let d = BitSet::from_bytes(&[0b00110000]);
1253 assert!(!a.is_disjoint(&d));
1254 assert!(!d.is_disjoint(&a));
1256 assert!(a.is_disjoint(&b));
1257 assert!(a.is_disjoint(&c));
1258 assert!(b.is_disjoint(&a));
1259 assert!(b.is_disjoint(&c));
1260 assert!(c.is_disjoint(&a));
1261 assert!(c.is_disjoint(&b));
1265 fn test_bit_set_union_with() {
1266 //a should grow to include larger elements
1267 let mut a = BitSet::new();
1269 let mut b = BitSet::new();
1271 let expected = BitSet::from_bytes(&[0b10000100]);
1273 assert_eq!(a, expected);
1276 let mut a = BitSet::from_bytes(&[0b10100010]);
1277 let mut b = BitSet::from_bytes(&[0b01100010]);
1281 assert_eq!(a.len(), 4);
1282 assert_eq!(b.len(), 4);
1286 fn test_bit_set_intersect_with() {
1287 // Explicitly 0'ed bits
1288 let mut a = BitSet::from_bytes(&[0b10100010]);
1289 let mut b = BitSet::from_bytes(&[0b00000000]);
1291 a.intersect_with(&b);
1292 b.intersect_with(&c);
1293 assert!(a.is_empty());
1294 assert!(b.is_empty());
1296 // Uninitialized bits should behave like 0's
1297 let mut a = BitSet::from_bytes(&[0b10100010]);
1298 let mut b = BitSet::new();
1300 a.intersect_with(&b);
1301 b.intersect_with(&c);
1302 assert!(a.is_empty());
1303 assert!(b.is_empty());
1306 let mut a = BitSet::from_bytes(&[0b10100010]);
1307 let mut b = BitSet::from_bytes(&[0b01100010]);
1309 a.intersect_with(&b);
1310 b.intersect_with(&c);
1311 assert_eq!(a.len(), 2);
1312 assert_eq!(b.len(), 2);
1316 fn test_bit_set_difference_with() {
1317 // Explicitly 0'ed bits
1318 let mut a = BitSet::from_bytes(&[0b00000000]);
1319 let b = BitSet::from_bytes(&[0b10100010]);
1320 a.difference_with(&b);
1321 assert!(a.is_empty());
1323 // Uninitialized bits should behave like 0's
1324 let mut a = BitSet::new();
1325 let b = BitSet::from_bytes(&[0b11111111]);
1326 a.difference_with(&b);
1327 assert!(a.is_empty());
1330 let mut a = BitSet::from_bytes(&[0b10100010]);
1331 let mut b = BitSet::from_bytes(&[0b01100010]);
1333 a.difference_with(&b);
1334 b.difference_with(&c);
1335 assert_eq!(a.len(), 1);
1336 assert_eq!(b.len(), 1);
1340 fn test_bit_set_symmetric_difference_with() {
1341 //a should grow to include larger elements
1342 let mut a = BitSet::new();
1345 let mut b = BitSet::new();
1348 let expected = BitSet::from_bytes(&[0b10000100]);
1349 a.symmetric_difference_with(&b);
1350 assert_eq!(a, expected);
1352 let mut a = BitSet::from_bytes(&[0b10100010]);
1353 let b = BitSet::new();
1355 a.symmetric_difference_with(&b);
1359 let mut a = BitSet::from_bytes(&[0b11100010]);
1360 let mut b = BitSet::from_bytes(&[0b01101010]);
1362 a.symmetric_difference_with(&b);
1363 b.symmetric_difference_with(&c);
1364 assert_eq!(a.len(), 2);
1365 assert_eq!(b.len(), 2);
1369 fn test_bit_set_eq() {
1370 let a = BitSet::from_bytes(&[0b10100010]);
1371 let b = BitSet::from_bytes(&[0b00000000]);
1372 let c = BitSet::new();
1383 fn test_bit_set_cmp() {
1384 let a = BitSet::from_bytes(&[0b10100010]);
1385 let b = BitSet::from_bytes(&[0b00000000]);
1386 let c = BitSet::new();
1388 assert_eq!(a.cmp(&b), Greater);
1389 assert_eq!(a.cmp(&c), Greater);
1390 assert_eq!(b.cmp(&a), Less);
1391 assert_eq!(b.cmp(&c), Equal);
1392 assert_eq!(c.cmp(&a), Less);
1393 assert_eq!(c.cmp(&b), Equal);
1397 fn test_bit_set_shrink_to_fit_new() {
1398 // There was a strange bug where we refused to truncate to 0
1399 // and this would end up actually growing the array in a way
1400 // that (safely corrupted the state).
1401 let mut a = BitSet::new();
1402 assert_eq!(a.len(), 0);
1403 assert_eq!(a.capacity(), 0);
1405 assert_eq!(a.len(), 0);
1406 assert_eq!(a.capacity(), 0);
1407 assert!(!a.contains(1));
1409 assert!(a.contains(3));
1410 assert_eq!(a.len(), 1);
1411 assert!(a.capacity() > 0);
1413 assert!(a.contains(3));
1414 assert_eq!(a.len(), 1);
1415 assert!(a.capacity() > 0);
1419 fn test_bit_set_shrink_to_fit() {
1420 let mut a = BitSet::new();
1421 assert_eq!(a.len(), 0);
1422 assert_eq!(a.capacity(), 0);
1426 assert_eq!(a.len(), 3);
1427 assert!(a.capacity() > 0);
1428 assert!(!a.contains(1));
1429 assert!(a.contains(259));
1430 assert!(a.contains(98));
1431 assert!(a.contains(3));
1434 assert!(!a.contains(1));
1435 assert!(a.contains(259));
1436 assert!(a.contains(98));
1437 assert!(a.contains(3));
1438 assert_eq!(a.len(), 3);
1439 assert!(a.capacity() > 0);
1441 let old_cap = a.capacity();
1442 assert!(a.remove(259));
1444 assert!(a.capacity() < old_cap, "{} {}", a.capacity(), old_cap);
1445 assert!(!a.contains(1));
1446 assert!(!a.contains(259));
1447 assert!(a.contains(98));
1448 assert!(a.contains(3));
1449 assert_eq!(a.len(), 2);
1451 let old_cap2 = a.capacity();
1453 assert_eq!(a.capacity(), old_cap2);
1454 assert_eq!(a.len(), 0);
1455 assert!(!a.contains(1));
1456 assert!(!a.contains(259));
1457 assert!(!a.contains(98));
1458 assert!(!a.contains(3));
1461 assert!(a.capacity() > 0);
1462 assert_eq!(a.len(), 1);
1463 assert!(a.contains(512));
1464 assert!(!a.contains(1));
1465 assert!(!a.contains(259));
1466 assert!(!a.contains(98));
1467 assert!(!a.contains(3));
1471 assert_eq!(a.capacity(), 0);
1472 assert_eq!(a.len(), 0);
1473 assert!(!a.contains(512));
1474 assert!(!a.contains(1));
1475 assert!(!a.contains(259));
1476 assert!(!a.contains(98));
1477 assert!(!a.contains(3));
1478 assert!(!a.contains(0));
1482 fn test_bit_vec_remove() {
1483 let mut a = BitSet::new();
1485 assert!(a.insert(1));
1486 assert!(a.remove(1));
1488 assert!(a.insert(100));
1489 assert!(a.remove(100));
1491 assert!(a.insert(1000));
1492 assert!(a.remove(1000));
1497 fn test_bit_vec_clone() {
1498 let mut a = BitSet::new();
1500 assert!(a.insert(1));
1501 assert!(a.insert(100));
1502 assert!(a.insert(1000));
1504 let mut b = a.clone();
1508 assert!(b.remove(1));
1509 assert!(a.contains(1));
1511 assert!(a.remove(1000));
1512 assert!(b.contains(1000));
1517 fn test_bit_set_append() {
1518 let mut a = BitSet::new();
1522 let mut b = BitSet::new();
1529 assert_eq!(a.len(), 4);
1530 assert_eq!(b.len(), 0);
1531 assert!(b.capacity() >= 6);
1533 assert_eq!(a, BitSet::from_bytes(&[0b01110010]));
1537 fn test_bit_set_split_off() {
1539 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1540 0b00110011, 0b01101011, 0b10101101]);
1542 let b = a.split_off(0);
1544 assert_eq!(a.len(), 0);
1545 assert_eq!(b.len(), 21);
1547 assert_eq!(b, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1548 0b00110011, 0b01101011, 0b10101101]);
1550 // Split behind last element
1551 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1552 0b00110011, 0b01101011, 0b10101101]);
1554 let b = a.split_off(50);
1556 assert_eq!(a.len(), 21);
1557 assert_eq!(b.len(), 0);
1559 assert_eq!(a, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1560 0b00110011, 0b01101011, 0b10101101]));
1562 // Split at arbitrary element
1563 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1564 0b00110011, 0b01101011, 0b10101101]);
1566 let b = a.split_off(34);
1568 assert_eq!(a.len(), 12);
1569 assert_eq!(b.len(), 9);
1571 assert_eq!(a, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1572 0b00110011, 0b01000000]));
1573 assert_eq!(b, BitSet::from_bytes(&[0, 0, 0, 0,
1574 0b00101011, 0b10101101]));
1579 #[cfg(all(test, feature = "nightly"))]
1582 use bit_vec::BitVec;
1583 use rand::{thread_rng, Rng, ThreadRng};
1585 use test::{black_box, Bencher};
1587 const BENCH_BITS: usize = 1 << 14;
1588 const BITS: usize = 32;
1590 fn rng() -> ThreadRng {
1595 fn bench_bit_vecset_small(b: &mut Bencher) {
1597 let mut bit_vec = BitSet::new();
1600 bit_vec.insert((r.next_u32() as usize) % BITS);
1602 black_box(&bit_vec);
1607 fn bench_bit_vecset_big(b: &mut Bencher) {
1609 let mut bit_vec = BitSet::new();
1612 bit_vec.insert((r.next_u32() as usize) % BENCH_BITS);
1614 black_box(&bit_vec);
1619 fn bench_bit_vecset_iter(b: &mut Bencher) {
1620 let bit_vec = BitSet::from_bit_vec(BitVec::from_fn(BENCH_BITS, |idx| idx % 3 == 0));
1623 for idx in &bit_vec {
1624 sum += idx as usize;