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(all(test, feature = "nightly"))]
62 use bit_vec::{BitBlock, BitVec, Blocks};
64 use core::cmp::Ordering;
67 use core::iter::{self, Chain, Enumerate, FromIterator, Repeat, Skip, Take};
69 type MatchWords<'a, B> = Chain<Enumerate<Blocks<'a, B>>, Skip<Take<Enumerate<Repeat<B>>>>>;
71 /// Computes how many blocks are needed to store that many bits
72 fn blocks_for_bits<B: BitBlock>(bits: usize) -> usize {
73 // If we want 17 bits, dividing by 32 will produce 0. So we add 1 to make sure we
74 // reserve enough. But if we want exactly a multiple of 32, this will actually allocate
75 // one too many. So we need to check if that's the case. We can do that by computing if
76 // bitwise AND by `32 - 1` is 0. But LLVM should be able to optimize the semantically
77 // superior modulo operator on a power of two to this.
79 // Note that we can technically avoid this branch with the expression
80 // `(nbits + BITS - 1) / 32::BITS`, but if nbits is almost usize::MAX this will overflow.
81 if bits % B::bits() == 0 {
88 // Take two BitVec's, and return iterators of their words, where the shorter one
89 // has been padded with 0's
90 fn match_words<'a, 'b, B: BitBlock>(
93 ) -> (MatchWords<'a, B>, MatchWords<'b, B>) {
94 let a_len = a.storage().len();
95 let b_len = b.storage().len();
97 // have to uselessly pretend to pad the longer one for type matching
102 .chain(iter::repeat(B::zero()).enumerate().take(b_len).skip(a_len)),
105 .chain(iter::repeat(B::zero()).enumerate().take(0).skip(0)),
111 .chain(iter::repeat(B::zero()).enumerate().take(0).skip(0)),
114 .chain(iter::repeat(B::zero()).enumerate().take(a_len).skip(b_len)),
119 pub struct BitSet<B = u32> {
123 impl<B: BitBlock> Clone for BitSet<B> {
124 fn clone(&self) -> Self {
126 bit_vec: self.bit_vec.clone(),
130 fn clone_from(&mut self, other: &Self) {
131 self.bit_vec.clone_from(&other.bit_vec);
135 impl<B: BitBlock> Default for BitSet<B> {
137 fn default() -> Self {
139 bit_vec: Default::default(),
144 impl<B: BitBlock> FromIterator<usize> for BitSet<B> {
145 fn from_iter<I: IntoIterator<Item = usize>>(iter: I) -> Self {
146 let mut ret = Self::default();
152 impl<B: BitBlock> Extend<usize> for BitSet<B> {
154 fn extend<I: IntoIterator<Item = usize>>(&mut self, iter: I) {
161 impl<B: BitBlock> PartialOrd for BitSet<B> {
163 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
164 self.iter().partial_cmp(other)
168 impl<B: BitBlock> Ord for BitSet<B> {
170 fn cmp(&self, other: &Self) -> Ordering {
171 self.iter().cmp(other)
175 impl<B: BitBlock> PartialEq for BitSet<B> {
177 fn eq(&self, other: &Self) -> bool {
178 self.iter().eq(other)
182 impl<B: BitBlock> Eq for BitSet<B> {}
185 /// Creates a new empty `BitSet`.
190 /// use bit_set::BitSet;
192 /// let mut s = BitSet::new();
195 pub fn new() -> Self {
199 /// Creates a new `BitSet` with initially no contents, able to
200 /// hold `nbits` elements without resizing.
205 /// use bit_set::BitSet;
207 /// let mut s = BitSet::with_capacity(100);
208 /// assert!(s.capacity() >= 100);
211 pub fn with_capacity(nbits: usize) -> Self {
212 let bit_vec = BitVec::from_elem(nbits, false);
213 Self::from_bit_vec(bit_vec)
216 /// Creates a new `BitSet` from the given bit vector.
221 /// extern crate bit_vec;
222 /// extern crate bit_set;
225 /// use bit_vec::BitVec;
226 /// use bit_set::BitSet;
228 /// let bv = BitVec::from_bytes(&[0b01100000]);
229 /// let s = BitSet::from_bit_vec(bv);
231 /// // Print 1, 2 in arbitrary order
232 /// for x in s.iter() {
233 /// println!("{}", x);
238 pub fn from_bit_vec(bit_vec: BitVec) -> Self {
242 pub fn from_bytes(bytes: &[u8]) -> Self {
244 bit_vec: BitVec::from_bytes(bytes),
249 impl<B: BitBlock> BitSet<B> {
250 /// Returns the capacity in bits for this bit vector. Inserting any
251 /// element less than this amount will not trigger a resizing.
256 /// use bit_set::BitSet;
258 /// let mut s = BitSet::with_capacity(100);
259 /// assert!(s.capacity() >= 100);
262 pub fn capacity(&self) -> usize {
263 self.bit_vec.capacity()
266 /// Reserves capacity for the given `BitSet` to contain `len` distinct elements. In the case
267 /// of `BitSet` this means reallocations will not occur as long as all inserted elements
268 /// are less than `len`.
270 /// The collection may reserve more space to avoid frequent reallocations.
276 /// use bit_set::BitSet;
278 /// let mut s = BitSet::new();
279 /// s.reserve_len(10);
280 /// assert!(s.capacity() >= 10);
282 pub fn reserve_len(&mut self, len: usize) {
283 let cur_len = self.bit_vec.len();
285 self.bit_vec.reserve(len - cur_len);
289 /// Reserves the minimum capacity for the given `BitSet` to contain `len` distinct elements.
290 /// In the case of `BitSet` this means reallocations will not occur as long as all inserted
291 /// elements are less than `len`.
293 /// Note that the allocator may give the collection more space than it requests. Therefore
294 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve_len` if future
295 /// insertions are expected.
301 /// use bit_set::BitSet;
303 /// let mut s = BitSet::new();
304 /// s.reserve_len_exact(10);
305 /// assert!(s.capacity() >= 10);
307 pub fn reserve_len_exact(&mut self, len: usize) {
308 let cur_len = self.bit_vec.len();
310 self.bit_vec.reserve_exact(len - cur_len);
314 /// Consumes this set to return the underlying bit vector.
319 /// use bit_set::BitSet;
321 /// let mut s = BitSet::new();
325 /// let bv = s.into_bit_vec();
330 pub fn into_bit_vec(self) -> BitVec<B> {
334 /// Returns a reference to the underlying bit vector.
339 /// use bit_set::BitSet;
341 /// let mut s = BitSet::new();
344 /// let bv = s.get_ref();
345 /// assert_eq!(bv[0], true);
348 pub fn get_ref(&self) -> &BitVec<B> {
353 fn other_op<F>(&mut self, other: &Self, mut f: F)
358 let self_bit_vec = &mut self.bit_vec;
359 let other_bit_vec = &other.bit_vec;
361 let self_len = self_bit_vec.len();
362 let other_len = other_bit_vec.len();
364 // Expand the vector if necessary
365 if self_len < other_len {
366 self_bit_vec.grow(other_len - self_len, false);
369 // virtually pad other with 0's for equal lengths
371 let (_, result) = match_words(self_bit_vec, other_bit_vec);
375 // Apply values found in other
376 for (i, w) in other_words {
377 let old = self_bit_vec.storage()[i];
380 self_bit_vec.storage_mut()[i] = new;
385 /// Truncates the underlying vector to the least length required.
390 /// use bit_set::BitSet;
392 /// let mut s = BitSet::new();
393 /// s.insert(32183231);
394 /// s.remove(32183231);
396 /// // Internal storage will probably be bigger than necessary
397 /// println!("old capacity: {}", s.capacity());
399 /// // Now should be smaller
400 /// s.shrink_to_fit();
401 /// println!("new capacity: {}", s.capacity());
404 pub fn shrink_to_fit(&mut self) {
405 let bit_vec = &mut self.bit_vec;
406 // Obtain original length
407 let old_len = bit_vec.storage().len();
408 // Obtain coarse trailing zero length
413 .take_while(|&&n| n == B::zero())
416 let trunc_len = cmp::max(old_len - n, 1);
418 bit_vec.storage_mut().truncate(trunc_len);
419 bit_vec.set_len(trunc_len * B::bits());
423 /// Iterator over each usize stored in the `BitSet`.
428 /// use bit_set::BitSet;
430 /// let s = BitSet::from_bytes(&[0b01001010]);
432 /// // Print 1, 4, 6 in arbitrary order
433 /// for x in s.iter() {
434 /// println!("{}", x);
438 pub fn iter(&self) -> Iter<B> {
439 Iter(BlockIter::from_blocks(self.bit_vec.blocks()))
442 /// Iterator over each usize stored in `self` union `other`.
443 /// See [union_with](#method.union_with) for an efficient in-place version.
448 /// use bit_set::BitSet;
450 /// let a = BitSet::from_bytes(&[0b01101000]);
451 /// let b = BitSet::from_bytes(&[0b10100000]);
453 /// // Print 0, 1, 2, 4 in arbitrary order
454 /// for x in a.union(&b) {
455 /// println!("{}", x);
459 pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, B> {
460 fn or<B: BitBlock>(w1: B, w2: B) -> B {
464 Union(BlockIter::from_blocks(TwoBitPositions {
465 set: self.bit_vec.blocks(),
466 other: other.bit_vec.blocks(),
471 /// Iterator over each usize stored in `self` intersect `other`.
472 /// See [intersect_with](#method.intersect_with) for an efficient in-place version.
477 /// use bit_set::BitSet;
479 /// let a = BitSet::from_bytes(&[0b01101000]);
480 /// let b = BitSet::from_bytes(&[0b10100000]);
483 /// for x in a.intersection(&b) {
484 /// println!("{}", x);
488 pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, B> {
489 fn bitand<B: BitBlock>(w1: B, w2: B) -> B {
492 let min = cmp::min(self.bit_vec.len(), other.bit_vec.len());
495 BlockIter::from_blocks(TwoBitPositions {
496 set: self.bit_vec.blocks(),
497 other: other.bit_vec.blocks(),
504 /// Iterator over each usize stored in the `self` setminus `other`.
505 /// See [difference_with](#method.difference_with) for an efficient in-place version.
510 /// use bit_set::BitSet;
512 /// let a = BitSet::from_bytes(&[0b01101000]);
513 /// let b = BitSet::from_bytes(&[0b10100000]);
515 /// // Print 1, 4 in arbitrary order
516 /// for x in a.difference(&b) {
517 /// println!("{}", x);
520 /// // Note that difference is not symmetric,
521 /// // and `b - a` means something else.
523 /// for x in b.difference(&a) {
524 /// println!("{}", x);
528 pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, B> {
529 fn diff<B: BitBlock>(w1: B, w2: B) -> B {
533 Difference(BlockIter::from_blocks(TwoBitPositions {
534 set: self.bit_vec.blocks(),
535 other: other.bit_vec.blocks(),
540 /// Iterator over each usize stored in the symmetric difference of `self` and `other`.
541 /// See [symmetric_difference_with](#method.symmetric_difference_with) for
542 /// an efficient in-place version.
547 /// use bit_set::BitSet;
549 /// let a = BitSet::from_bytes(&[0b01101000]);
550 /// let b = BitSet::from_bytes(&[0b10100000]);
552 /// // Print 0, 1, 4 in arbitrary order
553 /// for x in a.symmetric_difference(&b) {
554 /// println!("{}", x);
558 pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> SymmetricDifference<'a, B> {
559 fn bitxor<B: BitBlock>(w1: B, w2: B) -> B {
563 SymmetricDifference(BlockIter::from_blocks(TwoBitPositions {
564 set: self.bit_vec.blocks(),
565 other: other.bit_vec.blocks(),
570 /// Unions in-place with the specified other bit vector.
575 /// use bit_set::BitSet;
577 /// let a = 0b01101000;
578 /// let b = 0b10100000;
579 /// let res = 0b11101000;
581 /// let mut a = BitSet::from_bytes(&[a]);
582 /// let b = BitSet::from_bytes(&[b]);
583 /// let res = BitSet::from_bytes(&[res]);
585 /// a.union_with(&b);
586 /// assert_eq!(a, res);
589 pub fn union_with(&mut self, other: &Self) {
590 self.other_op(other, |w1, w2| w1 | w2);
593 /// Intersects in-place with the specified other bit vector.
598 /// use bit_set::BitSet;
600 /// let a = 0b01101000;
601 /// let b = 0b10100000;
602 /// let res = 0b00100000;
604 /// let mut a = BitSet::from_bytes(&[a]);
605 /// let b = BitSet::from_bytes(&[b]);
606 /// let res = BitSet::from_bytes(&[res]);
608 /// a.intersect_with(&b);
609 /// assert_eq!(a, res);
612 pub fn intersect_with(&mut self, other: &Self) {
613 self.other_op(other, |w1, w2| w1 & w2);
616 /// Makes this bit vector the difference with the specified other bit vector
622 /// use bit_set::BitSet;
624 /// let a = 0b01101000;
625 /// let b = 0b10100000;
626 /// let a_b = 0b01001000; // a - b
627 /// let b_a = 0b10000000; // b - a
629 /// let mut bva = BitSet::from_bytes(&[a]);
630 /// let bvb = BitSet::from_bytes(&[b]);
631 /// let bva_b = BitSet::from_bytes(&[a_b]);
632 /// let bvb_a = BitSet::from_bytes(&[b_a]);
634 /// bva.difference_with(&bvb);
635 /// assert_eq!(bva, bva_b);
637 /// let bva = BitSet::from_bytes(&[a]);
638 /// let mut bvb = BitSet::from_bytes(&[b]);
640 /// bvb.difference_with(&bva);
641 /// assert_eq!(bvb, bvb_a);
644 pub fn difference_with(&mut self, other: &Self) {
645 self.other_op(other, |w1, w2| w1 & !w2);
648 /// Makes this bit vector the symmetric difference with the specified other
649 /// bit vector in-place.
654 /// use bit_set::BitSet;
656 /// let a = 0b01101000;
657 /// let b = 0b10100000;
658 /// let res = 0b11001000;
660 /// let mut a = BitSet::from_bytes(&[a]);
661 /// let b = BitSet::from_bytes(&[b]);
662 /// let res = BitSet::from_bytes(&[res]);
664 /// a.symmetric_difference_with(&b);
665 /// assert_eq!(a, res);
668 pub fn symmetric_difference_with(&mut self, other: &Self) {
669 self.other_op(other, |w1, w2| w1 ^ w2);
673 /// Moves all elements from `other` into `Self`, leaving `other` empty.
678 /// use bit_set::BitSet;
680 /// let mut a = BitSet::new();
684 /// let mut b = BitSet::new();
689 /// a.append(&mut b);
691 /// assert_eq!(a.len(), 4);
692 /// assert_eq!(b.len(), 0);
693 /// assert_eq!(a, BitSet::from_bytes(&[0b01110010]));
695 pub fn append(&mut self, other: &mut Self) {
696 self.union_with(other);
700 /// Splits the `BitSet` into two at the given key including the key.
701 /// Retains the first part in-place while returning the second part.
706 /// use bit_set::BitSet;
708 /// let mut a = BitSet::new();
714 /// let b = a.split_off(3);
716 /// assert_eq!(a.len(), 2);
717 /// assert_eq!(b.len(), 2);
718 /// assert_eq!(a, BitSet::from_bytes(&[0b01100000]));
719 /// assert_eq!(b, BitSet::from_bytes(&[0b00010010]));
721 pub fn split_off(&mut self, at: usize) -> Self {
722 let mut other = BitSet::new();
725 swap(self, &mut other);
727 } else if at >= self.bit_vec.len() {
731 // Calculate block and bit at which to split
735 // Pad `other` with `w` zero blocks,
736 // append `self`'s blocks in the range from `w` to the end to `other`
737 other.bit_vec.storage_mut().extend(repeat(0u32).take(w)
738 .chain(self.bit_vec.storage()[w..].iter().cloned()));
739 other.bit_vec.nbits = self.bit_vec.nbits;
742 other.bit_vec.storage_mut()[w] &= !0 << b;
745 // Sets `bit_vec.len()` and fixes the last block as well
746 self.bit_vec.truncate(at);
752 /// Returns the number of set bits in this set.
754 pub fn len(&self) -> usize {
757 .fold(0, |acc, n| acc + n.count_ones() as usize)
760 /// Returns whether there are no bits set in this set
762 pub fn is_empty(&self) -> bool {
766 /// Clears all bits in this set
768 pub fn clear(&mut self) {
769 self.bit_vec.clear();
772 /// Returns `true` if this set contains the specified integer.
774 pub fn contains(&self, value: usize) -> bool {
775 let bit_vec = &self.bit_vec;
776 value < bit_vec.len() && bit_vec[value]
779 /// Returns `true` if the set has no elements in common with `other`.
780 /// This is equivalent to checking for an empty intersection.
782 pub fn is_disjoint(&self, other: &Self) -> bool {
783 self.intersection(other).next().is_none()
786 /// Returns `true` if the set is a subset of another.
788 pub fn is_subset(&self, other: &Self) -> bool {
789 let self_bit_vec = &self.bit_vec;
790 let other_bit_vec = &other.bit_vec;
791 let other_blocks = blocks_for_bits::<B>(other_bit_vec.len());
793 // Check that `self` intersect `other` is self
794 self_bit_vec.blocks().zip(other_bit_vec.blocks()).all(|(w1, w2)| w1 & w2 == w1) &&
795 // Make sure if `self` has any more blocks than `other`, they're all 0
796 self_bit_vec.blocks().skip(other_blocks).all(|w| w == B::zero())
799 /// Returns `true` if the set is a superset of another.
801 pub fn is_superset(&self, other: &Self) -> bool {
802 other.is_subset(self)
805 /// Adds a value to the set. Returns `true` if the value was not already
806 /// present in the set.
807 pub fn insert(&mut self, value: usize) -> bool {
808 if self.contains(value) {
812 // Ensure we have enough space to hold the new element
813 let len = self.bit_vec.len();
815 self.bit_vec.grow(value - len + 1, false)
818 self.bit_vec.set(value, true);
822 /// Removes a value from the set. Returns `true` if the value was
823 /// present in the set.
824 pub fn remove(&mut self, value: usize) -> bool {
825 if !self.contains(value) {
829 self.bit_vec.set(value, false);
835 impl<B: BitBlock> fmt::Debug for BitSet<B> {
836 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
837 fmt.debug_set().entries(self).finish()
841 impl<B: BitBlock> hash::Hash for BitSet<B> {
842 fn hash<H: hash::Hasher>(&self, state: &mut H) {
850 struct BlockIter<T, B> {
856 impl<T, B: BitBlock> BlockIter<T, B>
858 T: Iterator<Item = B>,
860 fn from_blocks(mut blocks: T) -> BlockIter<T, B> {
861 let h = blocks.next().unwrap_or_else(B::zero);
870 /// An iterator combining two `BitSet` iterators.
872 struct TwoBitPositions<'a, B: 'a> {
874 other: Blocks<'a, B>,
875 merge: fn(B, B) -> B,
878 /// An iterator for `BitSet`.
880 pub struct Iter<'a, B: 'a>(BlockIter<Blocks<'a, B>, B>);
882 pub struct Union<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
884 pub struct Intersection<'a, B: 'a>(Take<BlockIter<TwoBitPositions<'a, B>, B>>);
886 pub struct Difference<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
888 pub struct SymmetricDifference<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
890 impl<'a, T, B: BitBlock> Iterator for BlockIter<T, B>
892 T: Iterator<Item = B>,
896 fn next(&mut self) -> Option<usize> {
897 while self.head == B::zero() {
898 match self.tail.next() {
899 Some(w) => self.head = w,
902 self.head_offset += B::bits();
905 // from the current block, isolate the
906 // LSB and subtract 1, producing k:
907 // a block with a number of set bits
908 // equal to the index of the LSB
909 let k = (self.head & (!self.head + B::one())) - B::one();
910 // update block, removing the LSB
911 self.head = self.head & (self.head - B::one());
912 // return offset + (index of LSB)
913 Some(self.head_offset + (B::count_ones(k) as usize))
917 fn size_hint(&self) -> (usize, Option<usize>) {
918 match self.tail.size_hint() {
919 (_, Some(h)) => (0, Some(1 + h * B::bits())),
925 impl<'a, B: BitBlock> Iterator for TwoBitPositions<'a, B> {
928 fn next(&mut self) -> Option<B> {
929 match (self.set.next(), self.other.next()) {
930 (Some(a), Some(b)) => Some((self.merge)(a, b)),
931 (Some(a), None) => Some((self.merge)(a, B::zero())),
932 (None, Some(b)) => Some((self.merge)(B::zero(), b)),
938 fn size_hint(&self) -> (usize, Option<usize>) {
939 let (a, au) = self.set.size_hint();
940 let (b, bu) = self.other.size_hint();
942 let upper = match (au, bu) {
943 (Some(au), Some(bu)) => Some(cmp::max(au, bu)),
947 (cmp::max(a, b), upper)
951 impl<'a, B: BitBlock> Iterator for Iter<'a, B> {
955 fn next(&mut self) -> Option<usize> {
959 fn size_hint(&self) -> (usize, Option<usize>) {
964 impl<'a, B: BitBlock> Iterator for Union<'a, B> {
968 fn next(&mut self) -> Option<usize> {
972 fn size_hint(&self) -> (usize, Option<usize>) {
977 impl<'a, B: BitBlock> Iterator for Intersection<'a, B> {
981 fn next(&mut self) -> Option<usize> {
985 fn size_hint(&self) -> (usize, Option<usize>) {
990 impl<'a, B: BitBlock> Iterator for Difference<'a, B> {
994 fn next(&mut self) -> Option<usize> {
998 fn size_hint(&self) -> (usize, Option<usize>) {
1003 impl<'a, B: BitBlock> Iterator for SymmetricDifference<'a, B> {
1007 fn next(&mut self) -> Option<usize> {
1011 fn size_hint(&self) -> (usize, Option<usize>) {
1016 impl<'a, B: BitBlock> IntoIterator for &'a BitSet<B> {
1018 type IntoIter = Iter<'a, B>;
1020 fn into_iter(self) -> Iter<'a, B> {
1028 use bit_vec::BitVec;
1029 use std::cmp::Ordering::{Equal, Greater, Less};
1033 fn test_bit_set_show() {
1034 let mut s = BitSet::new();
1039 assert_eq!("{1, 2, 10, 50}", format!("{:?}", s));
1043 fn test_bit_set_from_usizes() {
1044 let usizes = vec![0, 2, 2, 3];
1045 let a: BitSet = usizes.into_iter().collect();
1046 let mut b = BitSet::new();
1054 fn test_bit_set_iterator() {
1055 let usizes = vec![0, 2, 2, 3];
1056 let bit_vec: BitSet = usizes.into_iter().collect();
1058 let idxs: Vec<_> = bit_vec.iter().collect();
1059 assert_eq!(idxs, [0, 2, 3]);
1061 let long: BitSet = (0..10000).filter(|&n| n % 2 == 0).collect();
1062 let real: Vec<_> = (0..10000 / 2).map(|x| x * 2).collect();
1064 let idxs: Vec<_> = long.iter().collect();
1065 assert_eq!(idxs, real);
1069 fn test_bit_set_frombit_vec_init() {
1070 let bools = [true, false];
1071 let lengths = [10, 64, 100];
1073 for &l in &lengths {
1074 let bitset = BitSet::from_bit_vec(BitVec::from_elem(l, b));
1075 assert_eq!(bitset.contains(1), b);
1076 assert_eq!(bitset.contains(l - 1), b);
1077 assert!(!bitset.contains(l));
1083 fn test_bit_vec_masking() {
1084 let b = BitVec::from_elem(140, true);
1085 let mut bs = BitSet::from_bit_vec(b);
1086 assert!(bs.contains(139));
1087 assert!(!bs.contains(140));
1088 assert!(bs.insert(150));
1089 assert!(!bs.contains(140));
1090 assert!(!bs.contains(149));
1091 assert!(bs.contains(150));
1092 assert!(!bs.contains(151));
1096 fn test_bit_set_basic() {
1097 let mut b = BitSet::new();
1098 assert!(b.insert(3));
1099 assert!(!b.insert(3));
1100 assert!(b.contains(3));
1101 assert!(b.insert(4));
1102 assert!(!b.insert(4));
1103 assert!(b.contains(3));
1104 assert!(b.insert(400));
1105 assert!(!b.insert(400));
1106 assert!(b.contains(400));
1107 assert_eq!(b.len(), 3);
1111 fn test_bit_set_intersection() {
1112 let mut a = BitSet::new();
1113 let mut b = BitSet::new();
1115 assert!(a.insert(11));
1116 assert!(a.insert(1));
1117 assert!(a.insert(3));
1118 assert!(a.insert(77));
1119 assert!(a.insert(103));
1120 assert!(a.insert(5));
1122 assert!(b.insert(2));
1123 assert!(b.insert(11));
1124 assert!(b.insert(77));
1125 assert!(b.insert(5));
1126 assert!(b.insert(3));
1128 let expected = [3, 5, 11, 77];
1129 let actual: Vec<_> = a.intersection(&b).collect();
1130 assert_eq!(actual, expected);
1134 fn test_bit_set_difference() {
1135 let mut a = BitSet::new();
1136 let mut b = BitSet::new();
1138 assert!(a.insert(1));
1139 assert!(a.insert(3));
1140 assert!(a.insert(5));
1141 assert!(a.insert(200));
1142 assert!(a.insert(500));
1144 assert!(b.insert(3));
1145 assert!(b.insert(200));
1147 let expected = [1, 5, 500];
1148 let actual: Vec<_> = a.difference(&b).collect();
1149 assert_eq!(actual, expected);
1153 fn test_bit_set_symmetric_difference() {
1154 let mut a = BitSet::new();
1155 let mut b = BitSet::new();
1157 assert!(a.insert(1));
1158 assert!(a.insert(3));
1159 assert!(a.insert(5));
1160 assert!(a.insert(9));
1161 assert!(a.insert(11));
1163 assert!(b.insert(3));
1164 assert!(b.insert(9));
1165 assert!(b.insert(14));
1166 assert!(b.insert(220));
1168 let expected = [1, 5, 11, 14, 220];
1169 let actual: Vec<_> = a.symmetric_difference(&b).collect();
1170 assert_eq!(actual, expected);
1174 fn test_bit_set_union() {
1175 let mut a = BitSet::new();
1176 let mut b = BitSet::new();
1177 assert!(a.insert(1));
1178 assert!(a.insert(3));
1179 assert!(a.insert(5));
1180 assert!(a.insert(9));
1181 assert!(a.insert(11));
1182 assert!(a.insert(160));
1183 assert!(a.insert(19));
1184 assert!(a.insert(24));
1185 assert!(a.insert(200));
1187 assert!(b.insert(1));
1188 assert!(b.insert(5));
1189 assert!(b.insert(9));
1190 assert!(b.insert(13));
1191 assert!(b.insert(19));
1193 let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160, 200];
1194 let actual: Vec<_> = a.union(&b).collect();
1195 assert_eq!(actual, expected);
1199 fn test_bit_set_subset() {
1200 let mut set1 = BitSet::new();
1201 let mut set2 = BitSet::new();
1203 assert!(set1.is_subset(&set2)); // {} {}
1205 assert!(set1.is_subset(&set2)); // {} { 1 }
1207 assert!(set1.is_subset(&set2)); // {} { 1, 2 }
1209 assert!(set1.is_subset(&set2)); // { 2 } { 1, 2 }
1211 assert!(!set1.is_subset(&set2)); // { 2, 3 } { 1, 2 }
1213 assert!(set1.is_subset(&set2)); // { 2, 3 } { 1, 2, 3 }
1215 assert!(set1.is_subset(&set2)); // { 2, 3 } { 1, 2, 3, 4 }
1217 assert!(set1.is_subset(&set2)); // { 2, 3 } { 2, 3, 4 }
1219 assert!(!set1.is_subset(&set2)); // { 2, 3 } { 2, 4 }
1221 assert!(set1.is_subset(&set2)); // { 2 } { 2, 4 }
1225 fn test_bit_set_is_disjoint() {
1226 let a = BitSet::from_bytes(&[0b10100010]);
1227 let b = BitSet::from_bytes(&[0b01000000]);
1228 let c = BitSet::new();
1229 let d = BitSet::from_bytes(&[0b00110000]);
1231 assert!(!a.is_disjoint(&d));
1232 assert!(!d.is_disjoint(&a));
1234 assert!(a.is_disjoint(&b));
1235 assert!(a.is_disjoint(&c));
1236 assert!(b.is_disjoint(&a));
1237 assert!(b.is_disjoint(&c));
1238 assert!(c.is_disjoint(&a));
1239 assert!(c.is_disjoint(&b));
1243 fn test_bit_set_union_with() {
1244 //a should grow to include larger elements
1245 let mut a = BitSet::new();
1247 let mut b = BitSet::new();
1249 let expected = BitSet::from_bytes(&[0b10000100]);
1251 assert_eq!(a, expected);
1254 let mut a = BitSet::from_bytes(&[0b10100010]);
1255 let mut b = BitSet::from_bytes(&[0b01100010]);
1259 assert_eq!(a.len(), 4);
1260 assert_eq!(b.len(), 4);
1264 fn test_bit_set_intersect_with() {
1265 // Explicitly 0'ed bits
1266 let mut a = BitSet::from_bytes(&[0b10100010]);
1267 let mut b = BitSet::from_bytes(&[0b00000000]);
1269 a.intersect_with(&b);
1270 b.intersect_with(&c);
1271 assert!(a.is_empty());
1272 assert!(b.is_empty());
1274 // Uninitialized bits should behave like 0's
1275 let mut a = BitSet::from_bytes(&[0b10100010]);
1276 let mut b = BitSet::new();
1278 a.intersect_with(&b);
1279 b.intersect_with(&c);
1280 assert!(a.is_empty());
1281 assert!(b.is_empty());
1284 let mut a = BitSet::from_bytes(&[0b10100010]);
1285 let mut b = BitSet::from_bytes(&[0b01100010]);
1287 a.intersect_with(&b);
1288 b.intersect_with(&c);
1289 assert_eq!(a.len(), 2);
1290 assert_eq!(b.len(), 2);
1294 fn test_bit_set_difference_with() {
1295 // Explicitly 0'ed bits
1296 let mut a = BitSet::from_bytes(&[0b00000000]);
1297 let b = BitSet::from_bytes(&[0b10100010]);
1298 a.difference_with(&b);
1299 assert!(a.is_empty());
1301 // Uninitialized bits should behave like 0's
1302 let mut a = BitSet::new();
1303 let b = BitSet::from_bytes(&[0b11111111]);
1304 a.difference_with(&b);
1305 assert!(a.is_empty());
1308 let mut a = BitSet::from_bytes(&[0b10100010]);
1309 let mut b = BitSet::from_bytes(&[0b01100010]);
1311 a.difference_with(&b);
1312 b.difference_with(&c);
1313 assert_eq!(a.len(), 1);
1314 assert_eq!(b.len(), 1);
1318 fn test_bit_set_symmetric_difference_with() {
1319 //a should grow to include larger elements
1320 let mut a = BitSet::new();
1323 let mut b = BitSet::new();
1326 let expected = BitSet::from_bytes(&[0b10000100]);
1327 a.symmetric_difference_with(&b);
1328 assert_eq!(a, expected);
1330 let mut a = BitSet::from_bytes(&[0b10100010]);
1331 let b = BitSet::new();
1333 a.symmetric_difference_with(&b);
1337 let mut a = BitSet::from_bytes(&[0b11100010]);
1338 let mut b = BitSet::from_bytes(&[0b01101010]);
1340 a.symmetric_difference_with(&b);
1341 b.symmetric_difference_with(&c);
1342 assert_eq!(a.len(), 2);
1343 assert_eq!(b.len(), 2);
1347 fn test_bit_set_eq() {
1348 let a = BitSet::from_bytes(&[0b10100010]);
1349 let b = BitSet::from_bytes(&[0b00000000]);
1350 let c = BitSet::new();
1361 fn test_bit_set_cmp() {
1362 let a = BitSet::from_bytes(&[0b10100010]);
1363 let b = BitSet::from_bytes(&[0b00000000]);
1364 let c = BitSet::new();
1366 assert_eq!(a.cmp(&b), Greater);
1367 assert_eq!(a.cmp(&c), Greater);
1368 assert_eq!(b.cmp(&a), Less);
1369 assert_eq!(b.cmp(&c), Equal);
1370 assert_eq!(c.cmp(&a), Less);
1371 assert_eq!(c.cmp(&b), Equal);
1375 fn test_bit_vec_remove() {
1376 let mut a = BitSet::new();
1378 assert!(a.insert(1));
1379 assert!(a.remove(1));
1381 assert!(a.insert(100));
1382 assert!(a.remove(100));
1384 assert!(a.insert(1000));
1385 assert!(a.remove(1000));
1390 fn test_bit_vec_clone() {
1391 let mut a = BitSet::new();
1393 assert!(a.insert(1));
1394 assert!(a.insert(100));
1395 assert!(a.insert(1000));
1397 let mut b = a.clone();
1401 assert!(b.remove(1));
1402 assert!(a.contains(1));
1404 assert!(a.remove(1000));
1405 assert!(b.contains(1000));
1410 fn test_bit_set_append() {
1411 let mut a = BitSet::new();
1415 let mut b = BitSet::new();
1422 assert_eq!(a.len(), 4);
1423 assert_eq!(b.len(), 0);
1424 assert!(b.capacity() >= 6);
1426 assert_eq!(a, BitSet::from_bytes(&[0b01110010]));
1430 fn test_bit_set_split_off() {
1432 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1433 0b00110011, 0b01101011, 0b10101101]);
1435 let b = a.split_off(0);
1437 assert_eq!(a.len(), 0);
1438 assert_eq!(b.len(), 21);
1440 assert_eq!(b, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1441 0b00110011, 0b01101011, 0b10101101]);
1443 // Split behind last element
1444 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1445 0b00110011, 0b01101011, 0b10101101]);
1447 let b = a.split_off(50);
1449 assert_eq!(a.len(), 21);
1450 assert_eq!(b.len(), 0);
1452 assert_eq!(a, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1453 0b00110011, 0b01101011, 0b10101101]));
1455 // Split at arbitrary element
1456 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1457 0b00110011, 0b01101011, 0b10101101]);
1459 let b = a.split_off(34);
1461 assert_eq!(a.len(), 12);
1462 assert_eq!(b.len(), 9);
1464 assert_eq!(a, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1465 0b00110011, 0b01000000]));
1466 assert_eq!(b, BitSet::from_bytes(&[0, 0, 0, 0,
1467 0b00101011, 0b10101101]));
1472 #[cfg(all(test, feature = "nightly"))]
1475 use bit_vec::BitVec;
1476 use rand::{thread_rng, Rng, ThreadRng};
1478 use test::{black_box, Bencher};
1480 const BENCH_BITS: usize = 1 << 14;
1481 const BITS: usize = 32;
1483 fn rng() -> ThreadRng {
1488 fn bench_bit_vecset_small(b: &mut Bencher) {
1490 let mut bit_vec = BitSet::new();
1493 bit_vec.insert((r.next_u32() as usize) % BITS);
1495 black_box(&bit_vec);
1500 fn bench_bit_vecset_big(b: &mut Bencher) {
1502 let mut bit_vec = BitSet::new();
1505 bit_vec.insert((r.next_u32() as usize) % BENCH_BITS);
1507 black_box(&bit_vec);
1512 fn bench_bit_vecset_iter(b: &mut Bencher) {
1513 let bit_vec = BitSet::from_bit_vec(BitVec::from_fn(BENCH_BITS, |idx| idx % 3 == 0));
1516 for idx in &bit_vec {
1517 sum += idx as usize;