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