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