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();
50 #![cfg_attr(all(test, feature = "nightly"), feature(test))]
51 #[cfg(all(test, feature = "nightly"))] extern crate test;
52 #[cfg(all(test, feature = "nightly"))] extern crate rand;
55 use bit_vec::{BitVec, Blocks, BitBlock};
56 use std::cmp::Ordering;
60 use std::iter::{self, Chain, Enumerate, FromIterator, Repeat, Skip, Take};
62 type MatchWords<'a, B> = Chain<Enumerate<Blocks<'a, B>>, Skip<Take<Enumerate<Repeat<B>>>>>;
64 /// Computes how many blocks are needed to store that many bits
65 fn blocks_for_bits<B: BitBlock>(bits: usize) -> usize {
66 // If we want 17 bits, dividing by 32 will produce 0. So we add 1 to make sure we
67 // reserve enough. But if we want exactly a multiple of 32, this will actually allocate
68 // one too many. So we need to check if that's the case. We can do that by computing if
69 // bitwise AND by `32 - 1` is 0. But LLVM should be able to optimize the semantically
70 // superior modulo operator on a power of two to this.
72 // Note that we can technically avoid this branch with the expression
73 // `(nbits + BITS - 1) / 32::BITS`, but if nbits is almost usize::MAX this will overflow.
74 if bits % B::bits() == 0 {
81 // Take two BitVec's, and return iterators of their words, where the shorter one
82 // has been padded with 0's
83 fn match_words<'a, 'b, B: BitBlock>(a: &'a BitVec<B>, b: &'b BitVec<B>)
84 -> (MatchWords<'a, B>, MatchWords<'b, B>)
86 let a_len = a.storage().len();
87 let b_len = b.storage().len();
89 // have to uselessly pretend to pad the longer one for type matching
91 (a.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(b_len).skip(a_len)),
92 b.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(0).skip(0)))
94 (a.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(0).skip(0)),
95 b.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(a_len).skip(b_len)))
99 pub struct BitSet<B = u32> {
103 impl<B: BitBlock> Clone for BitSet<B> {
104 fn clone(&self) -> Self {
106 bit_vec: self.bit_vec.clone(),
111 impl<B: BitBlock> Default for BitSet<B> {
113 fn default() -> Self { BitSet { bit_vec: Default::default() } }
116 impl<B: BitBlock> FromIterator<usize> for BitSet<B> {
117 fn from_iter<I: IntoIterator<Item = usize>>(iter: I) -> Self {
118 let mut ret = Self::default();
124 impl<B: BitBlock> Extend<usize> for BitSet<B> {
126 fn extend<I: IntoIterator<Item = usize>>(&mut self, iter: I) {
133 impl<B: BitBlock> PartialOrd for BitSet<B> {
135 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
136 self.iter().partial_cmp(other)
140 impl<B: BitBlock> Ord for BitSet<B> {
142 fn cmp(&self, other: &Self) -> Ordering {
143 self.iter().cmp(other)
147 impl<B: BitBlock> PartialEq for BitSet<B> {
149 fn eq(&self, other: &Self) -> bool {
150 self.iter().eq(other)
154 impl<B: BitBlock> Eq for BitSet<B> {}
157 /// Creates a new empty `BitSet`.
162 /// use bit_set::BitSet;
164 /// let mut s = BitSet::new();
167 pub fn new() -> Self {
171 /// Creates a new `BitSet` with initially no contents, able to
172 /// hold `nbits` elements without resizing.
177 /// use bit_set::BitSet;
179 /// let mut s = BitSet::with_capacity(100);
180 /// assert!(s.capacity() >= 100);
183 pub fn with_capacity(nbits: usize) -> Self {
184 let bit_vec = BitVec::from_elem(nbits, false);
185 Self::from_bit_vec(bit_vec)
188 /// Creates a new `BitSet` from the given bit vector.
193 /// extern crate bit_vec;
194 /// extern crate bit_set;
197 /// use bit_vec::BitVec;
198 /// use bit_set::BitSet;
200 /// let bv = BitVec::from_bytes(&[0b01100000]);
201 /// let s = BitSet::from_bit_vec(bv);
203 /// // Print 1, 2 in arbitrary order
204 /// for x in s.iter() {
205 /// println!("{}", x);
210 pub fn from_bit_vec(bit_vec: BitVec) -> Self {
211 BitSet { bit_vec: bit_vec }
214 pub fn from_bytes(bytes: &[u8]) -> Self {
215 BitSet { bit_vec: BitVec::from_bytes(bytes) }
219 impl<B: BitBlock> BitSet<B> {
221 /// Returns the capacity in bits for this bit vector. Inserting any
222 /// element less than this amount will not trigger a resizing.
227 /// use bit_set::BitSet;
229 /// let mut s = BitSet::with_capacity(100);
230 /// assert!(s.capacity() >= 100);
233 pub fn capacity(&self) -> usize {
234 self.bit_vec.capacity()
237 /// Reserves capacity for the given `BitSet` to contain `len` distinct elements. In the case
238 /// of `BitSet` this means reallocations will not occur as long as all inserted elements
239 /// are less than `len`.
241 /// The collection may reserve more space to avoid frequent reallocations.
247 /// use bit_set::BitSet;
249 /// let mut s = BitSet::new();
250 /// s.reserve_len(10);
251 /// assert!(s.capacity() >= 10);
253 pub fn reserve_len(&mut self, len: usize) {
254 let cur_len = self.bit_vec.len();
256 self.bit_vec.reserve(len - cur_len);
260 /// Reserves the minimum capacity for the given `BitSet` to contain `len` distinct elements.
261 /// In the case of `BitSet` this means reallocations will not occur as long as all inserted
262 /// elements are less than `len`.
264 /// Note that the allocator may give the collection more space than it requests. Therefore
265 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve_len` if future
266 /// insertions are expected.
272 /// use bit_set::BitSet;
274 /// let mut s = BitSet::new();
275 /// s.reserve_len_exact(10);
276 /// assert!(s.capacity() >= 10);
278 pub fn reserve_len_exact(&mut self, len: usize) {
279 let cur_len = self.bit_vec.len();
281 self.bit_vec.reserve_exact(len - cur_len);
285 /// Consumes this set to return the underlying bit vector.
290 /// use bit_set::BitSet;
292 /// let mut s = BitSet::new();
296 /// let bv = s.into_bit_vec();
301 pub fn into_bit_vec(self) -> BitVec<B> {
305 /// Returns a reference to the underlying bit vector.
310 /// use bit_set::BitSet;
312 /// let mut s = BitSet::new();
315 /// let bv = s.get_ref();
316 /// assert_eq!(bv[0], true);
319 pub fn get_ref(&self) -> &BitVec<B> {
324 fn other_op<F>(&mut self, other: &Self, mut f: F) where F: FnMut(B, B) -> B {
326 let self_bit_vec = &mut self.bit_vec;
327 let other_bit_vec = &other.bit_vec;
329 let self_len = self_bit_vec.len();
330 let other_len = other_bit_vec.len();
332 // Expand the vector if necessary
333 if self_len < other_len {
334 self_bit_vec.grow(other_len - self_len, false);
337 // virtually pad other with 0's for equal lengths
339 let (_, result) = match_words(self_bit_vec, other_bit_vec);
343 // Apply values found in other
344 for (i, w) in other_words {
345 let old = self_bit_vec.storage()[i];
348 self_bit_vec.storage_mut()[i] = new;
353 /// Truncates the underlying vector to the least length required.
358 /// use bit_set::BitSet;
360 /// let mut s = BitSet::new();
361 /// s.insert(32183231);
362 /// s.remove(32183231);
364 /// // Internal storage will probably be bigger than necessary
365 /// println!("old capacity: {}", s.capacity());
367 /// // Now should be smaller
368 /// s.shrink_to_fit();
369 /// println!("new capacity: {}", s.capacity());
372 pub fn shrink_to_fit(&mut self) {
373 let bit_vec = &mut self.bit_vec;
374 // Obtain original length
375 let old_len = bit_vec.storage().len();
376 // Obtain coarse trailing zero length
377 let n = bit_vec.storage().iter().rev().take_while(|&&n| n == B::zero()).count();
379 let trunc_len = cmp::max(old_len - n, 1);
381 bit_vec.storage_mut().truncate(trunc_len);
382 bit_vec.set_len(trunc_len * B::bits());
386 /// Iterator over each usize stored in the `BitSet`.
391 /// use bit_set::BitSet;
393 /// let s = BitSet::from_bytes(&[0b01001010]);
395 /// // Print 1, 4, 6 in arbitrary order
396 /// for x in s.iter() {
397 /// println!("{}", x);
401 pub fn iter(&self) -> Iter<B> {
402 Iter(BlockIter::from_blocks(self.bit_vec.blocks()))
405 /// Iterator over each usize stored in `self` union `other`.
406 /// See [union_with](#method.union_with) for an efficient in-place version.
411 /// use bit_set::BitSet;
413 /// let a = BitSet::from_bytes(&[0b01101000]);
414 /// let b = BitSet::from_bytes(&[0b10100000]);
416 /// // Print 0, 1, 2, 4 in arbitrary order
417 /// for x in a.union(&b) {
418 /// println!("{}", x);
422 pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, B> {
423 fn or<B: BitBlock>(w1: B, w2: B) -> B { w1 | w2 }
425 Union(BlockIter::from_blocks(TwoBitPositions {
426 set: self.bit_vec.blocks(),
427 other: other.bit_vec.blocks(),
432 /// Iterator over each usize stored in `self` intersect `other`.
433 /// See [intersect_with](#method.intersect_with) for an efficient in-place version.
438 /// use bit_set::BitSet;
440 /// let a = BitSet::from_bytes(&[0b01101000]);
441 /// let b = BitSet::from_bytes(&[0b10100000]);
444 /// for x in a.intersection(&b) {
445 /// println!("{}", x);
449 pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, B> {
450 fn bitand<B: BitBlock>(w1: B, w2: B) -> B { w1 & w2 }
451 let min = cmp::min(self.bit_vec.len(), other.bit_vec.len());
453 Intersection(BlockIter::from_blocks(TwoBitPositions {
454 set: self.bit_vec.blocks(),
455 other: other.bit_vec.blocks(),
460 /// Iterator over each usize stored in the `self` setminus `other`.
461 /// See [difference_with](#method.difference_with) for an efficient in-place version.
466 /// use bit_set::BitSet;
468 /// let a = BitSet::from_bytes(&[0b01101000]);
469 /// let b = BitSet::from_bytes(&[0b10100000]);
471 /// // Print 1, 4 in arbitrary order
472 /// for x in a.difference(&b) {
473 /// println!("{}", x);
476 /// // Note that difference is not symmetric,
477 /// // and `b - a` means something else.
479 /// for x in b.difference(&a) {
480 /// println!("{}", x);
484 pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, B> {
485 fn diff<B: BitBlock>(w1: B, w2: B) -> B { w1 & !w2 }
487 Difference(BlockIter::from_blocks(TwoBitPositions {
488 set: self.bit_vec.blocks(),
489 other: other.bit_vec.blocks(),
494 /// Iterator over each usize stored in the symmetric difference of `self` and `other`.
495 /// See [symmetric_difference_with](#method.symmetric_difference_with) for
496 /// an efficient in-place version.
501 /// use bit_set::BitSet;
503 /// let a = BitSet::from_bytes(&[0b01101000]);
504 /// let b = BitSet::from_bytes(&[0b10100000]);
506 /// // Print 0, 1, 4 in arbitrary order
507 /// for x in a.symmetric_difference(&b) {
508 /// println!("{}", x);
512 pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> SymmetricDifference<'a, B> {
513 fn bitxor<B: BitBlock>(w1: B, w2: B) -> B { w1 ^ w2 }
515 SymmetricDifference(BlockIter::from_blocks(TwoBitPositions {
516 set: self.bit_vec.blocks(),
517 other: other.bit_vec.blocks(),
522 /// Unions in-place with the specified other bit vector.
527 /// use bit_set::BitSet;
529 /// let a = 0b01101000;
530 /// let b = 0b10100000;
531 /// let res = 0b11101000;
533 /// let mut a = BitSet::from_bytes(&[a]);
534 /// let b = BitSet::from_bytes(&[b]);
535 /// let res = BitSet::from_bytes(&[res]);
537 /// a.union_with(&b);
538 /// assert_eq!(a, res);
541 pub fn union_with(&mut self, other: &Self) {
542 self.other_op(other, |w1, w2| w1 | w2);
545 /// Intersects in-place with the specified other bit vector.
550 /// use bit_set::BitSet;
552 /// let a = 0b01101000;
553 /// let b = 0b10100000;
554 /// let res = 0b00100000;
556 /// let mut a = BitSet::from_bytes(&[a]);
557 /// let b = BitSet::from_bytes(&[b]);
558 /// let res = BitSet::from_bytes(&[res]);
560 /// a.intersect_with(&b);
561 /// assert_eq!(a, res);
564 pub fn intersect_with(&mut self, other: &Self) {
565 self.other_op(other, |w1, w2| w1 & w2);
568 /// Makes this bit vector the difference with the specified other bit vector
574 /// use bit_set::BitSet;
576 /// let a = 0b01101000;
577 /// let b = 0b10100000;
578 /// let a_b = 0b01001000; // a - b
579 /// let b_a = 0b10000000; // b - a
581 /// let mut bva = BitSet::from_bytes(&[a]);
582 /// let bvb = BitSet::from_bytes(&[b]);
583 /// let bva_b = BitSet::from_bytes(&[a_b]);
584 /// let bvb_a = BitSet::from_bytes(&[b_a]);
586 /// bva.difference_with(&bvb);
587 /// assert_eq!(bva, bva_b);
589 /// let bva = BitSet::from_bytes(&[a]);
590 /// let mut bvb = BitSet::from_bytes(&[b]);
592 /// bvb.difference_with(&bva);
593 /// assert_eq!(bvb, bvb_a);
596 pub fn difference_with(&mut self, other: &Self) {
597 self.other_op(other, |w1, w2| w1 & !w2);
600 /// Makes this bit vector the symmetric difference with the specified other
601 /// bit vector in-place.
606 /// use bit_set::BitSet;
608 /// let a = 0b01101000;
609 /// let b = 0b10100000;
610 /// let res = 0b11001000;
612 /// let mut a = BitSet::from_bytes(&[a]);
613 /// let b = BitSet::from_bytes(&[b]);
614 /// let res = BitSet::from_bytes(&[res]);
616 /// a.symmetric_difference_with(&b);
617 /// assert_eq!(a, res);
620 pub fn symmetric_difference_with(&mut self, other: &Self) {
621 self.other_op(other, |w1, w2| w1 ^ w2);
625 /// Moves all elements from `other` into `Self`, leaving `other` empty.
630 /// use bit_set::BitSet;
632 /// let mut a = BitSet::new();
636 /// let mut b = BitSet::new();
641 /// a.append(&mut b);
643 /// assert_eq!(a.len(), 4);
644 /// assert_eq!(b.len(), 0);
645 /// assert_eq!(a, BitSet::from_bytes(&[0b01110010]));
647 pub fn append(&mut self, other: &mut Self) {
648 self.union_with(other);
652 /// Splits the `BitSet` into two at the given key including the key.
653 /// Retains the first part in-place while returning the second part.
658 /// use bit_set::BitSet;
660 /// let mut a = BitSet::new();
666 /// let b = a.split_off(3);
668 /// assert_eq!(a.len(), 2);
669 /// assert_eq!(b.len(), 2);
670 /// assert_eq!(a, BitSet::from_bytes(&[0b01100000]));
671 /// assert_eq!(b, BitSet::from_bytes(&[0b00010010]));
673 pub fn split_off(&mut self, at: usize) -> Self {
674 let mut other = BitSet::new();
677 swap(self, &mut other);
679 } else if at >= self.bit_vec.len() {
683 // Calculate block and bit at which to split
687 // Pad `other` with `w` zero blocks,
688 // append `self`'s blocks in the range from `w` to the end to `other`
689 other.bit_vec.storage_mut().extend(repeat(0u32).take(w)
690 .chain(self.bit_vec.storage()[w..].iter().cloned()));
691 other.bit_vec.nbits = self.bit_vec.nbits;
694 other.bit_vec.storage_mut()[w] &= !0 << b;
697 // Sets `bit_vec.len()` and fixes the last block as well
698 self.bit_vec.truncate(at);
704 /// Returns the number of set bits in this set.
706 pub fn len(&self) -> usize {
707 self.bit_vec.blocks().fold(0, |acc, n| acc + n.count_ones() as usize)
710 /// Returns whether there are no bits set in this set
712 pub fn is_empty(&self) -> bool {
716 /// Clears all bits in this set
718 pub fn clear(&mut self) {
719 self.bit_vec.clear();
722 /// Returns `true` if this set contains the specified integer.
724 pub fn contains(&self, value: usize) -> bool {
725 let bit_vec = &self.bit_vec;
726 value < bit_vec.len() && bit_vec[value]
729 /// Returns `true` if the set has no elements in common with `other`.
730 /// This is equivalent to checking for an empty intersection.
732 pub fn is_disjoint(&self, other: &Self) -> bool {
733 self.intersection(other).next().is_none()
736 /// Returns `true` if the set is a subset of another.
738 pub fn is_subset(&self, other: &Self) -> bool {
739 let self_bit_vec = &self.bit_vec;
740 let other_bit_vec = &other.bit_vec;
741 let other_blocks = blocks_for_bits::<B>(other_bit_vec.len());
743 // Check that `self` intersect `other` is self
744 self_bit_vec.blocks().zip(other_bit_vec.blocks()).all(|(w1, w2)| w1 & w2 == w1) &&
745 // Make sure if `self` has any more blocks than `other`, they're all 0
746 self_bit_vec.blocks().skip(other_blocks).all(|w| w == B::zero())
749 /// Returns `true` if the set is a superset of another.
751 pub fn is_superset(&self, other: &Self) -> bool {
752 other.is_subset(self)
755 /// Adds a value to the set. Returns `true` if the value was not already
756 /// present in the set.
757 pub fn insert(&mut self, value: usize) -> bool {
758 if self.contains(value) {
762 // Ensure we have enough space to hold the new element
763 let len = self.bit_vec.len();
765 self.bit_vec.grow(value - len + 1, false)
768 self.bit_vec.set(value, true);
772 /// Removes a value from the set. Returns `true` if the value was
773 /// present in the set.
774 pub fn remove(&mut self, value: usize) -> bool {
775 if !self.contains(value) {
779 self.bit_vec.set(value, false);
785 impl<B: BitBlock> fmt::Debug for BitSet<B> {
786 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
787 fmt.debug_set().entries(self).finish()
791 impl<B: BitBlock> hash::Hash for BitSet<B> {
792 fn hash<H: hash::Hasher>(&self, state: &mut H) {
800 struct BlockIter<T, B> {
806 impl<T, B: BitBlock> BlockIter<T, B> where T: Iterator<Item=B> {
807 fn from_blocks(mut blocks: T) -> BlockIter<T, B> {
808 let h = blocks.next().unwrap_or(B::zero());
809 BlockIter {tail: blocks, head: h, head_offset: 0}
813 /// An iterator combining two `BitSet` iterators.
815 struct TwoBitPositions<'a, B: 'a> {
817 other: Blocks<'a, B>,
818 merge: fn(B, B) -> B,
821 /// An iterator for `BitSet`.
823 pub struct Iter<'a, B: 'a>(BlockIter<Blocks<'a, B>, B>);
825 pub struct Union<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
827 pub struct Intersection<'a, B: 'a>(Take<BlockIter<TwoBitPositions<'a, B>, B>>);
829 pub struct Difference<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
831 pub struct SymmetricDifference<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
833 impl<'a, T, B: BitBlock> Iterator for BlockIter<T, B> where T: Iterator<Item=B> {
836 fn next(&mut self) -> Option<usize> {
837 while self.head == B::zero() {
838 match self.tail.next() {
839 Some(w) => self.head = w,
842 self.head_offset += B::bits();
845 // from the current block, isolate the
846 // LSB and subtract 1, producing k:
847 // a block with a number of set bits
848 // equal to the index of the LSB
849 let k = (self.head & (!self.head + B::one())) - B::one();
850 // update block, removing the LSB
851 self.head = self.head & (self.head - B::one());
852 // return offset + (index of LSB)
853 Some(self.head_offset + (B::count_ones(k) as usize))
857 fn size_hint(&self) -> (usize, Option<usize>) {
858 match self.tail.size_hint() {
859 (_, Some(h)) => (0, Some(1 + h * B::bits())),
865 impl<'a, B: BitBlock> Iterator for TwoBitPositions<'a, B> {
868 fn next(&mut self) -> Option<B> {
869 match (self.set.next(), self.other.next()) {
870 (Some(a), Some(b)) => Some((self.merge)(a, b)),
871 (Some(a), None) => Some((self.merge)(a, B::zero())),
872 (None, Some(b)) => Some((self.merge)(B::zero(), b)),
878 fn size_hint(&self) -> (usize, Option<usize>) {
879 let (a, au) = self.set.size_hint();
880 let (b, bu) = self.other.size_hint();
882 let upper = match (au, bu) {
883 (Some(au), Some(bu)) => Some(cmp::max(au, bu)),
887 (cmp::max(a, b), upper)
891 impl<'a, B: BitBlock> Iterator for Iter<'a, B> {
894 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
895 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
898 impl<'a, B: BitBlock> Iterator for Union<'a, B> {
901 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
902 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
905 impl<'a, B: BitBlock> Iterator for Intersection<'a, B> {
908 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
909 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
912 impl<'a, B: BitBlock> Iterator for Difference<'a, B> {
915 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
916 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
919 impl<'a, B: BitBlock> Iterator for SymmetricDifference<'a, B> {
922 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
923 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
926 impl<'a, B: BitBlock> IntoIterator for &'a BitSet<B> {
928 type IntoIter = Iter<'a, B>;
930 fn into_iter(self) -> Iter<'a, B> {
937 use std::cmp::Ordering::{Equal, Greater, Less};
942 fn test_bit_set_show() {
943 let mut s = BitSet::new();
948 assert_eq!("{1, 2, 10, 50}", format!("{:?}", s));
952 fn test_bit_set_from_usizes() {
953 let usizes = vec![0, 2, 2, 3];
954 let a: BitSet = usizes.into_iter().collect();
955 let mut b = BitSet::new();
963 fn test_bit_set_iterator() {
964 let usizes = vec![0, 2, 2, 3];
965 let bit_vec: BitSet = usizes.into_iter().collect();
967 let idxs: Vec<_> = bit_vec.iter().collect();
968 assert_eq!(idxs, [0, 2, 3]);
970 let long: BitSet = (0..10000).filter(|&n| n % 2 == 0).collect();
971 let real: Vec<_> = (0..10000/2).map(|x| x*2).collect();
973 let idxs: Vec<_> = long.iter().collect();
974 assert_eq!(idxs, real);
978 fn test_bit_set_frombit_vec_init() {
979 let bools = [true, false];
980 let lengths = [10, 64, 100];
983 let bitset = BitSet::from_bit_vec(BitVec::from_elem(l, b));
984 assert_eq!(bitset.contains(1), b);
985 assert_eq!(bitset.contains((l-1)), b);
986 assert!(!bitset.contains(l));
992 fn test_bit_vec_masking() {
993 let b = BitVec::from_elem(140, true);
994 let mut bs = BitSet::from_bit_vec(b);
995 assert!(bs.contains(139));
996 assert!(!bs.contains(140));
997 assert!(bs.insert(150));
998 assert!(!bs.contains(140));
999 assert!(!bs.contains(149));
1000 assert!(bs.contains(150));
1001 assert!(!bs.contains(151));
1005 fn test_bit_set_basic() {
1006 let mut b = BitSet::new();
1007 assert!(b.insert(3));
1008 assert!(!b.insert(3));
1009 assert!(b.contains(3));
1010 assert!(b.insert(4));
1011 assert!(!b.insert(4));
1012 assert!(b.contains(3));
1013 assert!(b.insert(400));
1014 assert!(!b.insert(400));
1015 assert!(b.contains(400));
1016 assert_eq!(b.len(), 3);
1020 fn test_bit_set_intersection() {
1021 let mut a = BitSet::new();
1022 let mut b = BitSet::new();
1024 assert!(a.insert(11));
1025 assert!(a.insert(1));
1026 assert!(a.insert(3));
1027 assert!(a.insert(77));
1028 assert!(a.insert(103));
1029 assert!(a.insert(5));
1031 assert!(b.insert(2));
1032 assert!(b.insert(11));
1033 assert!(b.insert(77));
1034 assert!(b.insert(5));
1035 assert!(b.insert(3));
1037 let expected = [3, 5, 11, 77];
1038 let actual: Vec<_> = a.intersection(&b).collect();
1039 assert_eq!(actual, expected);
1043 fn test_bit_set_difference() {
1044 let mut a = BitSet::new();
1045 let mut b = BitSet::new();
1047 assert!(a.insert(1));
1048 assert!(a.insert(3));
1049 assert!(a.insert(5));
1050 assert!(a.insert(200));
1051 assert!(a.insert(500));
1053 assert!(b.insert(3));
1054 assert!(b.insert(200));
1056 let expected = [1, 5, 500];
1057 let actual: Vec<_> = a.difference(&b).collect();
1058 assert_eq!(actual, expected);
1062 fn test_bit_set_symmetric_difference() {
1063 let mut a = BitSet::new();
1064 let mut b = BitSet::new();
1066 assert!(a.insert(1));
1067 assert!(a.insert(3));
1068 assert!(a.insert(5));
1069 assert!(a.insert(9));
1070 assert!(a.insert(11));
1072 assert!(b.insert(3));
1073 assert!(b.insert(9));
1074 assert!(b.insert(14));
1075 assert!(b.insert(220));
1077 let expected = [1, 5, 11, 14, 220];
1078 let actual: Vec<_> = a.symmetric_difference(&b).collect();
1079 assert_eq!(actual, expected);
1083 fn test_bit_set_union() {
1084 let mut a = BitSet::new();
1085 let mut b = BitSet::new();
1086 assert!(a.insert(1));
1087 assert!(a.insert(3));
1088 assert!(a.insert(5));
1089 assert!(a.insert(9));
1090 assert!(a.insert(11));
1091 assert!(a.insert(160));
1092 assert!(a.insert(19));
1093 assert!(a.insert(24));
1094 assert!(a.insert(200));
1096 assert!(b.insert(1));
1097 assert!(b.insert(5));
1098 assert!(b.insert(9));
1099 assert!(b.insert(13));
1100 assert!(b.insert(19));
1102 let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160, 200];
1103 let actual: Vec<_> = a.union(&b).collect();
1104 assert_eq!(actual, expected);
1108 fn test_bit_set_subset() {
1109 let mut set1 = BitSet::new();
1110 let mut set2 = BitSet::new();
1112 assert!(set1.is_subset(&set2)); // {} {}
1114 assert!(set1.is_subset(&set2)); // {} { 1 }
1116 assert!(set1.is_subset(&set2)); // {} { 1, 2 }
1118 assert!(set1.is_subset(&set2)); // { 2 } { 1, 2 }
1120 assert!(!set1.is_subset(&set2)); // { 2, 3 } { 1, 2 }
1122 assert!(set1.is_subset(&set2)); // { 2, 3 } { 1, 2, 3 }
1124 assert!(set1.is_subset(&set2)); // { 2, 3 } { 1, 2, 3, 4 }
1126 assert!(set1.is_subset(&set2)); // { 2, 3 } { 2, 3, 4 }
1128 assert!(!set1.is_subset(&set2)); // { 2, 3 } { 2, 4 }
1130 assert!(set1.is_subset(&set2)); // { 2 } { 2, 4 }
1134 fn test_bit_set_is_disjoint() {
1135 let a = BitSet::from_bytes(&[0b10100010]);
1136 let b = BitSet::from_bytes(&[0b01000000]);
1137 let c = BitSet::new();
1138 let d = BitSet::from_bytes(&[0b00110000]);
1140 assert!(!a.is_disjoint(&d));
1141 assert!(!d.is_disjoint(&a));
1143 assert!(a.is_disjoint(&b));
1144 assert!(a.is_disjoint(&c));
1145 assert!(b.is_disjoint(&a));
1146 assert!(b.is_disjoint(&c));
1147 assert!(c.is_disjoint(&a));
1148 assert!(c.is_disjoint(&b));
1152 fn test_bit_set_union_with() {
1153 //a should grow to include larger elements
1154 let mut a = BitSet::new();
1156 let mut b = BitSet::new();
1158 let expected = BitSet::from_bytes(&[0b10000100]);
1160 assert_eq!(a, expected);
1163 let mut a = BitSet::from_bytes(&[0b10100010]);
1164 let mut b = BitSet::from_bytes(&[0b01100010]);
1168 assert_eq!(a.len(), 4);
1169 assert_eq!(b.len(), 4);
1173 fn test_bit_set_intersect_with() {
1174 // Explicitly 0'ed bits
1175 let mut a = BitSet::from_bytes(&[0b10100010]);
1176 let mut b = BitSet::from_bytes(&[0b00000000]);
1178 a.intersect_with(&b);
1179 b.intersect_with(&c);
1180 assert!(a.is_empty());
1181 assert!(b.is_empty());
1183 // Uninitialized bits should behave like 0's
1184 let mut a = BitSet::from_bytes(&[0b10100010]);
1185 let mut b = BitSet::new();
1187 a.intersect_with(&b);
1188 b.intersect_with(&c);
1189 assert!(a.is_empty());
1190 assert!(b.is_empty());
1193 let mut a = BitSet::from_bytes(&[0b10100010]);
1194 let mut b = BitSet::from_bytes(&[0b01100010]);
1196 a.intersect_with(&b);
1197 b.intersect_with(&c);
1198 assert_eq!(a.len(), 2);
1199 assert_eq!(b.len(), 2);
1203 fn test_bit_set_difference_with() {
1204 // Explicitly 0'ed bits
1205 let mut a = BitSet::from_bytes(&[0b00000000]);
1206 let b = BitSet::from_bytes(&[0b10100010]);
1207 a.difference_with(&b);
1208 assert!(a.is_empty());
1210 // Uninitialized bits should behave like 0's
1211 let mut a = BitSet::new();
1212 let b = BitSet::from_bytes(&[0b11111111]);
1213 a.difference_with(&b);
1214 assert!(a.is_empty());
1217 let mut a = BitSet::from_bytes(&[0b10100010]);
1218 let mut b = BitSet::from_bytes(&[0b01100010]);
1220 a.difference_with(&b);
1221 b.difference_with(&c);
1222 assert_eq!(a.len(), 1);
1223 assert_eq!(b.len(), 1);
1227 fn test_bit_set_symmetric_difference_with() {
1228 //a should grow to include larger elements
1229 let mut a = BitSet::new();
1232 let mut b = BitSet::new();
1235 let expected = BitSet::from_bytes(&[0b10000100]);
1236 a.symmetric_difference_with(&b);
1237 assert_eq!(a, expected);
1239 let mut a = BitSet::from_bytes(&[0b10100010]);
1240 let b = BitSet::new();
1242 a.symmetric_difference_with(&b);
1246 let mut a = BitSet::from_bytes(&[0b11100010]);
1247 let mut b = BitSet::from_bytes(&[0b01101010]);
1249 a.symmetric_difference_with(&b);
1250 b.symmetric_difference_with(&c);
1251 assert_eq!(a.len(), 2);
1252 assert_eq!(b.len(), 2);
1256 fn test_bit_set_eq() {
1257 let a = BitSet::from_bytes(&[0b10100010]);
1258 let b = BitSet::from_bytes(&[0b00000000]);
1259 let c = BitSet::new();
1270 fn test_bit_set_cmp() {
1271 let a = BitSet::from_bytes(&[0b10100010]);
1272 let b = BitSet::from_bytes(&[0b00000000]);
1273 let c = BitSet::new();
1275 assert_eq!(a.cmp(&b), Greater);
1276 assert_eq!(a.cmp(&c), Greater);
1277 assert_eq!(b.cmp(&a), Less);
1278 assert_eq!(b.cmp(&c), Equal);
1279 assert_eq!(c.cmp(&a), Less);
1280 assert_eq!(c.cmp(&b), Equal);
1284 fn test_bit_vec_remove() {
1285 let mut a = BitSet::new();
1287 assert!(a.insert(1));
1288 assert!(a.remove(1));
1290 assert!(a.insert(100));
1291 assert!(a.remove(100));
1293 assert!(a.insert(1000));
1294 assert!(a.remove(1000));
1299 fn test_bit_vec_clone() {
1300 let mut a = BitSet::new();
1302 assert!(a.insert(1));
1303 assert!(a.insert(100));
1304 assert!(a.insert(1000));
1306 let mut b = a.clone();
1310 assert!(b.remove(1));
1311 assert!(a.contains(1));
1313 assert!(a.remove(1000));
1314 assert!(b.contains(1000));
1319 fn test_bit_set_append() {
1320 let mut a = BitSet::new();
1324 let mut b = BitSet::new();
1331 assert_eq!(a.len(), 4);
1332 assert_eq!(b.len(), 0);
1333 assert!(b.capacity() >= 6);
1335 assert_eq!(a, BitSet::from_bytes(&[0b01110010]));
1339 fn test_bit_set_split_off() {
1341 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1342 0b00110011, 0b01101011, 0b10101101]);
1344 let b = a.split_off(0);
1346 assert_eq!(a.len(), 0);
1347 assert_eq!(b.len(), 21);
1349 assert_eq!(b, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1350 0b00110011, 0b01101011, 0b10101101]);
1352 // Split behind last element
1353 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1354 0b00110011, 0b01101011, 0b10101101]);
1356 let b = a.split_off(50);
1358 assert_eq!(a.len(), 21);
1359 assert_eq!(b.len(), 0);
1361 assert_eq!(a, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1362 0b00110011, 0b01101011, 0b10101101]));
1364 // Split at arbitrary element
1365 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1366 0b00110011, 0b01101011, 0b10101101]);
1368 let b = a.split_off(34);
1370 assert_eq!(a.len(), 12);
1371 assert_eq!(b.len(), 9);
1373 assert_eq!(a, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1374 0b00110011, 0b01000000]));
1375 assert_eq!(b, BitSet::from_bytes(&[0, 0, 0, 0,
1376 0b00101011, 0b10101101]));
1381 #[cfg(all(test, feature = "nightly"))]
1384 use bit_vec::BitVec;
1385 use rand::{Rng, thread_rng, ThreadRng};
1387 use test::{Bencher, black_box};
1389 const BENCH_BITS: usize = 1 << 14;
1390 const BITS: usize = 32;
1392 fn rng() -> ThreadRng {
1397 fn bench_bit_vecset_small(b: &mut Bencher) {
1399 let mut bit_vec = BitSet::new();
1402 bit_vec.insert((r.next_u32() as usize) % BITS);
1404 black_box(&bit_vec);
1409 fn bench_bit_vecset_big(b: &mut Bencher) {
1411 let mut bit_vec = BitSet::new();
1414 bit_vec.insert((r.next_u32() as usize) % BENCH_BITS);
1416 black_box(&bit_vec);
1421 fn bench_bit_vecset_iter(b: &mut Bencher) {
1422 let bit_vec = BitSet::from_bit_vec(BitVec::from_fn(BENCH_BITS,
1423 |idx| {idx % 3 == 0}));
1426 for idx in &bit_vec {
1427 sum += idx as usize;