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();
52 #![cfg_attr(all(test, feature = "nightly"), feature(test))]
53 #[cfg(all(test, feature = "nightly"))] extern crate test;
54 #[cfg(all(test, feature = "nightly"))] extern crate rand;
61 use bit_vec::{BitVec, Blocks, BitBlock};
62 use core::cmp::Ordering;
66 use core::iter::{self, Chain, Enumerate, FromIterator, Repeat, Skip, Take};
68 type MatchWords<'a, B> = Chain<Enumerate<Blocks<'a, B>>, Skip<Take<Enumerate<Repeat<B>>>>>;
70 /// Computes how many blocks are needed to store that many bits
71 fn blocks_for_bits<B: BitBlock>(bits: usize) -> usize {
72 // If we want 17 bits, dividing by 32 will produce 0. So we add 1 to make sure we
73 // reserve enough. But if we want exactly a multiple of 32, this will actually allocate
74 // one too many. So we need to check if that's the case. We can do that by computing if
75 // bitwise AND by `32 - 1` is 0. But LLVM should be able to optimize the semantically
76 // superior modulo operator on a power of two to this.
78 // Note that we can technically avoid this branch with the expression
79 // `(nbits + BITS - 1) / 32::BITS`, but if nbits is almost usize::MAX this will overflow.
80 if bits % B::bits() == 0 {
87 // Take two BitVec's, and return iterators of their words, where the shorter one
88 // has been padded with 0's
89 fn match_words<'a, 'b, B: BitBlock>(a: &'a BitVec<B>, b: &'b BitVec<B>)
90 -> (MatchWords<'a, B>, MatchWords<'b, B>)
92 let a_len = a.storage().len();
93 let b_len = b.storage().len();
95 // have to uselessly pretend to pad the longer one for type matching
97 (a.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(b_len).skip(a_len)),
98 b.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(0).skip(0)))
100 (a.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(0).skip(0)),
101 b.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(a_len).skip(b_len)))
105 pub struct BitSet<B = u32> {
109 impl<B: BitBlock> Clone for BitSet<B> {
110 fn clone(&self) -> Self {
112 bit_vec: self.bit_vec.clone(),
116 fn clone_from(&mut self, other: &Self) {
117 self.bit_vec.clone_from(&other.bit_vec);
121 impl<B: BitBlock> Default for BitSet<B> {
123 fn default() -> Self { BitSet { bit_vec: Default::default() } }
126 impl<B: BitBlock> FromIterator<usize> for BitSet<B> {
127 fn from_iter<I: IntoIterator<Item = usize>>(iter: I) -> Self {
128 let mut ret = Self::default();
134 impl<B: BitBlock> Extend<usize> for BitSet<B> {
136 fn extend<I: IntoIterator<Item = usize>>(&mut self, iter: I) {
143 impl<B: BitBlock> PartialOrd for BitSet<B> {
145 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
146 self.iter().partial_cmp(other)
150 impl<B: BitBlock> Ord for BitSet<B> {
152 fn cmp(&self, other: &Self) -> Ordering {
153 self.iter().cmp(other)
157 impl<B: BitBlock> PartialEq for BitSet<B> {
159 fn eq(&self, other: &Self) -> bool {
160 self.iter().eq(other)
164 impl<B: BitBlock> Eq for BitSet<B> {}
167 /// Creates a new empty `BitSet`.
172 /// use bit_set::BitSet;
174 /// let mut s = BitSet::new();
177 pub fn new() -> Self {
181 /// Creates a new `BitSet` with initially no contents, able to
182 /// hold `nbits` elements without resizing.
187 /// use bit_set::BitSet;
189 /// let mut s = BitSet::with_capacity(100);
190 /// assert!(s.capacity() >= 100);
193 pub fn with_capacity(nbits: usize) -> Self {
194 let bit_vec = BitVec::from_elem(nbits, false);
195 Self::from_bit_vec(bit_vec)
198 /// Creates a new `BitSet` from the given bit vector.
203 /// extern crate bit_vec;
204 /// extern crate bit_set;
207 /// use bit_vec::BitVec;
208 /// use bit_set::BitSet;
210 /// let bv = BitVec::from_bytes(&[0b01100000]);
211 /// let s = BitSet::from_bit_vec(bv);
213 /// // Print 1, 2 in arbitrary order
214 /// for x in s.iter() {
215 /// println!("{}", x);
220 pub fn from_bit_vec(bit_vec: BitVec) -> Self {
221 BitSet { bit_vec: bit_vec }
224 pub fn from_bytes(bytes: &[u8]) -> Self {
225 BitSet { bit_vec: BitVec::from_bytes(bytes) }
229 impl<B: BitBlock> BitSet<B> {
231 /// Returns the capacity in bits for this bit vector. Inserting any
232 /// element less than this amount will not trigger a resizing.
237 /// use bit_set::BitSet;
239 /// let mut s = BitSet::with_capacity(100);
240 /// assert!(s.capacity() >= 100);
243 pub fn capacity(&self) -> usize {
244 self.bit_vec.capacity()
247 /// Reserves capacity for the given `BitSet` to contain `len` distinct elements. In the case
248 /// of `BitSet` this means reallocations will not occur as long as all inserted elements
249 /// are less than `len`.
251 /// The collection may reserve more space to avoid frequent reallocations.
257 /// use bit_set::BitSet;
259 /// let mut s = BitSet::new();
260 /// s.reserve_len(10);
261 /// assert!(s.capacity() >= 10);
263 pub fn reserve_len(&mut self, len: usize) {
264 let cur_len = self.bit_vec.len();
266 self.bit_vec.reserve(len - cur_len);
270 /// Reserves the minimum capacity for the given `BitSet` to contain `len` distinct elements.
271 /// In the case of `BitSet` this means reallocations will not occur as long as all inserted
272 /// elements are less than `len`.
274 /// Note that the allocator may give the collection more space than it requests. Therefore
275 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve_len` if future
276 /// insertions are expected.
282 /// use bit_set::BitSet;
284 /// let mut s = BitSet::new();
285 /// s.reserve_len_exact(10);
286 /// assert!(s.capacity() >= 10);
288 pub fn reserve_len_exact(&mut self, len: usize) {
289 let cur_len = self.bit_vec.len();
291 self.bit_vec.reserve_exact(len - cur_len);
295 /// Consumes this set to return the underlying bit vector.
300 /// use bit_set::BitSet;
302 /// let mut s = BitSet::new();
306 /// let bv = s.into_bit_vec();
311 pub fn into_bit_vec(self) -> BitVec<B> {
315 /// Returns a reference to the underlying bit vector.
320 /// use bit_set::BitSet;
322 /// let mut s = BitSet::new();
325 /// let bv = s.get_ref();
326 /// assert_eq!(bv[0], true);
329 pub fn get_ref(&self) -> &BitVec<B> {
334 fn other_op<F>(&mut self, other: &Self, mut f: F) where F: FnMut(B, B) -> B {
336 let self_bit_vec = &mut self.bit_vec;
337 let other_bit_vec = &other.bit_vec;
339 let self_len = self_bit_vec.len();
340 let other_len = other_bit_vec.len();
342 // Expand the vector if necessary
343 if self_len < other_len {
344 self_bit_vec.grow(other_len - self_len, false);
347 // virtually pad other with 0's for equal lengths
349 let (_, result) = match_words(self_bit_vec, other_bit_vec);
353 // Apply values found in other
354 for (i, w) in other_words {
355 let old = self_bit_vec.storage()[i];
358 self_bit_vec.storage_mut()[i] = new;
363 /// Truncates the underlying vector to the least length required.
368 /// use bit_set::BitSet;
370 /// let mut s = BitSet::new();
371 /// s.insert(32183231);
372 /// s.remove(32183231);
374 /// // Internal storage will probably be bigger than necessary
375 /// println!("old capacity: {}", s.capacity());
377 /// // Now should be smaller
378 /// s.shrink_to_fit();
379 /// println!("new capacity: {}", s.capacity());
382 pub fn shrink_to_fit(&mut self) {
383 let bit_vec = &mut self.bit_vec;
384 // Obtain original length
385 let old_len = bit_vec.storage().len();
386 // Obtain coarse trailing zero length
387 let n = bit_vec.storage().iter().rev().take_while(|&&n| n == B::zero()).count();
389 let trunc_len = cmp::max(old_len - n, 1);
391 bit_vec.storage_mut().truncate(trunc_len);
392 bit_vec.set_len(trunc_len * B::bits());
396 /// Iterator over each usize stored in the `BitSet`.
401 /// use bit_set::BitSet;
403 /// let s = BitSet::from_bytes(&[0b01001010]);
405 /// // Print 1, 4, 6 in arbitrary order
406 /// for x in s.iter() {
407 /// println!("{}", x);
411 pub fn iter(&self) -> Iter<B> {
412 Iter(BlockIter::from_blocks(self.bit_vec.blocks()))
415 /// Iterator over each usize stored in `self` union `other`.
416 /// See [union_with](#method.union_with) for an efficient in-place version.
421 /// use bit_set::BitSet;
423 /// let a = BitSet::from_bytes(&[0b01101000]);
424 /// let b = BitSet::from_bytes(&[0b10100000]);
426 /// // Print 0, 1, 2, 4 in arbitrary order
427 /// for x in a.union(&b) {
428 /// println!("{}", x);
432 pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, B> {
433 fn or<B: BitBlock>(w1: B, w2: B) -> B { w1 | w2 }
435 Union(BlockIter::from_blocks(TwoBitPositions {
436 set: self.bit_vec.blocks(),
437 other: other.bit_vec.blocks(),
442 /// Iterator over each usize stored in `self` intersect `other`.
443 /// See [intersect_with](#method.intersect_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]);
454 /// for x in a.intersection(&b) {
455 /// println!("{}", x);
459 pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, B> {
460 fn bitand<B: BitBlock>(w1: B, w2: B) -> B { w1 & w2 }
461 let min = cmp::min(self.bit_vec.len(), other.bit_vec.len());
463 Intersection(BlockIter::from_blocks(TwoBitPositions {
464 set: self.bit_vec.blocks(),
465 other: other.bit_vec.blocks(),
470 /// Iterator over each usize stored in the `self` setminus `other`.
471 /// See [difference_with](#method.difference_with) for an efficient in-place version.
476 /// use bit_set::BitSet;
478 /// let a = BitSet::from_bytes(&[0b01101000]);
479 /// let b = BitSet::from_bytes(&[0b10100000]);
481 /// // Print 1, 4 in arbitrary order
482 /// for x in a.difference(&b) {
483 /// println!("{}", x);
486 /// // Note that difference is not symmetric,
487 /// // and `b - a` means something else.
489 /// for x in b.difference(&a) {
490 /// println!("{}", x);
494 pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, B> {
495 fn diff<B: BitBlock>(w1: B, w2: B) -> B { w1 & !w2 }
497 Difference(BlockIter::from_blocks(TwoBitPositions {
498 set: self.bit_vec.blocks(),
499 other: other.bit_vec.blocks(),
504 /// Iterator over each usize stored in the symmetric difference of `self` and `other`.
505 /// See [symmetric_difference_with](#method.symmetric_difference_with) for
506 /// an efficient in-place version.
511 /// use bit_set::BitSet;
513 /// let a = BitSet::from_bytes(&[0b01101000]);
514 /// let b = BitSet::from_bytes(&[0b10100000]);
516 /// // Print 0, 1, 4 in arbitrary order
517 /// for x in a.symmetric_difference(&b) {
518 /// println!("{}", x);
522 pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> SymmetricDifference<'a, B> {
523 fn bitxor<B: BitBlock>(w1: B, w2: B) -> B { w1 ^ w2 }
525 SymmetricDifference(BlockIter::from_blocks(TwoBitPositions {
526 set: self.bit_vec.blocks(),
527 other: other.bit_vec.blocks(),
532 /// Unions in-place with the specified other bit vector.
537 /// use bit_set::BitSet;
539 /// let a = 0b01101000;
540 /// let b = 0b10100000;
541 /// let res = 0b11101000;
543 /// let mut a = BitSet::from_bytes(&[a]);
544 /// let b = BitSet::from_bytes(&[b]);
545 /// let res = BitSet::from_bytes(&[res]);
547 /// a.union_with(&b);
548 /// assert_eq!(a, res);
551 pub fn union_with(&mut self, other: &Self) {
552 self.other_op(other, |w1, w2| w1 | w2);
555 /// Intersects in-place with the specified other bit vector.
560 /// use bit_set::BitSet;
562 /// let a = 0b01101000;
563 /// let b = 0b10100000;
564 /// let res = 0b00100000;
566 /// let mut a = BitSet::from_bytes(&[a]);
567 /// let b = BitSet::from_bytes(&[b]);
568 /// let res = BitSet::from_bytes(&[res]);
570 /// a.intersect_with(&b);
571 /// assert_eq!(a, res);
574 pub fn intersect_with(&mut self, other: &Self) {
575 self.other_op(other, |w1, w2| w1 & w2);
578 /// Makes this bit vector the difference with the specified other bit vector
584 /// use bit_set::BitSet;
586 /// let a = 0b01101000;
587 /// let b = 0b10100000;
588 /// let a_b = 0b01001000; // a - b
589 /// let b_a = 0b10000000; // b - a
591 /// let mut bva = BitSet::from_bytes(&[a]);
592 /// let bvb = BitSet::from_bytes(&[b]);
593 /// let bva_b = BitSet::from_bytes(&[a_b]);
594 /// let bvb_a = BitSet::from_bytes(&[b_a]);
596 /// bva.difference_with(&bvb);
597 /// assert_eq!(bva, bva_b);
599 /// let bva = BitSet::from_bytes(&[a]);
600 /// let mut bvb = BitSet::from_bytes(&[b]);
602 /// bvb.difference_with(&bva);
603 /// assert_eq!(bvb, bvb_a);
606 pub fn difference_with(&mut self, other: &Self) {
607 self.other_op(other, |w1, w2| w1 & !w2);
610 /// Makes this bit vector the symmetric difference with the specified other
611 /// bit vector in-place.
616 /// use bit_set::BitSet;
618 /// let a = 0b01101000;
619 /// let b = 0b10100000;
620 /// let res = 0b11001000;
622 /// let mut a = BitSet::from_bytes(&[a]);
623 /// let b = BitSet::from_bytes(&[b]);
624 /// let res = BitSet::from_bytes(&[res]);
626 /// a.symmetric_difference_with(&b);
627 /// assert_eq!(a, res);
630 pub fn symmetric_difference_with(&mut self, other: &Self) {
631 self.other_op(other, |w1, w2| w1 ^ w2);
635 /// Moves all elements from `other` into `Self`, leaving `other` empty.
640 /// use bit_set::BitSet;
642 /// let mut a = BitSet::new();
646 /// let mut b = BitSet::new();
651 /// a.append(&mut b);
653 /// assert_eq!(a.len(), 4);
654 /// assert_eq!(b.len(), 0);
655 /// assert_eq!(a, BitSet::from_bytes(&[0b01110010]));
657 pub fn append(&mut self, other: &mut Self) {
658 self.union_with(other);
662 /// Splits the `BitSet` into two at the given key including the key.
663 /// Retains the first part in-place while returning the second part.
668 /// use bit_set::BitSet;
670 /// let mut a = BitSet::new();
676 /// let b = a.split_off(3);
678 /// assert_eq!(a.len(), 2);
679 /// assert_eq!(b.len(), 2);
680 /// assert_eq!(a, BitSet::from_bytes(&[0b01100000]));
681 /// assert_eq!(b, BitSet::from_bytes(&[0b00010010]));
683 pub fn split_off(&mut self, at: usize) -> Self {
684 let mut other = BitSet::new();
687 swap(self, &mut other);
689 } else if at >= self.bit_vec.len() {
693 // Calculate block and bit at which to split
697 // Pad `other` with `w` zero blocks,
698 // append `self`'s blocks in the range from `w` to the end to `other`
699 other.bit_vec.storage_mut().extend(repeat(0u32).take(w)
700 .chain(self.bit_vec.storage()[w..].iter().cloned()));
701 other.bit_vec.nbits = self.bit_vec.nbits;
704 other.bit_vec.storage_mut()[w] &= !0 << b;
707 // Sets `bit_vec.len()` and fixes the last block as well
708 self.bit_vec.truncate(at);
714 /// Returns the number of set bits in this set.
716 pub fn len(&self) -> usize {
717 self.bit_vec.blocks().fold(0, |acc, n| acc + n.count_ones() as usize)
720 /// Returns whether there are no bits set in this set
722 pub fn is_empty(&self) -> bool {
726 /// Clears all bits in this set
728 pub fn clear(&mut self) {
729 self.bit_vec.clear();
732 /// Returns `true` if this set contains the specified integer.
734 pub fn contains(&self, value: usize) -> bool {
735 let bit_vec = &self.bit_vec;
736 value < bit_vec.len() && bit_vec[value]
739 /// Returns `true` if the set has no elements in common with `other`.
740 /// This is equivalent to checking for an empty intersection.
742 pub fn is_disjoint(&self, other: &Self) -> bool {
743 self.intersection(other).next().is_none()
746 /// Returns `true` if the set is a subset of another.
748 pub fn is_subset(&self, other: &Self) -> bool {
749 let self_bit_vec = &self.bit_vec;
750 let other_bit_vec = &other.bit_vec;
751 let other_blocks = blocks_for_bits::<B>(other_bit_vec.len());
753 // Check that `self` intersect `other` is self
754 self_bit_vec.blocks().zip(other_bit_vec.blocks()).all(|(w1, w2)| w1 & w2 == w1) &&
755 // Make sure if `self` has any more blocks than `other`, they're all 0
756 self_bit_vec.blocks().skip(other_blocks).all(|w| w == B::zero())
759 /// Returns `true` if the set is a superset of another.
761 pub fn is_superset(&self, other: &Self) -> bool {
762 other.is_subset(self)
765 /// Adds a value to the set. Returns `true` if the value was not already
766 /// present in the set.
767 pub fn insert(&mut self, value: usize) -> bool {
768 if self.contains(value) {
772 // Ensure we have enough space to hold the new element
773 let len = self.bit_vec.len();
775 self.bit_vec.grow(value - len + 1, false)
778 self.bit_vec.set(value, true);
782 /// Removes a value from the set. Returns `true` if the value was
783 /// present in the set.
784 pub fn remove(&mut self, value: usize) -> bool {
785 if !self.contains(value) {
789 self.bit_vec.set(value, false);
795 impl<B: BitBlock> fmt::Debug for BitSet<B> {
796 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
797 fmt.debug_set().entries(self).finish()
801 impl<B: BitBlock> hash::Hash for BitSet<B> {
802 fn hash<H: hash::Hasher>(&self, state: &mut H) {
810 struct BlockIter<T, B> {
816 impl<T, B: BitBlock> BlockIter<T, B> where T: Iterator<Item=B> {
817 fn from_blocks(mut blocks: T) -> BlockIter<T, B> {
818 let h = blocks.next().unwrap_or(B::zero());
819 BlockIter {tail: blocks, head: h, head_offset: 0}
823 /// An iterator combining two `BitSet` iterators.
825 struct TwoBitPositions<'a, B: 'a> {
827 other: Blocks<'a, B>,
828 merge: fn(B, B) -> B,
831 /// An iterator for `BitSet`.
833 pub struct Iter<'a, B: 'a>(BlockIter<Blocks<'a, B>, B>);
835 pub struct Union<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
837 pub struct Intersection<'a, B: 'a>(Take<BlockIter<TwoBitPositions<'a, B>, B>>);
839 pub struct Difference<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
841 pub struct SymmetricDifference<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
843 impl<'a, T, B: BitBlock> Iterator for BlockIter<T, B> where T: Iterator<Item=B> {
846 fn next(&mut self) -> Option<usize> {
847 while self.head == B::zero() {
848 match self.tail.next() {
849 Some(w) => self.head = w,
852 self.head_offset += B::bits();
855 // from the current block, isolate the
856 // LSB and subtract 1, producing k:
857 // a block with a number of set bits
858 // equal to the index of the LSB
859 let k = (self.head & (!self.head + B::one())) - B::one();
860 // update block, removing the LSB
861 self.head = self.head & (self.head - B::one());
862 // return offset + (index of LSB)
863 Some(self.head_offset + (B::count_ones(k) as usize))
867 fn size_hint(&self) -> (usize, Option<usize>) {
868 match self.tail.size_hint() {
869 (_, Some(h)) => (0, Some(1 + h * B::bits())),
875 impl<'a, B: BitBlock> Iterator for TwoBitPositions<'a, B> {
878 fn next(&mut self) -> Option<B> {
879 match (self.set.next(), self.other.next()) {
880 (Some(a), Some(b)) => Some((self.merge)(a, b)),
881 (Some(a), None) => Some((self.merge)(a, B::zero())),
882 (None, Some(b)) => Some((self.merge)(B::zero(), b)),
888 fn size_hint(&self) -> (usize, Option<usize>) {
889 let (a, au) = self.set.size_hint();
890 let (b, bu) = self.other.size_hint();
892 let upper = match (au, bu) {
893 (Some(au), Some(bu)) => Some(cmp::max(au, bu)),
897 (cmp::max(a, b), upper)
901 impl<'a, B: BitBlock> Iterator for Iter<'a, B> {
904 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
905 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
908 impl<'a, B: BitBlock> Iterator for Union<'a, B> {
911 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
912 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
915 impl<'a, B: BitBlock> Iterator for Intersection<'a, B> {
918 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
919 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
922 impl<'a, B: BitBlock> Iterator for Difference<'a, B> {
925 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
926 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
929 impl<'a, B: BitBlock> Iterator for SymmetricDifference<'a, B> {
932 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
933 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
936 impl<'a, B: BitBlock> IntoIterator for &'a BitSet<B> {
938 type IntoIter = Iter<'a, B>;
940 fn into_iter(self) -> Iter<'a, B> {
947 use std::cmp::Ordering::{Equal, Greater, Less};
953 fn test_bit_set_show() {
954 let mut s = BitSet::new();
959 assert_eq!("{1, 2, 10, 50}", format!("{:?}", s));
963 fn test_bit_set_from_usizes() {
964 let usizes = vec![0, 2, 2, 3];
965 let a: BitSet = usizes.into_iter().collect();
966 let mut b = BitSet::new();
974 fn test_bit_set_iterator() {
975 let usizes = vec![0, 2, 2, 3];
976 let bit_vec: BitSet = usizes.into_iter().collect();
978 let idxs: Vec<_> = bit_vec.iter().collect();
979 assert_eq!(idxs, [0, 2, 3]);
981 let long: BitSet = (0..10000).filter(|&n| n % 2 == 0).collect();
982 let real: Vec<_> = (0..10000/2).map(|x| x*2).collect();
984 let idxs: Vec<_> = long.iter().collect();
985 assert_eq!(idxs, real);
989 fn test_bit_set_frombit_vec_init() {
990 let bools = [true, false];
991 let lengths = [10, 64, 100];
994 let bitset = BitSet::from_bit_vec(BitVec::from_elem(l, b));
995 assert_eq!(bitset.contains(1), b);
996 assert_eq!(bitset.contains((l-1)), b);
997 assert!(!bitset.contains(l));
1003 fn test_bit_vec_masking() {
1004 let b = BitVec::from_elem(140, true);
1005 let mut bs = BitSet::from_bit_vec(b);
1006 assert!(bs.contains(139));
1007 assert!(!bs.contains(140));
1008 assert!(bs.insert(150));
1009 assert!(!bs.contains(140));
1010 assert!(!bs.contains(149));
1011 assert!(bs.contains(150));
1012 assert!(!bs.contains(151));
1016 fn test_bit_set_basic() {
1017 let mut b = BitSet::new();
1018 assert!(b.insert(3));
1019 assert!(!b.insert(3));
1020 assert!(b.contains(3));
1021 assert!(b.insert(4));
1022 assert!(!b.insert(4));
1023 assert!(b.contains(3));
1024 assert!(b.insert(400));
1025 assert!(!b.insert(400));
1026 assert!(b.contains(400));
1027 assert_eq!(b.len(), 3);
1031 fn test_bit_set_intersection() {
1032 let mut a = BitSet::new();
1033 let mut b = BitSet::new();
1035 assert!(a.insert(11));
1036 assert!(a.insert(1));
1037 assert!(a.insert(3));
1038 assert!(a.insert(77));
1039 assert!(a.insert(103));
1040 assert!(a.insert(5));
1042 assert!(b.insert(2));
1043 assert!(b.insert(11));
1044 assert!(b.insert(77));
1045 assert!(b.insert(5));
1046 assert!(b.insert(3));
1048 let expected = [3, 5, 11, 77];
1049 let actual: Vec<_> = a.intersection(&b).collect();
1050 assert_eq!(actual, expected);
1054 fn test_bit_set_difference() {
1055 let mut a = BitSet::new();
1056 let mut b = BitSet::new();
1058 assert!(a.insert(1));
1059 assert!(a.insert(3));
1060 assert!(a.insert(5));
1061 assert!(a.insert(200));
1062 assert!(a.insert(500));
1064 assert!(b.insert(3));
1065 assert!(b.insert(200));
1067 let expected = [1, 5, 500];
1068 let actual: Vec<_> = a.difference(&b).collect();
1069 assert_eq!(actual, expected);
1073 fn test_bit_set_symmetric_difference() {
1074 let mut a = BitSet::new();
1075 let mut b = BitSet::new();
1077 assert!(a.insert(1));
1078 assert!(a.insert(3));
1079 assert!(a.insert(5));
1080 assert!(a.insert(9));
1081 assert!(a.insert(11));
1083 assert!(b.insert(3));
1084 assert!(b.insert(9));
1085 assert!(b.insert(14));
1086 assert!(b.insert(220));
1088 let expected = [1, 5, 11, 14, 220];
1089 let actual: Vec<_> = a.symmetric_difference(&b).collect();
1090 assert_eq!(actual, expected);
1094 fn test_bit_set_union() {
1095 let mut a = BitSet::new();
1096 let mut b = BitSet::new();
1097 assert!(a.insert(1));
1098 assert!(a.insert(3));
1099 assert!(a.insert(5));
1100 assert!(a.insert(9));
1101 assert!(a.insert(11));
1102 assert!(a.insert(160));
1103 assert!(a.insert(19));
1104 assert!(a.insert(24));
1105 assert!(a.insert(200));
1107 assert!(b.insert(1));
1108 assert!(b.insert(5));
1109 assert!(b.insert(9));
1110 assert!(b.insert(13));
1111 assert!(b.insert(19));
1113 let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160, 200];
1114 let actual: Vec<_> = a.union(&b).collect();
1115 assert_eq!(actual, expected);
1119 fn test_bit_set_subset() {
1120 let mut set1 = BitSet::new();
1121 let mut set2 = BitSet::new();
1123 assert!(set1.is_subset(&set2)); // {} {}
1125 assert!(set1.is_subset(&set2)); // {} { 1 }
1127 assert!(set1.is_subset(&set2)); // {} { 1, 2 }
1129 assert!(set1.is_subset(&set2)); // { 2 } { 1, 2 }
1131 assert!(!set1.is_subset(&set2)); // { 2, 3 } { 1, 2 }
1133 assert!(set1.is_subset(&set2)); // { 2, 3 } { 1, 2, 3 }
1135 assert!(set1.is_subset(&set2)); // { 2, 3 } { 1, 2, 3, 4 }
1137 assert!(set1.is_subset(&set2)); // { 2, 3 } { 2, 3, 4 }
1139 assert!(!set1.is_subset(&set2)); // { 2, 3 } { 2, 4 }
1141 assert!(set1.is_subset(&set2)); // { 2 } { 2, 4 }
1145 fn test_bit_set_is_disjoint() {
1146 let a = BitSet::from_bytes(&[0b10100010]);
1147 let b = BitSet::from_bytes(&[0b01000000]);
1148 let c = BitSet::new();
1149 let d = BitSet::from_bytes(&[0b00110000]);
1151 assert!(!a.is_disjoint(&d));
1152 assert!(!d.is_disjoint(&a));
1154 assert!(a.is_disjoint(&b));
1155 assert!(a.is_disjoint(&c));
1156 assert!(b.is_disjoint(&a));
1157 assert!(b.is_disjoint(&c));
1158 assert!(c.is_disjoint(&a));
1159 assert!(c.is_disjoint(&b));
1163 fn test_bit_set_union_with() {
1164 //a should grow to include larger elements
1165 let mut a = BitSet::new();
1167 let mut b = BitSet::new();
1169 let expected = BitSet::from_bytes(&[0b10000100]);
1171 assert_eq!(a, expected);
1174 let mut a = BitSet::from_bytes(&[0b10100010]);
1175 let mut b = BitSet::from_bytes(&[0b01100010]);
1179 assert_eq!(a.len(), 4);
1180 assert_eq!(b.len(), 4);
1184 fn test_bit_set_intersect_with() {
1185 // Explicitly 0'ed bits
1186 let mut a = BitSet::from_bytes(&[0b10100010]);
1187 let mut b = BitSet::from_bytes(&[0b00000000]);
1189 a.intersect_with(&b);
1190 b.intersect_with(&c);
1191 assert!(a.is_empty());
1192 assert!(b.is_empty());
1194 // Uninitialized bits should behave like 0's
1195 let mut a = BitSet::from_bytes(&[0b10100010]);
1196 let mut b = BitSet::new();
1198 a.intersect_with(&b);
1199 b.intersect_with(&c);
1200 assert!(a.is_empty());
1201 assert!(b.is_empty());
1204 let mut a = BitSet::from_bytes(&[0b10100010]);
1205 let mut b = BitSet::from_bytes(&[0b01100010]);
1207 a.intersect_with(&b);
1208 b.intersect_with(&c);
1209 assert_eq!(a.len(), 2);
1210 assert_eq!(b.len(), 2);
1214 fn test_bit_set_difference_with() {
1215 // Explicitly 0'ed bits
1216 let mut a = BitSet::from_bytes(&[0b00000000]);
1217 let b = BitSet::from_bytes(&[0b10100010]);
1218 a.difference_with(&b);
1219 assert!(a.is_empty());
1221 // Uninitialized bits should behave like 0's
1222 let mut a = BitSet::new();
1223 let b = BitSet::from_bytes(&[0b11111111]);
1224 a.difference_with(&b);
1225 assert!(a.is_empty());
1228 let mut a = BitSet::from_bytes(&[0b10100010]);
1229 let mut b = BitSet::from_bytes(&[0b01100010]);
1231 a.difference_with(&b);
1232 b.difference_with(&c);
1233 assert_eq!(a.len(), 1);
1234 assert_eq!(b.len(), 1);
1238 fn test_bit_set_symmetric_difference_with() {
1239 //a should grow to include larger elements
1240 let mut a = BitSet::new();
1243 let mut b = BitSet::new();
1246 let expected = BitSet::from_bytes(&[0b10000100]);
1247 a.symmetric_difference_with(&b);
1248 assert_eq!(a, expected);
1250 let mut a = BitSet::from_bytes(&[0b10100010]);
1251 let b = BitSet::new();
1253 a.symmetric_difference_with(&b);
1257 let mut a = BitSet::from_bytes(&[0b11100010]);
1258 let mut b = BitSet::from_bytes(&[0b01101010]);
1260 a.symmetric_difference_with(&b);
1261 b.symmetric_difference_with(&c);
1262 assert_eq!(a.len(), 2);
1263 assert_eq!(b.len(), 2);
1267 fn test_bit_set_eq() {
1268 let a = BitSet::from_bytes(&[0b10100010]);
1269 let b = BitSet::from_bytes(&[0b00000000]);
1270 let c = BitSet::new();
1281 fn test_bit_set_cmp() {
1282 let a = BitSet::from_bytes(&[0b10100010]);
1283 let b = BitSet::from_bytes(&[0b00000000]);
1284 let c = BitSet::new();
1286 assert_eq!(a.cmp(&b), Greater);
1287 assert_eq!(a.cmp(&c), Greater);
1288 assert_eq!(b.cmp(&a), Less);
1289 assert_eq!(b.cmp(&c), Equal);
1290 assert_eq!(c.cmp(&a), Less);
1291 assert_eq!(c.cmp(&b), Equal);
1295 fn test_bit_vec_remove() {
1296 let mut a = BitSet::new();
1298 assert!(a.insert(1));
1299 assert!(a.remove(1));
1301 assert!(a.insert(100));
1302 assert!(a.remove(100));
1304 assert!(a.insert(1000));
1305 assert!(a.remove(1000));
1310 fn test_bit_vec_clone() {
1311 let mut a = BitSet::new();
1313 assert!(a.insert(1));
1314 assert!(a.insert(100));
1315 assert!(a.insert(1000));
1317 let mut b = a.clone();
1321 assert!(b.remove(1));
1322 assert!(a.contains(1));
1324 assert!(a.remove(1000));
1325 assert!(b.contains(1000));
1330 fn test_bit_set_append() {
1331 let mut a = BitSet::new();
1335 let mut b = BitSet::new();
1342 assert_eq!(a.len(), 4);
1343 assert_eq!(b.len(), 0);
1344 assert!(b.capacity() >= 6);
1346 assert_eq!(a, BitSet::from_bytes(&[0b01110010]));
1350 fn test_bit_set_split_off() {
1352 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1353 0b00110011, 0b01101011, 0b10101101]);
1355 let b = a.split_off(0);
1357 assert_eq!(a.len(), 0);
1358 assert_eq!(b.len(), 21);
1360 assert_eq!(b, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1361 0b00110011, 0b01101011, 0b10101101]);
1363 // Split behind last element
1364 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1365 0b00110011, 0b01101011, 0b10101101]);
1367 let b = a.split_off(50);
1369 assert_eq!(a.len(), 21);
1370 assert_eq!(b.len(), 0);
1372 assert_eq!(a, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1373 0b00110011, 0b01101011, 0b10101101]));
1375 // Split at arbitrary element
1376 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1377 0b00110011, 0b01101011, 0b10101101]);
1379 let b = a.split_off(34);
1381 assert_eq!(a.len(), 12);
1382 assert_eq!(b.len(), 9);
1384 assert_eq!(a, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1385 0b00110011, 0b01000000]));
1386 assert_eq!(b, BitSet::from_bytes(&[0, 0, 0, 0,
1387 0b00101011, 0b10101101]));
1392 #[cfg(all(test, feature = "nightly"))]
1395 use bit_vec::BitVec;
1396 use rand::{Rng, thread_rng, ThreadRng};
1398 use test::{Bencher, black_box};
1400 const BENCH_BITS: usize = 1 << 14;
1401 const BITS: usize = 32;
1403 fn rng() -> ThreadRng {
1408 fn bench_bit_vecset_small(b: &mut Bencher) {
1410 let mut bit_vec = BitSet::new();
1413 bit_vec.insert((r.next_u32() as usize) % BITS);
1415 black_box(&bit_vec);
1420 fn bench_bit_vecset_big(b: &mut Bencher) {
1422 let mut bit_vec = BitSet::new();
1425 bit_vec.insert((r.next_u32() as usize) % BENCH_BITS);
1427 black_box(&bit_vec);
1432 fn bench_bit_vecset_iter(b: &mut Bencher) {
1433 let bit_vec = BitSet::from_bit_vec(BitVec::from_fn(BENCH_BITS,
1434 |idx| {idx % 3 == 0}));
1437 for idx in &bit_vec {
1438 sum += idx as usize;