]> git.lizzy.rs Git - bit-set.git/blob - src/lib.rs
Override `clone_from`
[bit-set.git] / src / lib.rs
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.
4 //
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.
10
11 //! An implementation of a set using a bit vector as an underlying
12 //! representation for holding unsigned numerical elements.
13 //!
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
16 //! as a `usize`.
17 //!
18 //! # Examples
19 //!
20 //! ```
21 //! use bit_set::BitSet;
22 //!
23 //! // It's a regular set
24 //! let mut s = BitSet::new();
25 //! s.insert(0);
26 //! s.insert(3);
27 //! s.insert(7);
28 //!
29 //! s.remove(7);
30 //!
31 //! if !s.contains(7) {
32 //!     println!("There is no 7");
33 //! }
34 //!
35 //! // Can initialize from a `BitVec`
36 //! let other = BitSet::from_bytes(&[0b11010000]);
37 //!
38 //! s.union_with(&other);
39 //!
40 //! // Print 0, 1, 3 in some order
41 //! for x in s.iter() {
42 //!     println!("{}", x);
43 //! }
44 //!
45 //! // Can convert back to a `BitVec`
46 //! let bv = s.into_bit_vec();
47 //! assert!(bv[3]);
48 //! ```
49
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;
53 extern crate bit_vec;
54
55 use bit_vec::{BitVec, Blocks, BitBlock};
56 use std::cmp::Ordering;
57 use std::cmp;
58 use std::fmt;
59 use std::hash;
60 use std::iter::{self, Chain, Enumerate, FromIterator, Repeat, Skip, Take};
61
62 type MatchWords<'a, B> = Chain<Enumerate<Blocks<'a, B>>, Skip<Take<Enumerate<Repeat<B>>>>>;
63
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.
71     //
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 {
75         bits / B::bits()
76     } else {
77         bits / B::bits() + 1
78     }
79 }
80
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>)
85 {
86     let a_len = a.storage().len();
87     let b_len = b.storage().len();
88
89     // have to uselessly pretend to pad the longer one for type matching
90     if a_len < b_len {
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)))
93     } else {
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)))
96     }
97 }
98
99 pub struct BitSet<B = u32> {
100     bit_vec: BitVec<B>,
101 }
102
103 impl<B: BitBlock> Clone for BitSet<B> {
104     fn clone(&self) -> Self {
105         BitSet {
106             bit_vec: self.bit_vec.clone(),
107         }
108     }
109
110     fn clone_from(&mut self, other: &Self) {
111         self.bit_vec.clone_from(&other.bit_vec);
112     }
113 }
114
115 impl<B: BitBlock> Default for BitSet<B> {
116     #[inline]
117     fn default() -> Self { BitSet { bit_vec: Default::default() } }
118 }
119
120 impl<B: BitBlock> FromIterator<usize> for BitSet<B> {
121     fn from_iter<I: IntoIterator<Item = usize>>(iter: I) -> Self {
122         let mut ret = Self::default();
123         ret.extend(iter);
124         ret
125     }
126 }
127
128 impl<B: BitBlock> Extend<usize> for BitSet<B> {
129     #[inline]
130     fn extend<I: IntoIterator<Item = usize>>(&mut self, iter: I) {
131         for i in iter {
132             self.insert(i);
133         }
134     }
135 }
136
137 impl<B: BitBlock> PartialOrd for BitSet<B> {
138     #[inline]
139     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
140         self.iter().partial_cmp(other)
141     }
142 }
143
144 impl<B: BitBlock> Ord for BitSet<B> {
145     #[inline]
146     fn cmp(&self, other: &Self) -> Ordering {
147         self.iter().cmp(other)
148     }
149 }
150
151 impl<B: BitBlock> PartialEq for BitSet<B> {
152     #[inline]
153     fn eq(&self, other: &Self) -> bool {
154         self.iter().eq(other)
155     }
156 }
157
158 impl<B: BitBlock> Eq for BitSet<B> {}
159
160 impl BitSet<u32> {
161     /// Creates a new empty `BitSet`.
162     ///
163     /// # Examples
164     ///
165     /// ```
166     /// use bit_set::BitSet;
167     ///
168     /// let mut s = BitSet::new();
169     /// ```
170     #[inline]
171     pub fn new() -> Self {
172         Self::default()
173     }
174
175     /// Creates a new `BitSet` with initially no contents, able to
176     /// hold `nbits` elements without resizing.
177     ///
178     /// # Examples
179     ///
180     /// ```
181     /// use bit_set::BitSet;
182     ///
183     /// let mut s = BitSet::with_capacity(100);
184     /// assert!(s.capacity() >= 100);
185     /// ```
186     #[inline]
187     pub fn with_capacity(nbits: usize) -> Self {
188         let bit_vec = BitVec::from_elem(nbits, false);
189         Self::from_bit_vec(bit_vec)
190     }
191
192     /// Creates a new `BitSet` from the given bit vector.
193     ///
194     /// # Examples
195     ///
196     /// ```
197     /// extern crate bit_vec;
198     /// extern crate bit_set;
199     ///
200     /// fn main() {
201     ///     use bit_vec::BitVec;
202     ///     use bit_set::BitSet;
203     ///
204     ///     let bv = BitVec::from_bytes(&[0b01100000]);
205     ///     let s = BitSet::from_bit_vec(bv);
206     ///
207     ///     // Print 1, 2 in arbitrary order
208     ///     for x in s.iter() {
209     ///         println!("{}", x);
210     ///     }
211     /// }
212     /// ```
213     #[inline]
214     pub fn from_bit_vec(bit_vec: BitVec) -> Self {
215         BitSet { bit_vec: bit_vec }
216     }
217
218     pub fn from_bytes(bytes: &[u8]) -> Self {
219         BitSet { bit_vec: BitVec::from_bytes(bytes) }
220     }
221 }
222
223 impl<B: BitBlock> BitSet<B> {
224
225     /// Returns the capacity in bits for this bit vector. Inserting any
226     /// element less than this amount will not trigger a resizing.
227     ///
228     /// # Examples
229     ///
230     /// ```
231     /// use bit_set::BitSet;
232     ///
233     /// let mut s = BitSet::with_capacity(100);
234     /// assert!(s.capacity() >= 100);
235     /// ```
236     #[inline]
237     pub fn capacity(&self) -> usize {
238         self.bit_vec.capacity()
239     }
240
241     /// Reserves capacity for the given `BitSet` to contain `len` distinct elements. In the case
242     /// of `BitSet` this means reallocations will not occur as long as all inserted elements
243     /// are less than `len`.
244     ///
245     /// The collection may reserve more space to avoid frequent reallocations.
246     ///
247     ///
248     /// # Examples
249     ///
250     /// ```
251     /// use bit_set::BitSet;
252     ///
253     /// let mut s = BitSet::new();
254     /// s.reserve_len(10);
255     /// assert!(s.capacity() >= 10);
256     /// ```
257     pub fn reserve_len(&mut self, len: usize) {
258         let cur_len = self.bit_vec.len();
259         if len >= cur_len {
260             self.bit_vec.reserve(len - cur_len);
261         }
262     }
263
264     /// Reserves the minimum capacity for the given `BitSet` to contain `len` distinct elements.
265     /// In the case of `BitSet` this means reallocations will not occur as long as all inserted
266     /// elements are less than `len`.
267     ///
268     /// Note that the allocator may give the collection more space than it requests. Therefore
269     /// capacity can not be relied upon to be precisely minimal. Prefer `reserve_len` if future
270     /// insertions are expected.
271     ///
272     ///
273     /// # Examples
274     ///
275     /// ```
276     /// use bit_set::BitSet;
277     ///
278     /// let mut s = BitSet::new();
279     /// s.reserve_len_exact(10);
280     /// assert!(s.capacity() >= 10);
281     /// ```
282     pub fn reserve_len_exact(&mut self, len: usize) {
283         let cur_len = self.bit_vec.len();
284         if len >= cur_len {
285             self.bit_vec.reserve_exact(len - cur_len);
286         }
287     }
288
289     /// Consumes this set to return the underlying bit vector.
290     ///
291     /// # Examples
292     ///
293     /// ```
294     /// use bit_set::BitSet;
295     ///
296     /// let mut s = BitSet::new();
297     /// s.insert(0);
298     /// s.insert(3);
299     ///
300     /// let bv = s.into_bit_vec();
301     /// assert!(bv[0]);
302     /// assert!(bv[3]);
303     /// ```
304     #[inline]
305     pub fn into_bit_vec(self) -> BitVec<B> {
306         self.bit_vec
307     }
308
309     /// Returns a reference to the underlying bit vector.
310     ///
311     /// # Examples
312     ///
313     /// ```
314     /// use bit_set::BitSet;
315     ///
316     /// let mut s = BitSet::new();
317     /// s.insert(0);
318     ///
319     /// let bv = s.get_ref();
320     /// assert_eq!(bv[0], true);
321     /// ```
322     #[inline]
323     pub fn get_ref(&self) -> &BitVec<B> {
324         &self.bit_vec
325     }
326
327     #[inline]
328     fn other_op<F>(&mut self, other: &Self, mut f: F) where F: FnMut(B, B) -> B {
329         // Unwrap BitVecs
330         let self_bit_vec = &mut self.bit_vec;
331         let other_bit_vec = &other.bit_vec;
332
333         let self_len = self_bit_vec.len();
334         let other_len = other_bit_vec.len();
335
336         // Expand the vector if necessary
337         if self_len < other_len {
338             self_bit_vec.grow(other_len - self_len, false);
339         }
340
341         // virtually pad other with 0's for equal lengths
342         let other_words = {
343             let (_, result) = match_words(self_bit_vec, other_bit_vec);
344             result
345         };
346
347         // Apply values found in other
348         for (i, w) in other_words {
349             let old = self_bit_vec.storage()[i];
350             let new = f(old, w);
351             unsafe {
352                 self_bit_vec.storage_mut()[i] = new;
353             }
354         }
355     }
356
357     /// Truncates the underlying vector to the least length required.
358     ///
359     /// # Examples
360     ///
361     /// ```
362     /// use bit_set::BitSet;
363     ///
364     /// let mut s = BitSet::new();
365     /// s.insert(32183231);
366     /// s.remove(32183231);
367     ///
368     /// // Internal storage will probably be bigger than necessary
369     /// println!("old capacity: {}", s.capacity());
370     ///
371     /// // Now should be smaller
372     /// s.shrink_to_fit();
373     /// println!("new capacity: {}", s.capacity());
374     /// ```
375     #[inline]
376     pub fn shrink_to_fit(&mut self) {
377         let bit_vec = &mut self.bit_vec;
378         // Obtain original length
379         let old_len = bit_vec.storage().len();
380         // Obtain coarse trailing zero length
381         let n = bit_vec.storage().iter().rev().take_while(|&&n| n == B::zero()).count();
382         // Truncate
383         let trunc_len = cmp::max(old_len - n, 1);
384         unsafe {
385             bit_vec.storage_mut().truncate(trunc_len);
386             bit_vec.set_len(trunc_len * B::bits());
387         }
388     }
389
390     /// Iterator over each usize stored in the `BitSet`.
391     ///
392     /// # Examples
393     ///
394     /// ```
395     /// use bit_set::BitSet;
396     ///
397     /// let s = BitSet::from_bytes(&[0b01001010]);
398     ///
399     /// // Print 1, 4, 6 in arbitrary order
400     /// for x in s.iter() {
401     ///     println!("{}", x);
402     /// }
403     /// ```
404     #[inline]
405     pub fn iter(&self) -> Iter<B> {
406         Iter(BlockIter::from_blocks(self.bit_vec.blocks()))
407     }
408
409     /// Iterator over each usize stored in `self` union `other`.
410     /// See [union_with](#method.union_with) for an efficient in-place version.
411     ///
412     /// # Examples
413     ///
414     /// ```
415     /// use bit_set::BitSet;
416     ///
417     /// let a = BitSet::from_bytes(&[0b01101000]);
418     /// let b = BitSet::from_bytes(&[0b10100000]);
419     ///
420     /// // Print 0, 1, 2, 4 in arbitrary order
421     /// for x in a.union(&b) {
422     ///     println!("{}", x);
423     /// }
424     /// ```
425     #[inline]
426     pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, B> {
427         fn or<B: BitBlock>(w1: B, w2: B) -> B { w1 | w2 }
428
429         Union(BlockIter::from_blocks(TwoBitPositions {
430             set: self.bit_vec.blocks(),
431             other: other.bit_vec.blocks(),
432             merge: or,
433         }))
434     }
435
436     /// Iterator over each usize stored in `self` intersect `other`.
437     /// See [intersect_with](#method.intersect_with) for an efficient in-place version.
438     ///
439     /// # Examples
440     ///
441     /// ```
442     /// use bit_set::BitSet;
443     ///
444     /// let a = BitSet::from_bytes(&[0b01101000]);
445     /// let b = BitSet::from_bytes(&[0b10100000]);
446     ///
447     /// // Print 2
448     /// for x in a.intersection(&b) {
449     ///     println!("{}", x);
450     /// }
451     /// ```
452     #[inline]
453     pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, B> {
454         fn bitand<B: BitBlock>(w1: B, w2: B) -> B { w1 & w2 }
455         let min = cmp::min(self.bit_vec.len(), other.bit_vec.len());
456
457         Intersection(BlockIter::from_blocks(TwoBitPositions {
458             set: self.bit_vec.blocks(),
459             other: other.bit_vec.blocks(),
460             merge: bitand,
461         }).take(min))
462     }
463
464     /// Iterator over each usize stored in the `self` setminus `other`.
465     /// See [difference_with](#method.difference_with) for an efficient in-place version.
466     ///
467     /// # Examples
468     ///
469     /// ```
470     /// use bit_set::BitSet;
471     ///
472     /// let a = BitSet::from_bytes(&[0b01101000]);
473     /// let b = BitSet::from_bytes(&[0b10100000]);
474     ///
475     /// // Print 1, 4 in arbitrary order
476     /// for x in a.difference(&b) {
477     ///     println!("{}", x);
478     /// }
479     ///
480     /// // Note that difference is not symmetric,
481     /// // and `b - a` means something else.
482     /// // This prints 0
483     /// for x in b.difference(&a) {
484     ///     println!("{}", x);
485     /// }
486     /// ```
487     #[inline]
488     pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, B> {
489         fn diff<B: BitBlock>(w1: B, w2: B) -> B { w1 & !w2 }
490
491         Difference(BlockIter::from_blocks(TwoBitPositions {
492             set: self.bit_vec.blocks(),
493             other: other.bit_vec.blocks(),
494             merge: diff,
495         }))
496     }
497
498     /// Iterator over each usize stored in the symmetric difference of `self` and `other`.
499     /// See [symmetric_difference_with](#method.symmetric_difference_with) for
500     /// an efficient in-place version.
501     ///
502     /// # Examples
503     ///
504     /// ```
505     /// use bit_set::BitSet;
506     ///
507     /// let a = BitSet::from_bytes(&[0b01101000]);
508     /// let b = BitSet::from_bytes(&[0b10100000]);
509     ///
510     /// // Print 0, 1, 4 in arbitrary order
511     /// for x in a.symmetric_difference(&b) {
512     ///     println!("{}", x);
513     /// }
514     /// ```
515     #[inline]
516     pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> SymmetricDifference<'a, B> {
517         fn bitxor<B: BitBlock>(w1: B, w2: B) -> B { w1 ^ w2 }
518
519         SymmetricDifference(BlockIter::from_blocks(TwoBitPositions {
520             set: self.bit_vec.blocks(),
521             other: other.bit_vec.blocks(),
522             merge: bitxor,
523         }))
524     }
525
526     /// Unions in-place with the specified other bit vector.
527     ///
528     /// # Examples
529     ///
530     /// ```
531     /// use bit_set::BitSet;
532     ///
533     /// let a   = 0b01101000;
534     /// let b   = 0b10100000;
535     /// let res = 0b11101000;
536     ///
537     /// let mut a = BitSet::from_bytes(&[a]);
538     /// let b = BitSet::from_bytes(&[b]);
539     /// let res = BitSet::from_bytes(&[res]);
540     ///
541     /// a.union_with(&b);
542     /// assert_eq!(a, res);
543     /// ```
544     #[inline]
545     pub fn union_with(&mut self, other: &Self) {
546         self.other_op(other, |w1, w2| w1 | w2);
547     }
548
549     /// Intersects in-place with the specified other bit vector.
550     ///
551     /// # Examples
552     ///
553     /// ```
554     /// use bit_set::BitSet;
555     ///
556     /// let a   = 0b01101000;
557     /// let b   = 0b10100000;
558     /// let res = 0b00100000;
559     ///
560     /// let mut a = BitSet::from_bytes(&[a]);
561     /// let b = BitSet::from_bytes(&[b]);
562     /// let res = BitSet::from_bytes(&[res]);
563     ///
564     /// a.intersect_with(&b);
565     /// assert_eq!(a, res);
566     /// ```
567     #[inline]
568     pub fn intersect_with(&mut self, other: &Self) {
569         self.other_op(other, |w1, w2| w1 & w2);
570     }
571
572     /// Makes this bit vector the difference with the specified other bit vector
573     /// in-place.
574     ///
575     /// # Examples
576     ///
577     /// ```
578     /// use bit_set::BitSet;
579     ///
580     /// let a   = 0b01101000;
581     /// let b   = 0b10100000;
582     /// let a_b = 0b01001000; // a - b
583     /// let b_a = 0b10000000; // b - a
584     ///
585     /// let mut bva = BitSet::from_bytes(&[a]);
586     /// let bvb = BitSet::from_bytes(&[b]);
587     /// let bva_b = BitSet::from_bytes(&[a_b]);
588     /// let bvb_a = BitSet::from_bytes(&[b_a]);
589     ///
590     /// bva.difference_with(&bvb);
591     /// assert_eq!(bva, bva_b);
592     ///
593     /// let bva = BitSet::from_bytes(&[a]);
594     /// let mut bvb = BitSet::from_bytes(&[b]);
595     ///
596     /// bvb.difference_with(&bva);
597     /// assert_eq!(bvb, bvb_a);
598     /// ```
599     #[inline]
600     pub fn difference_with(&mut self, other: &Self) {
601         self.other_op(other, |w1, w2| w1 & !w2);
602     }
603
604     /// Makes this bit vector the symmetric difference with the specified other
605     /// bit vector in-place.
606     ///
607     /// # Examples
608     ///
609     /// ```
610     /// use bit_set::BitSet;
611     ///
612     /// let a   = 0b01101000;
613     /// let b   = 0b10100000;
614     /// let res = 0b11001000;
615     ///
616     /// let mut a = BitSet::from_bytes(&[a]);
617     /// let b = BitSet::from_bytes(&[b]);
618     /// let res = BitSet::from_bytes(&[res]);
619     ///
620     /// a.symmetric_difference_with(&b);
621     /// assert_eq!(a, res);
622     /// ```
623     #[inline]
624     pub fn symmetric_difference_with(&mut self, other: &Self) {
625         self.other_op(other, |w1, w2| w1 ^ w2);
626     }
627
628 /*
629     /// Moves all elements from `other` into `Self`, leaving `other` empty.
630     ///
631     /// # Examples
632     ///
633     /// ```
634     /// use bit_set::BitSet;
635     ///
636     /// let mut a = BitSet::new();
637     /// a.insert(2);
638     /// a.insert(6);
639     ///
640     /// let mut b = BitSet::new();
641     /// b.insert(1);
642     /// b.insert(3);
643     /// b.insert(6);
644     ///
645     /// a.append(&mut b);
646     ///
647     /// assert_eq!(a.len(), 4);
648     /// assert_eq!(b.len(), 0);
649     /// assert_eq!(a, BitSet::from_bytes(&[0b01110010]));
650     /// ```
651     pub fn append(&mut self, other: &mut Self) {
652         self.union_with(other);
653         other.clear();
654     }
655
656     /// Splits the `BitSet` into two at the given key including the key.
657     /// Retains the first part in-place while returning the second part.
658     ///
659     /// # Examples
660     ///
661     /// ```
662     /// use bit_set::BitSet;
663     ///
664     /// let mut a = BitSet::new();
665     /// a.insert(2);
666     /// a.insert(6);
667     /// a.insert(1);
668     /// a.insert(3);
669     ///
670     /// let b = a.split_off(3);
671     ///
672     /// assert_eq!(a.len(), 2);
673     /// assert_eq!(b.len(), 2);
674     /// assert_eq!(a, BitSet::from_bytes(&[0b01100000]));
675     /// assert_eq!(b, BitSet::from_bytes(&[0b00010010]));
676     /// ```
677     pub fn split_off(&mut self, at: usize) -> Self {
678         let mut other = BitSet::new();
679
680         if at == 0 {
681             swap(self, &mut other);
682             return other;
683         } else if at >= self.bit_vec.len() {
684             return other;
685         }
686
687         // Calculate block and bit at which to split
688         let w = at / BITS;
689         let b = at % BITS;
690
691         // Pad `other` with `w` zero blocks,
692         // append `self`'s blocks in the range from `w` to the end to `other`
693         other.bit_vec.storage_mut().extend(repeat(0u32).take(w)
694                                      .chain(self.bit_vec.storage()[w..].iter().cloned()));
695         other.bit_vec.nbits = self.bit_vec.nbits;
696
697         if b > 0 {
698             other.bit_vec.storage_mut()[w] &= !0 << b;
699         }
700
701         // Sets `bit_vec.len()` and fixes the last block as well
702         self.bit_vec.truncate(at);
703
704         other
705     }
706 */
707
708     /// Returns the number of set bits in this set.
709     #[inline]
710     pub fn len(&self) -> usize  {
711         self.bit_vec.blocks().fold(0, |acc, n| acc + n.count_ones() as usize)
712     }
713
714     /// Returns whether there are no bits set in this set
715     #[inline]
716     pub fn is_empty(&self) -> bool {
717         self.bit_vec.none()
718     }
719
720     /// Clears all bits in this set
721     #[inline]
722     pub fn clear(&mut self) {
723         self.bit_vec.clear();
724     }
725
726     /// Returns `true` if this set contains the specified integer.
727     #[inline]
728     pub fn contains(&self, value: usize) -> bool {
729         let bit_vec = &self.bit_vec;
730         value < bit_vec.len() && bit_vec[value]
731     }
732
733     /// Returns `true` if the set has no elements in common with `other`.
734     /// This is equivalent to checking for an empty intersection.
735     #[inline]
736     pub fn is_disjoint(&self, other: &Self) -> bool {
737         self.intersection(other).next().is_none()
738     }
739
740     /// Returns `true` if the set is a subset of another.
741     #[inline]
742     pub fn is_subset(&self, other: &Self) -> bool {
743         let self_bit_vec = &self.bit_vec;
744         let other_bit_vec = &other.bit_vec;
745         let other_blocks = blocks_for_bits::<B>(other_bit_vec.len());
746
747         // Check that `self` intersect `other` is self
748         self_bit_vec.blocks().zip(other_bit_vec.blocks()).all(|(w1, w2)| w1 & w2 == w1) &&
749         // Make sure if `self` has any more blocks than `other`, they're all 0
750         self_bit_vec.blocks().skip(other_blocks).all(|w| w == B::zero())
751     }
752
753     /// Returns `true` if the set is a superset of another.
754     #[inline]
755     pub fn is_superset(&self, other: &Self) -> bool {
756         other.is_subset(self)
757     }
758
759     /// Adds a value to the set. Returns `true` if the value was not already
760     /// present in the set.
761     pub fn insert(&mut self, value: usize) -> bool {
762         if self.contains(value) {
763             return false;
764         }
765
766         // Ensure we have enough space to hold the new element
767         let len = self.bit_vec.len();
768         if value >= len {
769             self.bit_vec.grow(value - len + 1, false)
770         }
771
772         self.bit_vec.set(value, true);
773         return true;
774     }
775
776     /// Removes a value from the set. Returns `true` if the value was
777     /// present in the set.
778     pub fn remove(&mut self, value: usize) -> bool {
779         if !self.contains(value) {
780             return false;
781         }
782
783         self.bit_vec.set(value, false);
784
785         return true;
786     }
787 }
788
789 impl<B: BitBlock> fmt::Debug for BitSet<B> {
790     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
791         fmt.debug_set().entries(self).finish()
792     }
793 }
794
795 impl<B: BitBlock> hash::Hash for BitSet<B> {
796     fn hash<H: hash::Hasher>(&self, state: &mut H) {
797         for pos in self {
798             pos.hash(state);
799         }
800     }
801 }
802
803 #[derive(Clone)]
804 struct BlockIter<T, B> {
805     head: B,
806     head_offset: usize,
807     tail: T,
808 }
809
810 impl<T, B: BitBlock> BlockIter<T, B> where T: Iterator<Item=B> {
811     fn from_blocks(mut blocks: T) -> BlockIter<T, B> {
812         let h = blocks.next().unwrap_or(B::zero());
813         BlockIter {tail: blocks, head: h, head_offset: 0}
814     }
815 }
816
817 /// An iterator combining two `BitSet` iterators.
818 #[derive(Clone)]
819 struct TwoBitPositions<'a, B: 'a> {
820     set: Blocks<'a, B>,
821     other: Blocks<'a, B>,
822     merge: fn(B, B) -> B,
823 }
824
825 /// An iterator for `BitSet`.
826 #[derive(Clone)]
827 pub struct Iter<'a, B: 'a>(BlockIter<Blocks<'a, B>, B>);
828 #[derive(Clone)]
829 pub struct Union<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
830 #[derive(Clone)]
831 pub struct Intersection<'a, B: 'a>(Take<BlockIter<TwoBitPositions<'a, B>, B>>);
832 #[derive(Clone)]
833 pub struct Difference<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
834 #[derive(Clone)]
835 pub struct SymmetricDifference<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
836
837 impl<'a, T, B: BitBlock> Iterator for BlockIter<T, B> where T: Iterator<Item=B> {
838     type Item = usize;
839
840     fn next(&mut self) -> Option<usize> {
841         while self.head == B::zero() {
842             match self.tail.next() {
843                 Some(w) => self.head = w,
844                 None => return None
845             }
846             self.head_offset += B::bits();
847         }
848
849         // from the current block, isolate the
850         // LSB and subtract 1, producing k:
851         // a block with a number of set bits
852         // equal to the index of the LSB
853         let k = (self.head & (!self.head + B::one())) - B::one();
854         // update block, removing the LSB
855         self.head = self.head & (self.head - B::one());
856         // return offset + (index of LSB)
857         Some(self.head_offset + (B::count_ones(k) as usize))
858     }
859
860     #[inline]
861     fn size_hint(&self) -> (usize, Option<usize>) {
862         match self.tail.size_hint() {
863             (_, Some(h)) => (0, Some(1 + h * B::bits())),
864             _ => (0, None)
865         }
866     }
867 }
868
869 impl<'a, B: BitBlock> Iterator for TwoBitPositions<'a, B> {
870     type Item = B;
871
872     fn next(&mut self) -> Option<B> {
873         match (self.set.next(), self.other.next()) {
874             (Some(a), Some(b)) => Some((self.merge)(a, b)),
875             (Some(a), None) => Some((self.merge)(a, B::zero())),
876             (None, Some(b)) => Some((self.merge)(B::zero(), b)),
877             _ => return None
878         }
879     }
880
881     #[inline]
882     fn size_hint(&self) -> (usize, Option<usize>) {
883         let (a, au) = self.set.size_hint();
884         let (b, bu) = self.other.size_hint();
885
886         let upper = match (au, bu) {
887             (Some(au), Some(bu)) => Some(cmp::max(au, bu)),
888             _ => None
889         };
890
891         (cmp::max(a, b), upper)
892     }
893 }
894
895 impl<'a, B: BitBlock> Iterator for Iter<'a, B> {
896     type Item = usize;
897
898     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
899     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
900 }
901
902 impl<'a, B: BitBlock> Iterator for Union<'a, B> {
903     type Item = usize;
904
905     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
906     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
907 }
908
909 impl<'a, B: BitBlock> Iterator for Intersection<'a, B> {
910     type Item = usize;
911
912     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
913     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
914 }
915
916 impl<'a, B: BitBlock> Iterator for Difference<'a, B> {
917     type Item = usize;
918
919     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
920     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
921 }
922
923 impl<'a, B: BitBlock> Iterator for SymmetricDifference<'a, B> {
924     type Item = usize;
925
926     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
927     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
928 }
929
930 impl<'a, B: BitBlock> IntoIterator for &'a BitSet<B> {
931     type Item = usize;
932     type IntoIter = Iter<'a, B>;
933
934     fn into_iter(self) -> Iter<'a, B> {
935         self.iter()
936     }
937 }
938
939 #[cfg(test)]
940 mod tests {
941     use std::cmp::Ordering::{Equal, Greater, Less};
942     use super::BitSet;
943     use bit_vec::BitVec;
944
945     #[test]
946     fn test_bit_set_show() {
947         let mut s = BitSet::new();
948         s.insert(1);
949         s.insert(10);
950         s.insert(50);
951         s.insert(2);
952         assert_eq!("{1, 2, 10, 50}", format!("{:?}", s));
953     }
954
955     #[test]
956     fn test_bit_set_from_usizes() {
957         let usizes = vec![0, 2, 2, 3];
958         let a: BitSet = usizes.into_iter().collect();
959         let mut b = BitSet::new();
960         b.insert(0);
961         b.insert(2);
962         b.insert(3);
963         assert_eq!(a, b);
964     }
965
966     #[test]
967     fn test_bit_set_iterator() {
968         let usizes = vec![0, 2, 2, 3];
969         let bit_vec: BitSet = usizes.into_iter().collect();
970
971         let idxs: Vec<_> = bit_vec.iter().collect();
972         assert_eq!(idxs, [0, 2, 3]);
973
974         let long: BitSet = (0..10000).filter(|&n| n % 2 == 0).collect();
975         let real: Vec<_> = (0..10000/2).map(|x| x*2).collect();
976
977         let idxs: Vec<_> = long.iter().collect();
978         assert_eq!(idxs, real);
979     }
980
981     #[test]
982     fn test_bit_set_frombit_vec_init() {
983         let bools = [true, false];
984         let lengths = [10, 64, 100];
985         for &b in &bools {
986             for &l in &lengths {
987                 let bitset = BitSet::from_bit_vec(BitVec::from_elem(l, b));
988                 assert_eq!(bitset.contains(1), b);
989                 assert_eq!(bitset.contains((l-1)), b);
990                 assert!(!bitset.contains(l));
991             }
992         }
993     }
994
995     #[test]
996     fn test_bit_vec_masking() {
997         let b = BitVec::from_elem(140, true);
998         let mut bs = BitSet::from_bit_vec(b);
999         assert!(bs.contains(139));
1000         assert!(!bs.contains(140));
1001         assert!(bs.insert(150));
1002         assert!(!bs.contains(140));
1003         assert!(!bs.contains(149));
1004         assert!(bs.contains(150));
1005         assert!(!bs.contains(151));
1006     }
1007
1008     #[test]
1009     fn test_bit_set_basic() {
1010         let mut b = BitSet::new();
1011         assert!(b.insert(3));
1012         assert!(!b.insert(3));
1013         assert!(b.contains(3));
1014         assert!(b.insert(4));
1015         assert!(!b.insert(4));
1016         assert!(b.contains(3));
1017         assert!(b.insert(400));
1018         assert!(!b.insert(400));
1019         assert!(b.contains(400));
1020         assert_eq!(b.len(), 3);
1021     }
1022
1023     #[test]
1024     fn test_bit_set_intersection() {
1025         let mut a = BitSet::new();
1026         let mut b = BitSet::new();
1027
1028         assert!(a.insert(11));
1029         assert!(a.insert(1));
1030         assert!(a.insert(3));
1031         assert!(a.insert(77));
1032         assert!(a.insert(103));
1033         assert!(a.insert(5));
1034
1035         assert!(b.insert(2));
1036         assert!(b.insert(11));
1037         assert!(b.insert(77));
1038         assert!(b.insert(5));
1039         assert!(b.insert(3));
1040
1041         let expected = [3, 5, 11, 77];
1042         let actual: Vec<_> = a.intersection(&b).collect();
1043         assert_eq!(actual, expected);
1044     }
1045
1046     #[test]
1047     fn test_bit_set_difference() {
1048         let mut a = BitSet::new();
1049         let mut b = BitSet::new();
1050
1051         assert!(a.insert(1));
1052         assert!(a.insert(3));
1053         assert!(a.insert(5));
1054         assert!(a.insert(200));
1055         assert!(a.insert(500));
1056
1057         assert!(b.insert(3));
1058         assert!(b.insert(200));
1059
1060         let expected = [1, 5, 500];
1061         let actual: Vec<_> = a.difference(&b).collect();
1062         assert_eq!(actual, expected);
1063     }
1064
1065     #[test]
1066     fn test_bit_set_symmetric_difference() {
1067         let mut a = BitSet::new();
1068         let mut b = BitSet::new();
1069
1070         assert!(a.insert(1));
1071         assert!(a.insert(3));
1072         assert!(a.insert(5));
1073         assert!(a.insert(9));
1074         assert!(a.insert(11));
1075
1076         assert!(b.insert(3));
1077         assert!(b.insert(9));
1078         assert!(b.insert(14));
1079         assert!(b.insert(220));
1080
1081         let expected = [1, 5, 11, 14, 220];
1082         let actual: Vec<_> = a.symmetric_difference(&b).collect();
1083         assert_eq!(actual, expected);
1084     }
1085
1086     #[test]
1087     fn test_bit_set_union() {
1088         let mut a = BitSet::new();
1089         let mut b = BitSet::new();
1090         assert!(a.insert(1));
1091         assert!(a.insert(3));
1092         assert!(a.insert(5));
1093         assert!(a.insert(9));
1094         assert!(a.insert(11));
1095         assert!(a.insert(160));
1096         assert!(a.insert(19));
1097         assert!(a.insert(24));
1098         assert!(a.insert(200));
1099
1100         assert!(b.insert(1));
1101         assert!(b.insert(5));
1102         assert!(b.insert(9));
1103         assert!(b.insert(13));
1104         assert!(b.insert(19));
1105
1106         let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160, 200];
1107         let actual: Vec<_> = a.union(&b).collect();
1108         assert_eq!(actual, expected);
1109     }
1110
1111     #[test]
1112     fn test_bit_set_subset() {
1113         let mut set1 = BitSet::new();
1114         let mut set2 = BitSet::new();
1115
1116         assert!(set1.is_subset(&set2)); //  {}  {}
1117         set2.insert(100);
1118         assert!(set1.is_subset(&set2)); //  {}  { 1 }
1119         set2.insert(200);
1120         assert!(set1.is_subset(&set2)); //  {}  { 1, 2 }
1121         set1.insert(200);
1122         assert!(set1.is_subset(&set2)); //  { 2 }  { 1, 2 }
1123         set1.insert(300);
1124         assert!(!set1.is_subset(&set2)); // { 2, 3 }  { 1, 2 }
1125         set2.insert(300);
1126         assert!(set1.is_subset(&set2)); // { 2, 3 }  { 1, 2, 3 }
1127         set2.insert(400);
1128         assert!(set1.is_subset(&set2)); // { 2, 3 }  { 1, 2, 3, 4 }
1129         set2.remove(100);
1130         assert!(set1.is_subset(&set2)); // { 2, 3 }  { 2, 3, 4 }
1131         set2.remove(300);
1132         assert!(!set1.is_subset(&set2)); // { 2, 3 }  { 2, 4 }
1133         set1.remove(300);
1134         assert!(set1.is_subset(&set2)); // { 2 }  { 2, 4 }
1135     }
1136
1137     #[test]
1138     fn test_bit_set_is_disjoint() {
1139         let a = BitSet::from_bytes(&[0b10100010]);
1140         let b = BitSet::from_bytes(&[0b01000000]);
1141         let c = BitSet::new();
1142         let d = BitSet::from_bytes(&[0b00110000]);
1143
1144         assert!(!a.is_disjoint(&d));
1145         assert!(!d.is_disjoint(&a));
1146
1147         assert!(a.is_disjoint(&b));
1148         assert!(a.is_disjoint(&c));
1149         assert!(b.is_disjoint(&a));
1150         assert!(b.is_disjoint(&c));
1151         assert!(c.is_disjoint(&a));
1152         assert!(c.is_disjoint(&b));
1153     }
1154
1155     #[test]
1156     fn test_bit_set_union_with() {
1157         //a should grow to include larger elements
1158         let mut a = BitSet::new();
1159         a.insert(0);
1160         let mut b = BitSet::new();
1161         b.insert(5);
1162         let expected = BitSet::from_bytes(&[0b10000100]);
1163         a.union_with(&b);
1164         assert_eq!(a, expected);
1165
1166         // Standard
1167         let mut a = BitSet::from_bytes(&[0b10100010]);
1168         let mut b = BitSet::from_bytes(&[0b01100010]);
1169         let c = a.clone();
1170         a.union_with(&b);
1171         b.union_with(&c);
1172         assert_eq!(a.len(), 4);
1173         assert_eq!(b.len(), 4);
1174     }
1175
1176     #[test]
1177     fn test_bit_set_intersect_with() {
1178         // Explicitly 0'ed bits
1179         let mut a = BitSet::from_bytes(&[0b10100010]);
1180         let mut b = BitSet::from_bytes(&[0b00000000]);
1181         let c = a.clone();
1182         a.intersect_with(&b);
1183         b.intersect_with(&c);
1184         assert!(a.is_empty());
1185         assert!(b.is_empty());
1186
1187         // Uninitialized bits should behave like 0's
1188         let mut a = BitSet::from_bytes(&[0b10100010]);
1189         let mut b = BitSet::new();
1190         let c = a.clone();
1191         a.intersect_with(&b);
1192         b.intersect_with(&c);
1193         assert!(a.is_empty());
1194         assert!(b.is_empty());
1195
1196         // Standard
1197         let mut a = BitSet::from_bytes(&[0b10100010]);
1198         let mut b = BitSet::from_bytes(&[0b01100010]);
1199         let c = a.clone();
1200         a.intersect_with(&b);
1201         b.intersect_with(&c);
1202         assert_eq!(a.len(), 2);
1203         assert_eq!(b.len(), 2);
1204     }
1205
1206     #[test]
1207     fn test_bit_set_difference_with() {
1208         // Explicitly 0'ed bits
1209         let mut a = BitSet::from_bytes(&[0b00000000]);
1210         let b = BitSet::from_bytes(&[0b10100010]);
1211         a.difference_with(&b);
1212         assert!(a.is_empty());
1213
1214         // Uninitialized bits should behave like 0's
1215         let mut a = BitSet::new();
1216         let b = BitSet::from_bytes(&[0b11111111]);
1217         a.difference_with(&b);
1218         assert!(a.is_empty());
1219
1220         // Standard
1221         let mut a = BitSet::from_bytes(&[0b10100010]);
1222         let mut b = BitSet::from_bytes(&[0b01100010]);
1223         let c = a.clone();
1224         a.difference_with(&b);
1225         b.difference_with(&c);
1226         assert_eq!(a.len(), 1);
1227         assert_eq!(b.len(), 1);
1228     }
1229
1230     #[test]
1231     fn test_bit_set_symmetric_difference_with() {
1232         //a should grow to include larger elements
1233         let mut a = BitSet::new();
1234         a.insert(0);
1235         a.insert(1);
1236         let mut b = BitSet::new();
1237         b.insert(1);
1238         b.insert(5);
1239         let expected = BitSet::from_bytes(&[0b10000100]);
1240         a.symmetric_difference_with(&b);
1241         assert_eq!(a, expected);
1242
1243         let mut a = BitSet::from_bytes(&[0b10100010]);
1244         let b = BitSet::new();
1245         let c = a.clone();
1246         a.symmetric_difference_with(&b);
1247         assert_eq!(a, c);
1248
1249         // Standard
1250         let mut a = BitSet::from_bytes(&[0b11100010]);
1251         let mut b = BitSet::from_bytes(&[0b01101010]);
1252         let c = a.clone();
1253         a.symmetric_difference_with(&b);
1254         b.symmetric_difference_with(&c);
1255         assert_eq!(a.len(), 2);
1256         assert_eq!(b.len(), 2);
1257     }
1258
1259     #[test]
1260     fn test_bit_set_eq() {
1261         let a = BitSet::from_bytes(&[0b10100010]);
1262         let b = BitSet::from_bytes(&[0b00000000]);
1263         let c = BitSet::new();
1264
1265         assert!(a == a);
1266         assert!(a != b);
1267         assert!(a != c);
1268         assert!(b == b);
1269         assert!(b == c);
1270         assert!(c == c);
1271     }
1272
1273     #[test]
1274     fn test_bit_set_cmp() {
1275         let a = BitSet::from_bytes(&[0b10100010]);
1276         let b = BitSet::from_bytes(&[0b00000000]);
1277         let c = BitSet::new();
1278
1279         assert_eq!(a.cmp(&b), Greater);
1280         assert_eq!(a.cmp(&c), Greater);
1281         assert_eq!(b.cmp(&a), Less);
1282         assert_eq!(b.cmp(&c), Equal);
1283         assert_eq!(c.cmp(&a), Less);
1284         assert_eq!(c.cmp(&b), Equal);
1285     }
1286
1287     #[test]
1288     fn test_bit_vec_remove() {
1289         let mut a = BitSet::new();
1290
1291         assert!(a.insert(1));
1292         assert!(a.remove(1));
1293
1294         assert!(a.insert(100));
1295         assert!(a.remove(100));
1296
1297         assert!(a.insert(1000));
1298         assert!(a.remove(1000));
1299         a.shrink_to_fit();
1300     }
1301
1302     #[test]
1303     fn test_bit_vec_clone() {
1304         let mut a = BitSet::new();
1305
1306         assert!(a.insert(1));
1307         assert!(a.insert(100));
1308         assert!(a.insert(1000));
1309
1310         let mut b = a.clone();
1311
1312         assert!(a == b);
1313
1314         assert!(b.remove(1));
1315         assert!(a.contains(1));
1316
1317         assert!(a.remove(1000));
1318         assert!(b.contains(1000));
1319     }
1320
1321 /*
1322     #[test]
1323     fn test_bit_set_append() {
1324         let mut a = BitSet::new();
1325         a.insert(2);
1326         a.insert(6);
1327
1328         let mut b = BitSet::new();
1329         b.insert(1);
1330         b.insert(3);
1331         b.insert(6);
1332
1333         a.append(&mut b);
1334
1335         assert_eq!(a.len(), 4);
1336         assert_eq!(b.len(), 0);
1337         assert!(b.capacity() >= 6);
1338
1339         assert_eq!(a, BitSet::from_bytes(&[0b01110010]));
1340     }
1341
1342     #[test]
1343     fn test_bit_set_split_off() {
1344         // Split at 0
1345         let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1346                                          0b00110011, 0b01101011, 0b10101101]);
1347
1348         let b = a.split_off(0);
1349
1350         assert_eq!(a.len(), 0);
1351         assert_eq!(b.len(), 21);
1352
1353         assert_eq!(b, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1354                                            0b00110011, 0b01101011, 0b10101101]);
1355
1356         // Split behind last element
1357         let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1358                                          0b00110011, 0b01101011, 0b10101101]);
1359
1360         let b = a.split_off(50);
1361
1362         assert_eq!(a.len(), 21);
1363         assert_eq!(b.len(), 0);
1364
1365         assert_eq!(a, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1366                                            0b00110011, 0b01101011, 0b10101101]));
1367
1368         // Split at arbitrary element
1369         let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1370                                          0b00110011, 0b01101011, 0b10101101]);
1371
1372         let b = a.split_off(34);
1373
1374         assert_eq!(a.len(), 12);
1375         assert_eq!(b.len(), 9);
1376
1377         assert_eq!(a, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1378                                            0b00110011, 0b01000000]));
1379         assert_eq!(b, BitSet::from_bytes(&[0, 0, 0, 0,
1380                                            0b00101011, 0b10101101]));
1381     }
1382 */
1383 }
1384
1385 #[cfg(all(test, feature = "nightly"))]
1386 mod bench {
1387     use super::BitSet;
1388     use bit_vec::BitVec;
1389     use rand::{Rng, thread_rng, ThreadRng};
1390
1391     use test::{Bencher, black_box};
1392
1393     const BENCH_BITS: usize = 1 << 14;
1394     const BITS: usize = 32;
1395
1396     fn rng() -> ThreadRng {
1397         thread_rng()
1398     }
1399
1400     #[bench]
1401     fn bench_bit_vecset_small(b: &mut Bencher) {
1402         let mut r = rng();
1403         let mut bit_vec = BitSet::new();
1404         b.iter(|| {
1405             for _ in 0..100 {
1406                 bit_vec.insert((r.next_u32() as usize) % BITS);
1407             }
1408             black_box(&bit_vec);
1409         });
1410     }
1411
1412     #[bench]
1413     fn bench_bit_vecset_big(b: &mut Bencher) {
1414         let mut r = rng();
1415         let mut bit_vec = BitSet::new();
1416         b.iter(|| {
1417             for _ in 0..100 {
1418                 bit_vec.insert((r.next_u32() as usize) % BENCH_BITS);
1419             }
1420             black_box(&bit_vec);
1421         });
1422     }
1423
1424     #[bench]
1425     fn bench_bit_vecset_iter(b: &mut Bencher) {
1426         let bit_vec = BitSet::from_bit_vec(BitVec::from_fn(BENCH_BITS,
1427                                               |idx| {idx % 3 == 0}));
1428         b.iter(|| {
1429             let mut sum = 0;
1430             for idx in &bit_vec {
1431                 sum += idx as usize;
1432             }
1433             sum
1434         })
1435     }
1436 }