]> git.lizzy.rs Git - rust.git/blob - src/libcollections/bit.rs
Add a doctest for the std::string::as_string method.
[rust.git] / src / libcollections / bit.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 // FIXME(Gankro): Bitv and BitvSet are very tightly coupled. Ideally (for maintenance),
12 // they should be in separate files/modules, with BitvSet only using Bitv's public API.
13
14 //! Collections implemented with bit vectors.
15 //!
16 //! # Example
17 //!
18 //! This is a simple example of the [Sieve of Eratosthenes][sieve]
19 //! which calculates prime numbers up to a given limit.
20 //!
21 //! [sieve]: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
22 //!
23 //! ```
24 //! use std::collections::{BitvSet, Bitv};
25 //! use std::num::Float;
26 //! use std::iter;
27 //!
28 //! let max_prime = 10000;
29 //!
30 //! // Store the primes as a BitvSet
31 //! let primes = {
32 //!     // Assume all numbers are prime to begin, and then we
33 //!     // cross off non-primes progressively
34 //!     let mut bv = Bitv::with_capacity(max_prime, true);
35 //!
36 //!     // Neither 0 nor 1 are prime
37 //!     bv.set(0, false);
38 //!     bv.set(1, false);
39 //!
40 //!     for i in iter::range_inclusive(2, (max_prime as f64).sqrt() as uint) {
41 //!         // if i is a prime
42 //!         if bv[i] {
43 //!             // Mark all multiples of i as non-prime (any multiples below i * i
44 //!             // will have been marked as non-prime previously)
45 //!             for j in iter::range_step(i * i, max_prime, i) { bv.set(j, false) }
46 //!         }
47 //!     }
48 //!     BitvSet::from_bitv(bv)
49 //! };
50 //!
51 //! // Simple primality tests below our max bound
52 //! let print_primes = 20;
53 //! print!("The primes below {} are: ", print_primes);
54 //! for x in range(0, print_primes) {
55 //!     if primes.contains(&x) {
56 //!         print!("{} ", x);
57 //!     }
58 //! }
59 //! println!("");
60 //!
61 //! // We can manipulate the internal Bitv
62 //! let num_primes = primes.get_ref().iter().filter(|x| *x).count();
63 //! println!("There are {} primes below {}", num_primes, max_prime);
64 //! ```
65
66 use core::prelude::*;
67
68 use core::cmp;
69 use core::default::Default;
70 use core::fmt;
71 use core::iter::{Chain, Enumerate, Repeat, Skip, Take, repeat};
72 use core::iter;
73 use core::num::Int;
74 use core::slice;
75 use core::u32;
76 use std::hash;
77
78 use vec::Vec;
79
80 // FIXME(conventions): look, we just need to refactor this whole thing. Inside and out.
81
82 type MatchWords<'a> = Chain<MaskWords<'a>, Skip<Take<Enumerate<Repeat<u32>>>>>;
83 // Take two BitV's, and return iterators of their words, where the shorter one
84 // has been padded with 0's
85 fn match_words <'a,'b>(a: &'a Bitv, b: &'b Bitv) -> (MatchWords<'a>, MatchWords<'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.mask_words(0).chain(repeat(0u32).enumerate().take(b_len).skip(a_len)),
92          b.mask_words(0).chain(repeat(0u32).enumerate().take(0).skip(0)))
93     } else {
94         (a.mask_words(0).chain(repeat(0u32).enumerate().take(0).skip(0)),
95          b.mask_words(0).chain(repeat(0u32).enumerate().take(a_len).skip(b_len)))
96     }
97 }
98
99 static TRUE: bool = true;
100 static FALSE: bool = false;
101
102 /// The bitvector type.
103 ///
104 /// # Example
105 ///
106 /// ```rust
107 /// use collections::Bitv;
108 ///
109 /// let mut bv = Bitv::with_capacity(10, false);
110 ///
111 /// // insert all primes less than 10
112 /// bv.set(2, true);
113 /// bv.set(3, true);
114 /// bv.set(5, true);
115 /// bv.set(7, true);
116 /// println!("{}", bv.to_string());
117 /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
118 ///
119 /// // flip all values in bitvector, producing non-primes less than 10
120 /// bv.negate();
121 /// println!("{}", bv.to_string());
122 /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
123 ///
124 /// // reset bitvector to empty
125 /// bv.clear();
126 /// println!("{}", bv.to_string());
127 /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
128 /// ```
129 pub struct Bitv {
130     /// Internal representation of the bit vector
131     storage: Vec<u32>,
132     /// The number of valid bits in the internal representation
133     nbits: uint
134 }
135
136 impl Index<uint,bool> for Bitv {
137     #[inline]
138     fn index<'a>(&'a self, i: &uint) -> &'a bool {
139         if self.get(*i) {
140             &TRUE
141         } else {
142             &FALSE
143         }
144     }
145 }
146
147 struct MaskWords<'a> {
148     iter: slice::Items<'a, u32>,
149     next_word: Option<&'a u32>,
150     last_word_mask: u32,
151     offset: uint
152 }
153
154 impl<'a> Iterator<(uint, u32)> for MaskWords<'a> {
155     /// Returns (offset, word)
156     #[inline]
157     fn next<'a>(&'a mut self) -> Option<(uint, u32)> {
158         let ret = self.next_word;
159         match ret {
160             Some(&w) => {
161                 self.next_word = self.iter.next();
162                 self.offset += 1;
163                 // The last word may need to be masked
164                 if self.next_word.is_none() {
165                     Some((self.offset - 1, w & self.last_word_mask))
166                 } else {
167                     Some((self.offset - 1, w))
168                 }
169             },
170             None => None
171         }
172     }
173 }
174
175 impl Bitv {
176     #[inline]
177     fn process(&mut self, other: &Bitv, op: |u32, u32| -> u32) -> bool {
178         let len = other.storage.len();
179         assert_eq!(self.storage.len(), len);
180         let mut changed = false;
181         // Notice: `a` is *not* masked here, which is fine as long as
182         // `op` is a bitwise operation, since any bits that should've
183         // been masked were fine to change anyway. `b` is masked to
184         // make sure its unmasked bits do not cause damage.
185         for (a, (_, b)) in self.storage.iter_mut()
186                            .zip(other.mask_words(0)) {
187             let w = op(*a, b);
188             if *a != w {
189                 changed = true;
190                 *a = w;
191             }
192         }
193         changed
194     }
195
196     #[inline]
197     fn mask_words<'a>(&'a self, mut start: uint) -> MaskWords<'a> {
198         if start > self.storage.len() {
199             start = self.storage.len();
200         }
201         let mut iter = self.storage[start..].iter();
202         MaskWords {
203           next_word: iter.next(),
204           iter: iter,
205           last_word_mask: {
206               let rem = self.nbits % u32::BITS;
207               if rem > 0 {
208                   (1 << rem) - 1
209               } else { !0 }
210           },
211           offset: start
212         }
213     }
214
215     /// Creates an empty `Bitv`.
216     ///
217     /// # Example
218     ///
219     /// ```
220     /// use std::collections::Bitv;
221     /// let mut bv = Bitv::new();
222     /// ```
223     #[unstable = "matches collection reform specification, waiting for dust to settle"]
224     pub fn new() -> Bitv {
225         Bitv { storage: Vec::new(), nbits: 0 }
226     }
227
228     /// Creates a `Bitv` that holds `nbits` elements, setting each element
229     /// to `init`.
230     ///
231     /// # Example
232     ///
233     /// ```
234     /// use std::collections::Bitv;
235     ///
236     /// let mut bv = Bitv::with_capacity(10u, false);
237     /// assert_eq!(bv.len(), 10u);
238     /// for x in bv.iter() {
239     ///     assert_eq!(x, false);
240     /// }
241     /// ```
242     pub fn with_capacity(nbits: uint, init: bool) -> Bitv {
243         let mut bitv = Bitv {
244             storage: Vec::from_elem((nbits + u32::BITS - 1) / u32::BITS,
245                                     if init { !0u32 } else { 0u32 }),
246             nbits: nbits
247         };
248
249         // Zero out any unused bits in the highest word if necessary
250         let used_bits = bitv.nbits % u32::BITS;
251         if init && used_bits != 0 {
252             let largest_used_word = (bitv.nbits + u32::BITS - 1) / u32::BITS - 1;
253             bitv.storage[largest_used_word] &= (1 << used_bits) - 1;
254         }
255
256         bitv
257     }
258
259     /// Retrieves the value at index `i`.
260     ///
261     /// # Panics
262     ///
263     /// Panics if `i` is out of bounds.
264     ///
265     /// # Example
266     ///
267     /// ```
268     /// use std::collections::bitv;
269     ///
270     /// let bv = bitv::from_bytes(&[0b01100000]);
271     /// assert_eq!(bv.get(0), false);
272     /// assert_eq!(bv.get(1), true);
273     ///
274     /// // Can also use array indexing
275     /// assert_eq!(bv[1], true);
276     /// ```
277     #[inline]
278     pub fn get(&self, i: uint) -> bool {
279         assert!(i < self.nbits);
280         let w = i / u32::BITS;
281         let b = i % u32::BITS;
282         let x = self.storage[w] & (1 << b);
283         x != 0
284     }
285
286     /// Sets the value of a bit at an index `i`.
287     ///
288     /// # Panics
289     ///
290     /// Panics if `i` is out of bounds.
291     ///
292     /// # Example
293     ///
294     /// ```
295     /// use std::collections::Bitv;
296     ///
297     /// let mut bv = Bitv::with_capacity(5, false);
298     /// bv.set(3, true);
299     /// assert_eq!(bv[3], true);
300     /// ```
301     #[inline]
302     pub fn set(&mut self, i: uint, x: bool) {
303         assert!(i < self.nbits);
304         let w = i / u32::BITS;
305         let b = i % u32::BITS;
306         let flag = 1 << b;
307         let val = if x { self.storage[w] | flag }
308                   else { self.storage[w] & !flag };
309         self.storage[w] = val;
310     }
311
312     /// Sets all bits to 1.
313     ///
314     /// # Example
315     ///
316     /// ```
317     /// use std::collections::bitv;
318     ///
319     /// let before = 0b01100000;
320     /// let after  = 0b11111111;
321     ///
322     /// let mut bv = bitv::from_bytes(&[before]);
323     /// bv.set_all();
324     /// assert_eq!(bv, bitv::from_bytes(&[after]));
325     /// ```
326     #[inline]
327     pub fn set_all(&mut self) {
328         for w in self.storage.iter_mut() { *w = !0u32; }
329     }
330
331     /// Flips all bits.
332     ///
333     /// # Example
334     ///
335     /// ```
336     /// use std::collections::bitv;
337     ///
338     /// let before = 0b01100000;
339     /// let after  = 0b10011111;
340     ///
341     /// let mut bv = bitv::from_bytes(&[before]);
342     /// bv.negate();
343     /// assert_eq!(bv, bitv::from_bytes(&[after]));
344     /// ```
345     #[inline]
346     pub fn negate(&mut self) {
347         for w in self.storage.iter_mut() { *w = !*w; }
348     }
349
350     /// Calculates the union of two bitvectors. This acts like the bitwise `or`
351     /// function.
352     ///
353     /// Sets `self` to the union of `self` and `other`. Both bitvectors must be
354     /// the same length. Returns `true` if `self` changed.
355     ///
356     /// # Panics
357     ///
358     /// Panics if the bitvectors are of different lengths.
359     ///
360     /// # Example
361     ///
362     /// ```
363     /// use std::collections::bitv;
364     ///
365     /// let a   = 0b01100100;
366     /// let b   = 0b01011010;
367     /// let res = 0b01111110;
368     ///
369     /// let mut a = bitv::from_bytes(&[a]);
370     /// let b = bitv::from_bytes(&[b]);
371     ///
372     /// assert!(a.union(&b));
373     /// assert_eq!(a, bitv::from_bytes(&[res]));
374     /// ```
375     #[inline]
376     pub fn union(&mut self, other: &Bitv) -> bool {
377         self.process(other, |w1, w2| w1 | w2)
378     }
379
380     /// Calculates the intersection of two bitvectors. This acts like the
381     /// bitwise `and` function.
382     ///
383     /// Sets `self` to the intersection of `self` and `other`. Both bitvectors
384     /// must be the same length. Returns `true` if `self` changed.
385     ///
386     /// # Panics
387     ///
388     /// Panics if the bitvectors are of different lengths.
389     ///
390     /// # Example
391     ///
392     /// ```
393     /// use std::collections::bitv;
394     ///
395     /// let a   = 0b01100100;
396     /// let b   = 0b01011010;
397     /// let res = 0b01000000;
398     ///
399     /// let mut a = bitv::from_bytes(&[a]);
400     /// let b = bitv::from_bytes(&[b]);
401     ///
402     /// assert!(a.intersect(&b));
403     /// assert_eq!(a, bitv::from_bytes(&[res]));
404     /// ```
405     #[inline]
406     pub fn intersect(&mut self, other: &Bitv) -> bool {
407         self.process(other, |w1, w2| w1 & w2)
408     }
409
410     /// Calculates the difference between two bitvectors.
411     ///
412     /// Sets each element of `self` to the value of that element minus the
413     /// element of `other` at the same index. Both bitvectors must be the same
414     /// length. Returns `true` if `self` changed.
415     ///
416     /// # Panics
417     ///
418     /// Panics if the bitvectors are of different length.
419     ///
420     /// # Example
421     ///
422     /// ```
423     /// use std::collections::bitv;
424     ///
425     /// let a   = 0b01100100;
426     /// let b   = 0b01011010;
427     /// let a_b = 0b00100100; // a - b
428     /// let b_a = 0b00011010; // b - a
429     ///
430     /// let mut bva = bitv::from_bytes(&[a]);
431     /// let bvb = bitv::from_bytes(&[b]);
432     ///
433     /// assert!(bva.difference(&bvb));
434     /// assert_eq!(bva, bitv::from_bytes(&[a_b]));
435     ///
436     /// let bva = bitv::from_bytes(&[a]);
437     /// let mut bvb = bitv::from_bytes(&[b]);
438     ///
439     /// assert!(bvb.difference(&bva));
440     /// assert_eq!(bvb, bitv::from_bytes(&[b_a]));
441     /// ```
442     #[inline]
443     pub fn difference(&mut self, other: &Bitv) -> bool {
444         self.process(other, |w1, w2| w1 & !w2)
445     }
446
447     /// Returns `true` if all bits are 1.
448     ///
449     /// # Example
450     ///
451     /// ```
452     /// use std::collections::Bitv;
453     ///
454     /// let mut bv = Bitv::with_capacity(5, true);
455     /// assert_eq!(bv.all(), true);
456     ///
457     /// bv.set(1, false);
458     /// assert_eq!(bv.all(), false);
459     /// ```
460     #[inline]
461     pub fn all(&self) -> bool {
462         let mut last_word = !0u32;
463         // Check that every word but the last is all-ones...
464         self.mask_words(0).all(|(_, elem)|
465             { let tmp = last_word; last_word = elem; tmp == !0u32 }) &&
466         // ...and that the last word is ones as far as it needs to be
467         (last_word == ((1 << self.nbits % u32::BITS) - 1) || last_word == !0u32)
468     }
469
470     /// Returns an iterator over the elements of the vector in order.
471     ///
472     /// # Example
473     ///
474     /// ```
475     /// use std::collections::bitv;
476     ///
477     /// let bv = bitv::from_bytes(&[0b01110100, 0b10010010]);
478     /// assert_eq!(bv.iter().filter(|x| *x).count(), 7);
479     /// ```
480     #[inline]
481     pub fn iter<'a>(&'a self) -> Bits<'a> {
482         Bits {bitv: self, next_idx: 0, end_idx: self.nbits}
483     }
484
485     /// Returns `true` if all bits are 0.
486     ///
487     /// # Example
488     ///
489     /// ```
490     /// use std::collections::Bitv;
491     ///
492     /// let mut bv = Bitv::with_capacity(10, false);
493     /// assert_eq!(bv.none(), true);
494     ///
495     /// bv.set(3, true);
496     /// assert_eq!(bv.none(), false);
497     /// ```
498     pub fn none(&self) -> bool {
499         self.mask_words(0).all(|(_, w)| w == 0)
500     }
501
502     /// Returns `true` if any bit is 1.
503     ///
504     /// # Example
505     ///
506     /// ```
507     /// use std::collections::Bitv;
508     ///
509     /// let mut bv = Bitv::with_capacity(10, false);
510     /// assert_eq!(bv.any(), false);
511     ///
512     /// bv.set(3, true);
513     /// assert_eq!(bv.any(), true);
514     /// ```
515     #[inline]
516     pub fn any(&self) -> bool {
517         !self.none()
518     }
519
520     /// Organises the bits into bytes, such that the first bit in the
521     /// `Bitv` becomes the high-order bit of the first byte. If the
522     /// size of the `Bitv` is not a multiple of eight then trailing bits
523     /// will be filled-in with `false`.
524     ///
525     /// # Example
526     ///
527     /// ```
528     /// use std::collections::Bitv;
529     ///
530     /// let mut bv = Bitv::with_capacity(3, true);
531     /// bv.set(1, false);
532     ///
533     /// assert_eq!(bv.to_bytes(), vec!(0b10100000));
534     ///
535     /// let mut bv = Bitv::with_capacity(9, false);
536     /// bv.set(2, true);
537     /// bv.set(8, true);
538     ///
539     /// assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000));
540     /// ```
541     pub fn to_bytes(&self) -> Vec<u8> {
542         fn bit (bitv: &Bitv, byte: uint, bit: uint) -> u8 {
543             let offset = byte * 8 + bit;
544             if offset >= bitv.nbits {
545                 0
546             } else {
547                 bitv.get(offset) as u8 << (7 - bit)
548             }
549         }
550
551         let len = self.nbits/8 +
552                   if self.nbits % 8 == 0 { 0 } else { 1 };
553         Vec::from_fn(len, |i|
554             bit(self, i, 0) |
555             bit(self, i, 1) |
556             bit(self, i, 2) |
557             bit(self, i, 3) |
558             bit(self, i, 4) |
559             bit(self, i, 5) |
560             bit(self, i, 6) |
561             bit(self, i, 7)
562         )
563     }
564
565     /// Transforms `self` into a `Vec<bool>` by turning each bit into a `bool`.
566     ///
567     /// # Example
568     ///
569     /// ```
570     /// use std::collections::bitv;
571     ///
572     /// let bv = bitv::from_bytes(&[0b10100000]);
573     /// assert_eq!(bv.to_bools(), vec!(true, false, true, false,
574     ///                                false, false, false, false));
575     /// ```
576     pub fn to_bools(&self) -> Vec<bool> {
577         Vec::from_fn(self.nbits, |i| self.get(i))
578     }
579
580     /// Compares a `Bitv` to a slice of `bool`s.
581     /// Both the `Bitv` and slice must have the same length.
582     ///
583     /// # Panics
584     ///
585     /// Panics if the `Bitv` and slice are of different length.
586     ///
587     /// # Example
588     ///
589     /// ```
590     /// use std::collections::bitv;
591     ///
592     /// let bv = bitv::from_bytes(&[0b10100000]);
593     ///
594     /// assert!(bv.eq_vec(&[true, false, true, false,
595     ///                     false, false, false, false]));
596     /// ```
597     pub fn eq_vec(&self, v: &[bool]) -> bool {
598         assert_eq!(self.nbits, v.len());
599         let mut i = 0;
600         while i < self.nbits {
601             if self.get(i) != v[i] { return false; }
602             i = i + 1;
603         }
604         true
605     }
606
607     /// Shortens a `Bitv`, dropping excess elements.
608     ///
609     /// If `len` is greater than the vector's current length, this has no
610     /// effect.
611     ///
612     /// # Example
613     ///
614     /// ```
615     /// use std::collections::bitv;
616     ///
617     /// let mut bv = bitv::from_bytes(&[0b01001011]);
618     /// bv.truncate(2);
619     /// assert!(bv.eq_vec(&[false, true]));
620     /// ```
621     #[unstable = "matches collection reform specification, waiting for dust to settle"]
622     pub fn truncate(&mut self, len: uint) {
623         if len < self.len() {
624             self.nbits = len;
625             let word_len = (len + u32::BITS - 1) / u32::BITS;
626             self.storage.truncate(word_len);
627             if len % u32::BITS > 0 {
628                 let mask = (1 << len % u32::BITS) - 1;
629                 self.storage[word_len - 1] &= mask;
630             }
631         }
632     }
633
634     /// Grows the vector to be able to store `size` bits without resizing.
635     ///
636     /// # Example
637     ///
638     /// ```
639     /// use std::collections::Bitv;
640     ///
641     /// let mut bv = Bitv::with_capacity(3, false);
642     /// bv.reserve(10);
643     /// assert_eq!(bv.len(), 3);
644     /// assert!(bv.capacity() >= 10);
645     /// ```
646     pub fn reserve(&mut self, size: uint) {
647         let old_size = self.storage.len();
648         let new_size = (size + u32::BITS - 1) / u32::BITS;
649         if old_size < new_size {
650             self.storage.grow(new_size - old_size, 0);
651         }
652     }
653
654     /// Returns the capacity in bits for this bit vector. Inserting any
655     /// element less than this amount will not trigger a resizing.
656     ///
657     /// # Example
658     ///
659     /// ```
660     /// use std::collections::Bitv;
661     ///
662     /// let mut bv = Bitv::new();
663     /// bv.reserve(10);
664     /// assert!(bv.capacity() >= 10);
665     /// ```
666     #[inline]
667     pub fn capacity(&self) -> uint {
668         self.storage.len() * u32::BITS
669     }
670
671     /// Grows the `Bitv` in-place, adding `n` copies of `value` to the `Bitv`.
672     ///
673     /// # Example
674     ///
675     /// ```
676     /// use std::collections::bitv;
677     ///
678     /// let mut bv = bitv::from_bytes(&[0b01001011]);
679     /// bv.grow(2, true);
680     /// assert_eq!(bv.len(), 10);
681     /// assert_eq!(bv.to_bytes(), vec!(0b01001011, 0b11000000));
682     /// ```
683     pub fn grow(&mut self, n: uint, value: bool) {
684         let new_nbits = self.nbits + n;
685         let new_nwords = (new_nbits + u32::BITS - 1) / u32::BITS;
686         let full_value = if value { !0 } else { 0 };
687         // Correct the old tail word
688         let old_last_word = (self.nbits + u32::BITS - 1) / u32::BITS - 1;
689         if self.nbits % u32::BITS > 0 {
690             let overhang = self.nbits % u32::BITS; // # of already-used bits
691             let mask = !((1 << overhang) - 1);  // e.g. 5 unused bits => 111110....0
692             if value {
693                 self.storage[old_last_word] |= mask;
694             } else {
695                 self.storage[old_last_word] &= !mask;
696             }
697         }
698         // Fill in words after the old tail word
699         let stop_idx = cmp::min(self.storage.len(), new_nwords);
700         for idx in range(old_last_word + 1, stop_idx) {
701             self.storage[idx] = full_value;
702         }
703         // Allocate new words, if needed
704         if new_nwords > self.storage.len() {
705             let to_add = new_nwords - self.storage.len();
706             self.storage.grow(to_add, full_value);
707
708             // Zero out and unused bits in the new tail word
709             if value {
710                 let tail_word = new_nwords - 1;
711                 let used_bits = new_nbits % u32::BITS;
712                 self.storage[tail_word] &= (1 << used_bits) - 1;
713             }
714         }
715         // Adjust internal bit count
716         self.nbits = new_nbits;
717     }
718
719     /// Shortens by one element and returns the removed element.
720     ///
721     /// # Panics
722     ///
723     /// Assert if empty.
724     ///
725     /// # Example
726     ///
727     /// ```
728     /// use std::collections::bitv;
729     ///
730     /// let mut bv = bitv::from_bytes(&[0b01001001]);
731     /// assert_eq!(bv.pop(), true);
732     /// assert_eq!(bv.pop(), false);
733     /// assert_eq!(bv.len(), 6);
734     /// assert_eq!(bv.to_bytes(), vec!(0b01001000));
735     /// ```
736     pub fn pop(&mut self) -> bool {
737         let ret = self.get(self.nbits - 1);
738         // If we are unusing a whole word, make sure it is zeroed out
739         if self.nbits % u32::BITS == 1 {
740             self.storage[self.nbits / u32::BITS] = 0;
741         }
742         self.nbits -= 1;
743         ret
744     }
745
746     /// Pushes a `bool` onto the end.
747     ///
748     /// # Example
749     ///
750     /// ```
751     /// use std::collections::Bitv;
752     ///
753     /// let mut bv = Bitv::new();
754     /// bv.push(true);
755     /// bv.push(false);
756     /// assert!(bv.eq_vec(&[true, false]));
757     /// ```
758     pub fn push(&mut self, elem: bool) {
759         let insert_pos = self.nbits;
760         self.nbits += 1;
761         if self.storage.len() * u32::BITS < self.nbits {
762             self.storage.push(0);
763         }
764         self.set(insert_pos, elem);
765     }
766
767     /// Return the total number of bits in this vector
768     #[inline]
769     #[unstable = "matches collection reform specification, waiting for dust to settle"]
770     pub fn len(&self) -> uint { self.nbits }
771
772     /// Returns true if there are no bits in this vector
773     #[inline]
774     #[unstable = "matches collection reform specification, waiting for dust to settle"]
775     pub fn is_empty(&self) -> bool { self.len() == 0 }
776
777     /// Clears all bits in this vector.
778     #[inline]
779     #[unstable = "matches collection reform specification, waiting for dust to settle"]
780     pub fn clear(&mut self) {
781         for w in self.storage.iter_mut() { *w = 0u32; }
782     }
783 }
784
785 /// Transforms a byte-vector into a `Bitv`. Each byte becomes eight bits,
786 /// with the most significant bits of each byte coming first. Each
787 /// bit becomes `true` if equal to 1 or `false` if equal to 0.
788 ///
789 /// # Example
790 ///
791 /// ```
792 /// use std::collections::bitv;
793 ///
794 /// let bv = bitv::from_bytes(&[0b10100000, 0b00010010]);
795 /// assert!(bv.eq_vec(&[true, false, true, false,
796 ///                     false, false, false, false,
797 ///                     false, false, false, true,
798 ///                     false, false, true, false]));
799 /// ```
800 pub fn from_bytes(bytes: &[u8]) -> Bitv {
801     from_fn(bytes.len() * 8, |i| {
802         let b = bytes[i / 8] as u32;
803         let offset = i % 8;
804         b >> (7 - offset) & 1 == 1
805     })
806 }
807
808 /// Creates a `Bitv` of the specified length where the value at each
809 /// index is `f(index)`.
810 ///
811 /// # Example
812 ///
813 /// ```
814 /// use std::collections::bitv::from_fn;
815 ///
816 /// let bv = from_fn(5, |i| { i % 2 == 0 });
817 /// assert!(bv.eq_vec(&[true, false, true, false, true]));
818 /// ```
819 pub fn from_fn(len: uint, f: |index: uint| -> bool) -> Bitv {
820     let mut bitv = Bitv::with_capacity(len, false);
821     for i in range(0u, len) {
822         bitv.set(i, f(i));
823     }
824     bitv
825 }
826
827 impl Default for Bitv {
828     #[inline]
829     fn default() -> Bitv { Bitv::new() }
830 }
831
832 impl FromIterator<bool> for Bitv {
833     fn from_iter<I:Iterator<bool>>(iterator: I) -> Bitv {
834         let mut ret = Bitv::new();
835         ret.extend(iterator);
836         ret
837     }
838 }
839
840 impl Extend<bool> for Bitv {
841     #[inline]
842     fn extend<I: Iterator<bool>>(&mut self, mut iterator: I) {
843         let (min, _) = iterator.size_hint();
844         let nbits = self.nbits;
845         self.reserve(nbits + min);
846         for element in iterator {
847             self.push(element)
848         }
849     }
850 }
851
852 impl Clone for Bitv {
853     #[inline]
854     fn clone(&self) -> Bitv {
855         Bitv { storage: self.storage.clone(), nbits: self.nbits }
856     }
857
858     #[inline]
859     fn clone_from(&mut self, source: &Bitv) {
860         self.nbits = source.nbits;
861         self.storage.clone_from(&source.storage);
862     }
863 }
864
865 impl PartialOrd for Bitv {
866     #[inline]
867     fn partial_cmp(&self, other: &Bitv) -> Option<Ordering> {
868         iter::order::partial_cmp(self.iter(), other.iter())
869     }
870 }
871
872 impl Ord for Bitv {
873     #[inline]
874     fn cmp(&self, other: &Bitv) -> Ordering {
875         iter::order::cmp(self.iter(), other.iter())
876     }
877 }
878
879 impl fmt::Show for Bitv {
880     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
881         for bit in self.iter() {
882             try!(write!(fmt, "{}", if bit { 1u } else { 0u }));
883         }
884         Ok(())
885     }
886 }
887
888 impl<S: hash::Writer> hash::Hash<S> for Bitv {
889     fn hash(&self, state: &mut S) {
890         self.nbits.hash(state);
891         for (_, elem) in self.mask_words(0) {
892             elem.hash(state);
893         }
894     }
895 }
896
897 impl cmp::PartialEq for Bitv {
898     #[inline]
899     fn eq(&self, other: &Bitv) -> bool {
900         if self.nbits != other.nbits {
901             return false;
902         }
903         self.mask_words(0).zip(other.mask_words(0)).all(|((_, w1), (_, w2))| w1 == w2)
904     }
905 }
906
907 impl cmp::Eq for Bitv {}
908
909 /// An iterator for `Bitv`.
910 pub struct Bits<'a> {
911     bitv: &'a Bitv,
912     next_idx: uint,
913     end_idx: uint,
914 }
915
916 impl<'a> Iterator<bool> for Bits<'a> {
917     #[inline]
918     fn next(&mut self) -> Option<bool> {
919         if self.next_idx != self.end_idx {
920             let idx = self.next_idx;
921             self.next_idx += 1;
922             Some(self.bitv.get(idx))
923         } else {
924             None
925         }
926     }
927
928     fn size_hint(&self) -> (uint, Option<uint>) {
929         let rem = self.end_idx - self.next_idx;
930         (rem, Some(rem))
931     }
932 }
933
934 impl<'a> DoubleEndedIterator<bool> for Bits<'a> {
935     #[inline]
936     fn next_back(&mut self) -> Option<bool> {
937         if self.next_idx != self.end_idx {
938             self.end_idx -= 1;
939             Some(self.bitv.get(self.end_idx))
940         } else {
941             None
942         }
943     }
944 }
945
946 impl<'a> ExactSizeIterator<bool> for Bits<'a> {}
947
948 impl<'a> RandomAccessIterator<bool> for Bits<'a> {
949     #[inline]
950     fn indexable(&self) -> uint {
951         self.end_idx - self.next_idx
952     }
953
954     #[inline]
955     fn idx(&mut self, index: uint) -> Option<bool> {
956         if index >= self.indexable() {
957             None
958         } else {
959             Some(self.bitv.get(index))
960         }
961     }
962 }
963
964 /// An implementation of a set using a bit vector as an underlying
965 /// representation for holding unsigned numerical elements.
966 ///
967 /// It should also be noted that the amount of storage necessary for holding a
968 /// set of objects is proportional to the maximum of the objects when viewed
969 /// as a `uint`.
970 ///
971 /// # Example
972 ///
973 /// ```
974 /// use std::collections::{BitvSet, Bitv};
975 /// use std::collections::bitv;
976 ///
977 /// // It's a regular set
978 /// let mut s = BitvSet::new();
979 /// s.insert(0);
980 /// s.insert(3);
981 /// s.insert(7);
982 ///
983 /// s.remove(&7);
984 ///
985 /// if !s.contains(&7) {
986 ///     println!("There is no 7");
987 /// }
988 ///
989 /// // Can initialize from a `Bitv`
990 /// let other = BitvSet::from_bitv(bitv::from_bytes(&[0b11010000]));
991 ///
992 /// s.union_with(&other);
993 ///
994 /// // Print 0, 1, 3 in some order
995 /// for x in s.iter() {
996 ///     println!("{}", x);
997 /// }
998 ///
999 /// // Can convert back to a `Bitv`
1000 /// let bv: Bitv = s.into_bitv();
1001 /// assert!(bv.get(3));
1002 /// ```
1003 #[deriving(Clone)]
1004 pub struct BitvSet(Bitv);
1005
1006 impl Default for BitvSet {
1007     #[inline]
1008     fn default() -> BitvSet { BitvSet::new() }
1009 }
1010
1011 impl FromIterator<bool> for BitvSet {
1012     fn from_iter<I:Iterator<bool>>(iterator: I) -> BitvSet {
1013         let mut ret = BitvSet::new();
1014         ret.extend(iterator);
1015         ret
1016     }
1017 }
1018
1019 impl Extend<bool> for BitvSet {
1020     #[inline]
1021     fn extend<I: Iterator<bool>>(&mut self, iterator: I) {
1022         let &BitvSet(ref mut self_bitv) = self;
1023         self_bitv.extend(iterator);
1024     }
1025 }
1026
1027 impl PartialOrd for BitvSet {
1028     #[inline]
1029     fn partial_cmp(&self, other: &BitvSet) -> Option<Ordering> {
1030         let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1031         iter::order::partial_cmp(a_iter, b_iter)
1032     }
1033 }
1034
1035 impl Ord for BitvSet {
1036     #[inline]
1037     fn cmp(&self, other: &BitvSet) -> Ordering {
1038         let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1039         iter::order::cmp(a_iter, b_iter)
1040     }
1041 }
1042
1043 impl cmp::PartialEq for BitvSet {
1044     #[inline]
1045     fn eq(&self, other: &BitvSet) -> bool {
1046         let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1047         iter::order::eq(a_iter, b_iter)
1048     }
1049 }
1050
1051 impl cmp::Eq for BitvSet {}
1052
1053 impl BitvSet {
1054     /// Creates a new bit vector set with initially no contents.
1055     ///
1056     /// # Example
1057     ///
1058     /// ```
1059     /// use std::collections::BitvSet;
1060     /// let mut s = BitvSet::new();
1061     /// ```
1062     #[inline]
1063     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1064     pub fn new() -> BitvSet {
1065         BitvSet(Bitv::new())
1066     }
1067
1068     /// Creates a new bit vector set with initially no contents, able to
1069     /// hold `nbits` elements without resizing.
1070     ///
1071     /// # Example
1072     ///
1073     /// ```
1074     /// use std::collections::BitvSet;
1075     /// let mut s = BitvSet::with_capacity(100);
1076     /// assert!(s.capacity() >= 100);
1077     /// ```
1078     #[inline]
1079     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1080     pub fn with_capacity(nbits: uint) -> BitvSet {
1081         let bitv = Bitv::with_capacity(nbits, false);
1082         BitvSet::from_bitv(bitv)
1083     }
1084
1085     /// Creates a new bit vector set from the given bit vector.
1086     ///
1087     /// # Example
1088     ///
1089     /// ```
1090     /// use std::collections::{bitv, BitvSet};
1091     ///
1092     /// let bv = bitv::from_bytes(&[0b01100000]);
1093     /// let s = BitvSet::from_bitv(bv);
1094     ///
1095     /// // Print 1, 2 in arbitrary order
1096     /// for x in s.iter() {
1097     ///     println!("{}", x);
1098     /// }
1099     /// ```
1100     #[inline]
1101     pub fn from_bitv(mut bitv: Bitv) -> BitvSet {
1102         // Mark every bit as valid
1103         bitv.nbits = bitv.capacity();
1104         BitvSet(bitv)
1105     }
1106
1107     /// Returns the capacity in bits for this bit vector. Inserting any
1108     /// element less than this amount will not trigger a resizing.
1109     ///
1110     /// # Example
1111     ///
1112     /// ```
1113     /// use std::collections::BitvSet;
1114     ///
1115     /// let mut s = BitvSet::with_capacity(100);
1116     /// assert!(s.capacity() >= 100);
1117     /// ```
1118     #[inline]
1119     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1120     pub fn capacity(&self) -> uint {
1121         let &BitvSet(ref bitv) = self;
1122         bitv.capacity()
1123     }
1124
1125     /// Grows the underlying vector to be able to store `size` bits.
1126     ///
1127     /// # Example
1128     ///
1129     /// ```
1130     /// use std::collections::BitvSet;
1131     ///
1132     /// let mut s = BitvSet::new();
1133     /// s.reserve(10);
1134     /// assert!(s.capacity() >= 10);
1135     /// ```
1136     pub fn reserve(&mut self, size: uint) {
1137         let &BitvSet(ref mut bitv) = self;
1138         bitv.reserve(size);
1139         if bitv.nbits < size {
1140             bitv.nbits = bitv.capacity();
1141         }
1142     }
1143
1144     /// Consumes this set to return the underlying bit vector.
1145     ///
1146     /// # Example
1147     ///
1148     /// ```
1149     /// use std::collections::BitvSet;
1150     ///
1151     /// let mut s = BitvSet::new();
1152     /// s.insert(0);
1153     /// s.insert(3);
1154     ///
1155     /// let bv = s.into_bitv();
1156     /// assert!(bv.get(0));
1157     /// assert!(bv.get(3));
1158     /// ```
1159     #[inline]
1160     pub fn into_bitv(self) -> Bitv {
1161         let BitvSet(bitv) = self;
1162         bitv
1163     }
1164
1165     /// Returns a reference to the underlying bit vector.
1166     ///
1167     /// # Example
1168     ///
1169     /// ```
1170     /// use std::collections::BitvSet;
1171     ///
1172     /// let mut s = BitvSet::new();
1173     /// s.insert(0);
1174     ///
1175     /// let bv = s.get_ref();
1176     /// assert_eq!(bv[0], true);
1177     /// ```
1178     #[inline]
1179     pub fn get_ref<'a>(&'a self) -> &'a Bitv {
1180         let &BitvSet(ref bitv) = self;
1181         bitv
1182     }
1183
1184     #[inline]
1185     fn other_op(&mut self, other: &BitvSet, f: |u32, u32| -> u32) {
1186         // Expand the vector if necessary
1187         self.reserve(other.capacity());
1188
1189         // Unwrap Bitvs
1190         let &BitvSet(ref mut self_bitv) = self;
1191         let &BitvSet(ref other_bitv) = other;
1192
1193         // virtually pad other with 0's for equal lengths
1194         let mut other_words = {
1195             let (_, result) = match_words(self_bitv, other_bitv);
1196             result
1197         };
1198
1199         // Apply values found in other
1200         for (i, w) in other_words {
1201             let old = self_bitv.storage[i];
1202             let new = f(old, w);
1203             self_bitv.storage[i] = new;
1204         }
1205     }
1206
1207     /// Truncates the underlying vector to the least length required.
1208     ///
1209     /// # Example
1210     ///
1211     /// ```
1212     /// use std::collections::BitvSet;
1213     ///
1214     /// let mut s = BitvSet::new();
1215     /// s.insert(32183231);
1216     /// s.remove(&32183231);
1217     ///
1218     /// // Internal storage will probably be bigger than necessary
1219     /// println!("old capacity: {}", s.capacity());
1220     ///
1221     /// // Now should be smaller
1222     /// s.shrink_to_fit();
1223     /// println!("new capacity: {}", s.capacity());
1224     /// ```
1225     #[inline]
1226     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1227     pub fn shrink_to_fit(&mut self) {
1228         let &BitvSet(ref mut bitv) = self;
1229         // Obtain original length
1230         let old_len = bitv.storage.len();
1231         // Obtain coarse trailing zero length
1232         let n = bitv.storage.iter().rev().take_while(|&&n| n == 0).count();
1233         // Truncate
1234         let trunc_len = cmp::max(old_len - n, 1);
1235         bitv.storage.truncate(trunc_len);
1236         bitv.nbits = trunc_len * u32::BITS;
1237     }
1238
1239     /// Iterator over each u32 stored in the `BitvSet`.
1240     ///
1241     /// # Example
1242     ///
1243     /// ```
1244     /// use std::collections::BitvSet;
1245     /// use std::collections::bitv;
1246     ///
1247     /// let s = BitvSet::from_bitv(bitv::from_bytes(&[0b01001010]));
1248     ///
1249     /// // Print 1, 4, 6 in arbitrary order
1250     /// for x in s.iter() {
1251     ///     println!("{}", x);
1252     /// }
1253     /// ```
1254     #[inline]
1255     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1256     pub fn iter<'a>(&'a self) -> BitPositions<'a> {
1257         BitPositions {set: self, next_idx: 0u}
1258     }
1259
1260     /// Iterator over each u32 stored in `self` union `other`.
1261     /// See [union_with](#method.union_with) for an efficient in-place version.
1262     ///
1263     /// # Example
1264     ///
1265     /// ```
1266     /// use std::collections::BitvSet;
1267     /// use std::collections::bitv;
1268     ///
1269     /// let a = BitvSet::from_bitv(bitv::from_bytes(&[0b01101000]));
1270     /// let b = BitvSet::from_bitv(bitv::from_bytes(&[0b10100000]));
1271     ///
1272     /// // Print 0, 1, 2, 4 in arbitrary order
1273     /// for x in a.union(&b) {
1274     ///     println!("{}", x);
1275     /// }
1276     /// ```
1277     #[inline]
1278     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1279     pub fn union<'a>(&'a self, other: &'a BitvSet) -> TwoBitPositions<'a> {
1280         TwoBitPositions {
1281             set: self,
1282             other: other,
1283             merge: |w1, w2| w1 | w2,
1284             current_word: 0u32,
1285             next_idx: 0u
1286         }
1287     }
1288
1289     /// Iterator over each uint stored in `self` intersect `other`.
1290     /// See [intersect_with](#method.intersect_with) for an efficient in-place version.
1291     ///
1292     /// # Example
1293     ///
1294     /// ```
1295     /// use std::collections::BitvSet;
1296     /// use std::collections::bitv;
1297     ///
1298     /// let a = BitvSet::from_bitv(bitv::from_bytes(&[0b01101000]));
1299     /// let b = BitvSet::from_bitv(bitv::from_bytes(&[0b10100000]));
1300     ///
1301     /// // Print 2
1302     /// for x in a.intersection(&b) {
1303     ///     println!("{}", x);
1304     /// }
1305     /// ```
1306     #[inline]
1307     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1308     pub fn intersection<'a>(&'a self, other: &'a BitvSet) -> Take<TwoBitPositions<'a>> {
1309         let min = cmp::min(self.capacity(), other.capacity());
1310         TwoBitPositions {
1311             set: self,
1312             other: other,
1313             merge: |w1, w2| w1 & w2,
1314             current_word: 0u32,
1315             next_idx: 0
1316         }.take(min)
1317     }
1318
1319     /// Iterator over each uint stored in the `self` setminus `other`.
1320     /// See [difference_with](#method.difference_with) for an efficient in-place version.
1321     ///
1322     /// # Example
1323     ///
1324     /// ```
1325     /// use std::collections::BitvSet;
1326     /// use std::collections::bitv;
1327     ///
1328     /// let a = BitvSet::from_bitv(bitv::from_bytes(&[0b01101000]));
1329     /// let b = BitvSet::from_bitv(bitv::from_bytes(&[0b10100000]));
1330     ///
1331     /// // Print 1, 4 in arbitrary order
1332     /// for x in a.difference(&b) {
1333     ///     println!("{}", x);
1334     /// }
1335     ///
1336     /// // Note that difference is not symmetric,
1337     /// // and `b - a` means something else.
1338     /// // This prints 0
1339     /// for x in b.difference(&a) {
1340     ///     println!("{}", x);
1341     /// }
1342     /// ```
1343     #[inline]
1344     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1345     pub fn difference<'a>(&'a self, other: &'a BitvSet) -> TwoBitPositions<'a> {
1346         TwoBitPositions {
1347             set: self,
1348             other: other,
1349             merge: |w1, w2| w1 & !w2,
1350             current_word: 0u32,
1351             next_idx: 0
1352         }
1353     }
1354
1355     /// Iterator over each u32 stored in the symmetric difference of `self` and `other`.
1356     /// See [symmetric_difference_with](#method.symmetric_difference_with) for
1357     /// an efficient in-place version.
1358     ///
1359     /// # Example
1360     ///
1361     /// ```
1362     /// use std::collections::BitvSet;
1363     /// use std::collections::bitv;
1364     ///
1365     /// let a = BitvSet::from_bitv(bitv::from_bytes(&[0b01101000]));
1366     /// let b = BitvSet::from_bitv(bitv::from_bytes(&[0b10100000]));
1367     ///
1368     /// // Print 0, 1, 4 in arbitrary order
1369     /// for x in a.symmetric_difference(&b) {
1370     ///     println!("{}", x);
1371     /// }
1372     /// ```
1373     #[inline]
1374     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1375     pub fn symmetric_difference<'a>(&'a self, other: &'a BitvSet) -> TwoBitPositions<'a> {
1376         TwoBitPositions {
1377             set: self,
1378             other: other,
1379             merge: |w1, w2| w1 ^ w2,
1380             current_word: 0u32,
1381             next_idx: 0
1382         }
1383     }
1384
1385     /// Unions in-place with the specified other bit vector.
1386     ///
1387     /// # Example
1388     ///
1389     /// ```
1390     /// use std::collections::BitvSet;
1391     /// use std::collections::bitv;
1392     ///
1393     /// let a   = 0b01101000;
1394     /// let b   = 0b10100000;
1395     /// let res = 0b11101000;
1396     ///
1397     /// let mut a = BitvSet::from_bitv(bitv::from_bytes(&[a]));
1398     /// let b = BitvSet::from_bitv(bitv::from_bytes(&[b]));
1399     /// let res = BitvSet::from_bitv(bitv::from_bytes(&[res]));
1400     ///
1401     /// a.union_with(&b);
1402     /// assert_eq!(a, res);
1403     /// ```
1404     #[inline]
1405     pub fn union_with(&mut self, other: &BitvSet) {
1406         self.other_op(other, |w1, w2| w1 | w2);
1407     }
1408
1409     /// Intersects in-place with the specified other bit vector.
1410     ///
1411     /// # Example
1412     ///
1413     /// ```
1414     /// use std::collections::BitvSet;
1415     /// use std::collections::bitv;
1416     ///
1417     /// let a   = 0b01101000;
1418     /// let b   = 0b10100000;
1419     /// let res = 0b00100000;
1420     ///
1421     /// let mut a = BitvSet::from_bitv(bitv::from_bytes(&[a]));
1422     /// let b = BitvSet::from_bitv(bitv::from_bytes(&[b]));
1423     /// let res = BitvSet::from_bitv(bitv::from_bytes(&[res]));
1424     ///
1425     /// a.intersect_with(&b);
1426     /// assert_eq!(a, res);
1427     /// ```
1428     #[inline]
1429     pub fn intersect_with(&mut self, other: &BitvSet) {
1430         self.other_op(other, |w1, w2| w1 & w2);
1431     }
1432
1433     /// Makes this bit vector the difference with the specified other bit vector
1434     /// in-place.
1435     ///
1436     /// # Example
1437     ///
1438     /// ```
1439     /// use std::collections::BitvSet;
1440     /// use std::collections::bitv;
1441     ///
1442     /// let a   = 0b01101000;
1443     /// let b   = 0b10100000;
1444     /// let a_b = 0b01001000; // a - b
1445     /// let b_a = 0b10000000; // b - a
1446     ///
1447     /// let mut bva = BitvSet::from_bitv(bitv::from_bytes(&[a]));
1448     /// let bvb = BitvSet::from_bitv(bitv::from_bytes(&[b]));
1449     /// let bva_b = BitvSet::from_bitv(bitv::from_bytes(&[a_b]));
1450     /// let bvb_a = BitvSet::from_bitv(bitv::from_bytes(&[b_a]));
1451     ///
1452     /// bva.difference_with(&bvb);
1453     /// assert_eq!(bva, bva_b);
1454     ///
1455     /// let bva = BitvSet::from_bitv(bitv::from_bytes(&[a]));
1456     /// let mut bvb = BitvSet::from_bitv(bitv::from_bytes(&[b]));
1457     ///
1458     /// bvb.difference_with(&bva);
1459     /// assert_eq!(bvb, bvb_a);
1460     /// ```
1461     #[inline]
1462     pub fn difference_with(&mut self, other: &BitvSet) {
1463         self.other_op(other, |w1, w2| w1 & !w2);
1464     }
1465
1466     /// Makes this bit vector the symmetric difference with the specified other
1467     /// bit vector in-place.
1468     ///
1469     /// # Example
1470     ///
1471     /// ```
1472     /// use std::collections::BitvSet;
1473     /// use std::collections::bitv;
1474     ///
1475     /// let a   = 0b01101000;
1476     /// let b   = 0b10100000;
1477     /// let res = 0b11001000;
1478     ///
1479     /// let mut a = BitvSet::from_bitv(bitv::from_bytes(&[a]));
1480     /// let b = BitvSet::from_bitv(bitv::from_bytes(&[b]));
1481     /// let res = BitvSet::from_bitv(bitv::from_bytes(&[res]));
1482     ///
1483     /// a.symmetric_difference_with(&b);
1484     /// assert_eq!(a, res);
1485     /// ```
1486     #[inline]
1487     pub fn symmetric_difference_with(&mut self, other: &BitvSet) {
1488         self.other_op(other, |w1, w2| w1 ^ w2);
1489     }
1490
1491     /// Return the number of set bits in this set.
1492     #[inline]
1493     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1494     pub fn len(&self) -> uint  {
1495         let &BitvSet(ref bitv) = self;
1496         bitv.storage.iter().fold(0, |acc, &n| acc + n.count_ones())
1497     }
1498
1499     /// Returns whether there are no bits set in this set
1500     #[inline]
1501     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1502     pub fn is_empty(&self) -> bool {
1503         let &BitvSet(ref bitv) = self;
1504         bitv.storage.iter().all(|&n| n == 0)
1505     }
1506
1507     /// Clears all bits in this set
1508     #[inline]
1509     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1510     pub fn clear(&mut self) {
1511         let &BitvSet(ref mut bitv) = self;
1512         bitv.clear();
1513     }
1514
1515     /// Returns `true` if this set contains the specified integer.
1516     #[inline]
1517     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1518     pub fn contains(&self, value: &uint) -> bool {
1519         let &BitvSet(ref bitv) = self;
1520         *value < bitv.nbits && bitv.get(*value)
1521     }
1522
1523     /// Returns `true` if the set has no elements in common with `other`.
1524     /// This is equivalent to checking for an empty intersection.
1525     #[inline]
1526     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1527     pub fn is_disjoint(&self, other: &BitvSet) -> bool {
1528         self.intersection(other).next().is_none()
1529     }
1530
1531     /// Returns `true` if the set is a subset of another.
1532     #[inline]
1533     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1534     pub fn is_subset(&self, other: &BitvSet) -> bool {
1535         let &BitvSet(ref self_bitv) = self;
1536         let &BitvSet(ref other_bitv) = other;
1537
1538         // Check that `self` intersect `other` is self
1539         self_bitv.mask_words(0).zip(other_bitv.mask_words(0))
1540                                .all(|((_, w1), (_, w2))| w1 & w2 == w1) &&
1541         // Check that `self` setminus `other` is empty
1542         self_bitv.mask_words(other_bitv.storage.len()).all(|(_, w)| w == 0)
1543     }
1544
1545     /// Returns `true` if the set is a superset of another.
1546     #[inline]
1547     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1548     pub fn is_superset(&self, other: &BitvSet) -> bool {
1549         other.is_subset(self)
1550     }
1551
1552     /// Adds a value to the set. Returns `true` if the value was not already
1553     /// present in the set.
1554     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1555     pub fn insert(&mut self, value: uint) -> bool {
1556         if self.contains(&value) {
1557             return false;
1558         }
1559
1560         // Ensure we have enough space to hold the new element
1561         if value >= self.capacity() {
1562             let new_cap = cmp::max(value + 1, self.capacity() * 2);
1563             self.reserve(new_cap);
1564         }
1565
1566         let &BitvSet(ref mut bitv) = self;
1567         bitv.set(value, true);
1568         return true;
1569     }
1570
1571     /// Removes a value from the set. Returns `true` if the value was
1572     /// present in the set.
1573     #[unstable = "matches collection reform specification, waiting for dust to settle"]
1574     pub fn remove(&mut self, value: &uint) -> bool {
1575         if !self.contains(value) {
1576             return false;
1577         }
1578         let &BitvSet(ref mut bitv) = self;
1579         bitv.set(*value, false);
1580         return true;
1581     }
1582 }
1583
1584 impl fmt::Show for BitvSet {
1585     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1586         try!(write!(fmt, "{{"));
1587         let mut first = true;
1588         for n in self.iter() {
1589             if !first {
1590                 try!(write!(fmt, ", "));
1591             }
1592             try!(write!(fmt, "{}", n));
1593             first = false;
1594         }
1595         write!(fmt, "}}")
1596     }
1597 }
1598
1599 impl<S: hash::Writer> hash::Hash<S> for BitvSet {
1600     fn hash(&self, state: &mut S) {
1601         for pos in self.iter() {
1602             pos.hash(state);
1603         }
1604     }
1605 }
1606
1607 /// An iterator for `BitvSet`.
1608 pub struct BitPositions<'a> {
1609     set: &'a BitvSet,
1610     next_idx: uint
1611 }
1612
1613 /// An iterator combining two `BitvSet` iterators.
1614 pub struct TwoBitPositions<'a> {
1615     set: &'a BitvSet,
1616     other: &'a BitvSet,
1617     merge: |u32, u32|: 'a -> u32,
1618     current_word: u32,
1619     next_idx: uint
1620 }
1621
1622 impl<'a> Iterator<uint> for BitPositions<'a> {
1623     fn next(&mut self) -> Option<uint> {
1624         while self.next_idx < self.set.capacity() {
1625             let idx = self.next_idx;
1626             self.next_idx += 1;
1627
1628             if self.set.contains(&idx) {
1629                 return Some(idx);
1630             }
1631         }
1632
1633         return None;
1634     }
1635
1636     #[inline]
1637     fn size_hint(&self) -> (uint, Option<uint>) {
1638         (0, Some(self.set.capacity() - self.next_idx))
1639     }
1640 }
1641
1642 impl<'a> Iterator<uint> for TwoBitPositions<'a> {
1643     fn next(&mut self) -> Option<uint> {
1644         while self.next_idx < self.set.capacity() ||
1645               self.next_idx < self.other.capacity() {
1646             let bit_idx = self.next_idx % u32::BITS;
1647             if bit_idx == 0 {
1648                 let &BitvSet(ref s_bitv) = self.set;
1649                 let &BitvSet(ref o_bitv) = self.other;
1650                 // Merging the two words is a bit of an awkward dance since
1651                 // one Bitv might be longer than the other
1652                 let word_idx = self.next_idx / u32::BITS;
1653                 let w1 = if word_idx < s_bitv.storage.len() {
1654                              s_bitv.storage[word_idx]
1655                          } else { 0 };
1656                 let w2 = if word_idx < o_bitv.storage.len() {
1657                              o_bitv.storage[word_idx]
1658                          } else { 0 };
1659                 self.current_word = (self.merge)(w1, w2);
1660             }
1661
1662             self.next_idx += 1;
1663             if self.current_word & (1 << bit_idx) != 0 {
1664                 return Some(self.next_idx - 1);
1665             }
1666         }
1667         return None;
1668     }
1669
1670     #[inline]
1671     fn size_hint(&self) -> (uint, Option<uint>) {
1672         let cap = cmp::max(self.set.capacity(), self.other.capacity());
1673         (0, Some(cap - self.next_idx))
1674     }
1675 }
1676
1677 #[cfg(test)]
1678 mod tests {
1679     use std::prelude::*;
1680     use std::iter::range_step;
1681     use std::rand;
1682     use std::rand::Rng;
1683     use std::u32;
1684     use test::{Bencher, black_box};
1685
1686     use super::{Bitv, BitvSet, from_fn, from_bytes};
1687     use bitv;
1688     use vec::Vec;
1689
1690     static BENCH_BITS : uint = 1 << 14;
1691
1692     #[test]
1693     fn test_to_str() {
1694         let zerolen = Bitv::new();
1695         assert_eq!(zerolen.to_string().as_slice(), "");
1696
1697         let eightbits = Bitv::with_capacity(8u, false);
1698         assert_eq!(eightbits.to_string().as_slice(), "00000000")
1699     }
1700
1701     #[test]
1702     fn test_0_elements() {
1703         let act = Bitv::new();
1704         let exp = Vec::from_elem(0u, false);
1705         assert!(act.eq_vec(exp.as_slice()));
1706     }
1707
1708     #[test]
1709     fn test_1_element() {
1710         let mut act = Bitv::with_capacity(1u, false);
1711         assert!(act.eq_vec(&[false]));
1712         act = Bitv::with_capacity(1u, true);
1713         assert!(act.eq_vec(&[true]));
1714     }
1715
1716     #[test]
1717     fn test_2_elements() {
1718         let mut b = bitv::Bitv::with_capacity(2, false);
1719         b.set(0, true);
1720         b.set(1, false);
1721         assert_eq!(b.to_string().as_slice(), "10");
1722     }
1723
1724     #[test]
1725     fn test_10_elements() {
1726         let mut act;
1727         // all 0
1728
1729         act = Bitv::with_capacity(10u, false);
1730         assert!((act.eq_vec(
1731                     &[false, false, false, false, false, false, false, false, false, false])));
1732         // all 1
1733
1734         act = Bitv::with_capacity(10u, true);
1735         assert!((act.eq_vec(&[true, true, true, true, true, true, true, true, true, true])));
1736         // mixed
1737
1738         act = Bitv::with_capacity(10u, false);
1739         act.set(0u, true);
1740         act.set(1u, true);
1741         act.set(2u, true);
1742         act.set(3u, true);
1743         act.set(4u, true);
1744         assert!((act.eq_vec(&[true, true, true, true, true, false, false, false, false, false])));
1745         // mixed
1746
1747         act = Bitv::with_capacity(10u, false);
1748         act.set(5u, true);
1749         act.set(6u, true);
1750         act.set(7u, true);
1751         act.set(8u, true);
1752         act.set(9u, true);
1753         assert!((act.eq_vec(&[false, false, false, false, false, true, true, true, true, true])));
1754         // mixed
1755
1756         act = Bitv::with_capacity(10u, false);
1757         act.set(0u, true);
1758         act.set(3u, true);
1759         act.set(6u, true);
1760         act.set(9u, true);
1761         assert!((act.eq_vec(&[true, false, false, true, false, false, true, false, false, true])));
1762     }
1763
1764     #[test]
1765     fn test_31_elements() {
1766         let mut act;
1767         // all 0
1768
1769         act = Bitv::with_capacity(31u, false);
1770         assert!(act.eq_vec(
1771                 &[false, false, false, false, false, false, false, false, false, false, false,
1772                   false, false, false, false, false, false, false, false, false, false, false,
1773                   false, false, false, false, false, false, false, false, false]));
1774         // all 1
1775
1776         act = Bitv::with_capacity(31u, true);
1777         assert!(act.eq_vec(
1778                 &[true, true, true, true, true, true, true, true, true, true, true, true, true,
1779                   true, true, true, true, true, true, true, true, true, true, true, true, true,
1780                   true, true, true, true, true]));
1781         // mixed
1782
1783         act = Bitv::with_capacity(31u, false);
1784         act.set(0u, true);
1785         act.set(1u, true);
1786         act.set(2u, true);
1787         act.set(3u, true);
1788         act.set(4u, true);
1789         act.set(5u, true);
1790         act.set(6u, true);
1791         act.set(7u, true);
1792         assert!(act.eq_vec(
1793                 &[true, true, true, true, true, true, true, true, false, false, false, false, false,
1794                   false, false, false, false, false, false, false, false, false, false, false,
1795                   false, false, false, false, false, false, false]));
1796         // mixed
1797
1798         act = Bitv::with_capacity(31u, false);
1799         act.set(16u, true);
1800         act.set(17u, true);
1801         act.set(18u, true);
1802         act.set(19u, true);
1803         act.set(20u, true);
1804         act.set(21u, true);
1805         act.set(22u, true);
1806         act.set(23u, true);
1807         assert!(act.eq_vec(
1808                 &[false, false, false, false, false, false, false, false, false, false, false,
1809                   false, false, false, false, false, true, true, true, true, true, true, true, true,
1810                   false, false, false, false, false, false, false]));
1811         // mixed
1812
1813         act = Bitv::with_capacity(31u, false);
1814         act.set(24u, true);
1815         act.set(25u, true);
1816         act.set(26u, true);
1817         act.set(27u, true);
1818         act.set(28u, true);
1819         act.set(29u, true);
1820         act.set(30u, true);
1821         assert!(act.eq_vec(
1822                 &[false, false, false, false, false, false, false, false, false, false, false,
1823                   false, false, false, false, false, false, false, false, false, false, false,
1824                   false, false, true, true, true, true, true, true, true]));
1825         // mixed
1826
1827         act = Bitv::with_capacity(31u, false);
1828         act.set(3u, true);
1829         act.set(17u, true);
1830         act.set(30u, true);
1831         assert!(act.eq_vec(
1832                 &[false, false, false, true, false, false, false, false, false, false, false, false,
1833                   false, false, false, false, false, true, false, false, false, false, false, false,
1834                   false, false, false, false, false, false, true]));
1835     }
1836
1837     #[test]
1838     fn test_32_elements() {
1839         let mut act;
1840         // all 0
1841
1842         act = Bitv::with_capacity(32u, false);
1843         assert!(act.eq_vec(
1844                 &[false, false, false, false, false, false, false, false, false, false, false,
1845                   false, false, false, false, false, false, false, false, false, false, false,
1846                   false, false, false, false, false, false, false, false, false, false]));
1847         // all 1
1848
1849         act = Bitv::with_capacity(32u, true);
1850         assert!(act.eq_vec(
1851                 &[true, true, true, true, true, true, true, true, true, true, true, true, true,
1852                   true, true, true, true, true, true, true, true, true, true, true, true, true,
1853                   true, true, true, true, true, true]));
1854         // mixed
1855
1856         act = Bitv::with_capacity(32u, false);
1857         act.set(0u, true);
1858         act.set(1u, true);
1859         act.set(2u, true);
1860         act.set(3u, true);
1861         act.set(4u, true);
1862         act.set(5u, true);
1863         act.set(6u, true);
1864         act.set(7u, true);
1865         assert!(act.eq_vec(
1866                 &[true, true, true, true, true, true, true, true, false, false, false, false, false,
1867                   false, false, false, false, false, false, false, false, false, false, false,
1868                   false, false, false, false, false, false, false, false]));
1869         // mixed
1870
1871         act = Bitv::with_capacity(32u, false);
1872         act.set(16u, true);
1873         act.set(17u, true);
1874         act.set(18u, true);
1875         act.set(19u, true);
1876         act.set(20u, true);
1877         act.set(21u, true);
1878         act.set(22u, true);
1879         act.set(23u, true);
1880         assert!(act.eq_vec(
1881                 &[false, false, false, false, false, false, false, false, false, false, false,
1882                   false, false, false, false, false, true, true, true, true, true, true, true, true,
1883                   false, false, false, false, false, false, false, false]));
1884         // mixed
1885
1886         act = Bitv::with_capacity(32u, false);
1887         act.set(24u, true);
1888         act.set(25u, true);
1889         act.set(26u, true);
1890         act.set(27u, true);
1891         act.set(28u, true);
1892         act.set(29u, true);
1893         act.set(30u, true);
1894         act.set(31u, true);
1895         assert!(act.eq_vec(
1896                 &[false, false, false, false, false, false, false, false, false, false, false,
1897                   false, false, false, false, false, false, false, false, false, false, false,
1898                   false, false, true, true, true, true, true, true, true, true]));
1899         // mixed
1900
1901         act = Bitv::with_capacity(32u, false);
1902         act.set(3u, true);
1903         act.set(17u, true);
1904         act.set(30u, true);
1905         act.set(31u, true);
1906         assert!(act.eq_vec(
1907                 &[false, false, false, true, false, false, false, false, false, false, false, false,
1908                   false, false, false, false, false, true, false, false, false, false, false, false,
1909                   false, false, false, false, false, false, true, true]));
1910     }
1911
1912     #[test]
1913     fn test_33_elements() {
1914         let mut act;
1915         // all 0
1916
1917         act = Bitv::with_capacity(33u, false);
1918         assert!(act.eq_vec(
1919                 &[false, false, false, false, false, false, false, false, false, false, false,
1920                   false, false, false, false, false, false, false, false, false, false, false,
1921                   false, false, false, false, false, false, false, false, false, false, false]));
1922         // all 1
1923
1924         act = Bitv::with_capacity(33u, true);
1925         assert!(act.eq_vec(
1926                 &[true, true, true, true, true, true, true, true, true, true, true, true, true,
1927                   true, true, true, true, true, true, true, true, true, true, true, true, true,
1928                   true, true, true, true, true, true, true]));
1929         // mixed
1930
1931         act = Bitv::with_capacity(33u, false);
1932         act.set(0u, true);
1933         act.set(1u, true);
1934         act.set(2u, true);
1935         act.set(3u, true);
1936         act.set(4u, true);
1937         act.set(5u, true);
1938         act.set(6u, true);
1939         act.set(7u, true);
1940         assert!(act.eq_vec(
1941                 &[true, true, true, true, true, true, true, true, false, false, false, false, false,
1942                   false, false, false, false, false, false, false, false, false, false, false,
1943                   false, false, false, false, false, false, false, false, false]));
1944         // mixed
1945
1946         act = Bitv::with_capacity(33u, false);
1947         act.set(16u, true);
1948         act.set(17u, true);
1949         act.set(18u, true);
1950         act.set(19u, true);
1951         act.set(20u, true);
1952         act.set(21u, true);
1953         act.set(22u, true);
1954         act.set(23u, true);
1955         assert!(act.eq_vec(
1956                 &[false, false, false, false, false, false, false, false, false, false, false,
1957                   false, false, false, false, false, true, true, true, true, true, true, true, true,
1958                   false, false, false, false, false, false, false, false, false]));
1959         // mixed
1960
1961         act = Bitv::with_capacity(33u, false);
1962         act.set(24u, true);
1963         act.set(25u, true);
1964         act.set(26u, true);
1965         act.set(27u, true);
1966         act.set(28u, true);
1967         act.set(29u, true);
1968         act.set(30u, true);
1969         act.set(31u, true);
1970         assert!(act.eq_vec(
1971                 &[false, false, false, false, false, false, false, false, false, false, false,
1972                   false, false, false, false, false, false, false, false, false, false, false,
1973                   false, false, true, true, true, true, true, true, true, true, false]));
1974         // mixed
1975
1976         act = Bitv::with_capacity(33u, false);
1977         act.set(3u, true);
1978         act.set(17u, true);
1979         act.set(30u, true);
1980         act.set(31u, true);
1981         act.set(32u, true);
1982         assert!(act.eq_vec(
1983                 &[false, false, false, true, false, false, false, false, false, false, false, false,
1984                   false, false, false, false, false, true, false, false, false, false, false, false,
1985                   false, false, false, false, false, false, true, true, true]));
1986     }
1987
1988     #[test]
1989     fn test_equal_differing_sizes() {
1990         let v0 = Bitv::with_capacity(10u, false);
1991         let v1 = Bitv::with_capacity(11u, false);
1992         assert!(v0 != v1);
1993     }
1994
1995     #[test]
1996     fn test_equal_greatly_differing_sizes() {
1997         let v0 = Bitv::with_capacity(10u, false);
1998         let v1 = Bitv::with_capacity(110u, false);
1999         assert!(v0 != v1);
2000     }
2001
2002     #[test]
2003     fn test_equal_sneaky_small() {
2004         let mut a = bitv::Bitv::with_capacity(1, false);
2005         a.set(0, true);
2006
2007         let mut b = bitv::Bitv::with_capacity(1, true);
2008         b.set(0, true);
2009
2010         assert_eq!(a, b);
2011     }
2012
2013     #[test]
2014     fn test_equal_sneaky_big() {
2015         let mut a = bitv::Bitv::with_capacity(100, false);
2016         for i in range(0u, 100) {
2017             a.set(i, true);
2018         }
2019
2020         let mut b = bitv::Bitv::with_capacity(100, true);
2021         for i in range(0u, 100) {
2022             b.set(i, true);
2023         }
2024
2025         assert_eq!(a, b);
2026     }
2027
2028     #[test]
2029     fn test_from_bytes() {
2030         let bitv = from_bytes(&[0b10110110, 0b00000000, 0b11111111]);
2031         let str = format!("{}{}{}", "10110110", "00000000", "11111111");
2032         assert_eq!(bitv.to_string().as_slice(), str.as_slice());
2033     }
2034
2035     #[test]
2036     fn test_to_bytes() {
2037         let mut bv = Bitv::with_capacity(3, true);
2038         bv.set(1, false);
2039         assert_eq!(bv.to_bytes(), vec!(0b10100000));
2040
2041         let mut bv = Bitv::with_capacity(9, false);
2042         bv.set(2, true);
2043         bv.set(8, true);
2044         assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000));
2045     }
2046
2047     #[test]
2048     fn test_from_bools() {
2049         let bools = vec![true, false, true, true];
2050         let bitv: Bitv = bools.iter().map(|n| *n).collect();
2051         assert_eq!(bitv.to_string().as_slice(), "1011");
2052     }
2053
2054     #[test]
2055     fn test_bitv_set_from_bools() {
2056         let bools = vec![true, false, true, true];
2057         let a: BitvSet = bools.iter().map(|n| *n).collect();
2058         let mut b = BitvSet::new();
2059         b.insert(0);
2060         b.insert(2);
2061         b.insert(3);
2062         assert_eq!(a, b);
2063     }
2064
2065     #[test]
2066     fn test_to_bools() {
2067         let bools = vec!(false, false, true, false, false, true, true, false);
2068         assert_eq!(from_bytes(&[0b00100110]).iter().collect::<Vec<bool>>(), bools);
2069     }
2070
2071     #[test]
2072     fn test_bitv_iterator() {
2073         let bools = vec![true, false, true, true];
2074         let bitv: Bitv = bools.iter().map(|n| *n).collect();
2075
2076         assert_eq!(bitv.iter().collect::<Vec<bool>>(), bools)
2077
2078         let long = Vec::from_fn(10000, |i| i % 2 == 0);
2079         let bitv: Bitv = long.iter().map(|n| *n).collect();
2080         assert_eq!(bitv.iter().collect::<Vec<bool>>(), long)
2081     }
2082
2083     #[test]
2084     fn test_bitv_set_iterator() {
2085         let bools = [true, false, true, true];
2086         let bitv: BitvSet = bools.iter().map(|n| *n).collect();
2087
2088         let idxs: Vec<uint> = bitv.iter().collect();
2089         assert_eq!(idxs, vec!(0, 2, 3));
2090
2091         let long: BitvSet = range(0u, 10000).map(|n| n % 2 == 0).collect();
2092         let real = range_step(0, 10000, 2).collect::<Vec<uint>>();
2093
2094         let idxs: Vec<uint> = long.iter().collect();
2095         assert_eq!(idxs, real);
2096     }
2097
2098     #[test]
2099     fn test_bitv_set_frombitv_init() {
2100         let bools = [true, false];
2101         let lengths = [10, 64, 100];
2102         for &b in bools.iter() {
2103             for &l in lengths.iter() {
2104                 let bitset = BitvSet::from_bitv(Bitv::with_capacity(l, b));
2105                 assert_eq!(bitset.contains(&1u), b)
2106                 assert_eq!(bitset.contains(&(l-1u)), b)
2107                 assert!(!bitset.contains(&l))
2108             }
2109         }
2110     }
2111
2112     #[test]
2113     fn test_small_difference() {
2114         let mut b1 = Bitv::with_capacity(3, false);
2115         let mut b2 = Bitv::with_capacity(3, false);
2116         b1.set(0, true);
2117         b1.set(1, true);
2118         b2.set(1, true);
2119         b2.set(2, true);
2120         assert!(b1.difference(&b2));
2121         assert!(b1.get(0));
2122         assert!(!b1.get(1));
2123         assert!(!b1.get(2));
2124     }
2125
2126     #[test]
2127     fn test_big_difference() {
2128         let mut b1 = Bitv::with_capacity(100, false);
2129         let mut b2 = Bitv::with_capacity(100, false);
2130         b1.set(0, true);
2131         b1.set(40, true);
2132         b2.set(40, true);
2133         b2.set(80, true);
2134         assert!(b1.difference(&b2));
2135         assert!(b1.get(0));
2136         assert!(!b1.get(40));
2137         assert!(!b1.get(80));
2138     }
2139
2140     #[test]
2141     fn test_small_clear() {
2142         let mut b = Bitv::with_capacity(14, true);
2143         b.clear();
2144         assert!(b.none());
2145     }
2146
2147     #[test]
2148     fn test_big_clear() {
2149         let mut b = Bitv::with_capacity(140, true);
2150         b.clear();
2151         assert!(b.none());
2152     }
2153
2154     #[test]
2155     fn test_bitv_masking() {
2156         let b = Bitv::with_capacity(140, true);
2157         let mut bs = BitvSet::from_bitv(b);
2158         assert!(bs.contains(&139));
2159         assert!(!bs.contains(&140));
2160         assert!(bs.insert(150));
2161         assert!(!bs.contains(&140));
2162         assert!(!bs.contains(&149));
2163         assert!(bs.contains(&150));
2164         assert!(!bs.contains(&151));
2165     }
2166
2167     #[test]
2168     fn test_bitv_set_basic() {
2169         // calculate nbits with u32::BITS granularity
2170         fn calc_nbits(bits: uint) -> uint {
2171             u32::BITS * ((bits + u32::BITS - 1) / u32::BITS)
2172         }
2173
2174         let mut b = BitvSet::new();
2175         assert_eq!(b.capacity(), calc_nbits(0));
2176         assert!(b.insert(3));
2177         assert_eq!(b.capacity(), calc_nbits(3));
2178         assert!(!b.insert(3));
2179         assert!(b.contains(&3));
2180         assert!(b.insert(4));
2181         assert!(!b.insert(4));
2182         assert!(b.contains(&3));
2183         assert!(b.insert(400));
2184         assert_eq!(b.capacity(), calc_nbits(400));
2185         assert!(!b.insert(400));
2186         assert!(b.contains(&400));
2187         assert_eq!(b.len(), 3);
2188     }
2189
2190     #[test]
2191     fn test_bitv_set_intersection() {
2192         let mut a = BitvSet::new();
2193         let mut b = BitvSet::new();
2194
2195         assert!(a.insert(11));
2196         assert!(a.insert(1));
2197         assert!(a.insert(3));
2198         assert!(a.insert(77));
2199         assert!(a.insert(103));
2200         assert!(a.insert(5));
2201
2202         assert!(b.insert(2));
2203         assert!(b.insert(11));
2204         assert!(b.insert(77));
2205         assert!(b.insert(5));
2206         assert!(b.insert(3));
2207
2208         let expected = [3, 5, 11, 77];
2209         let actual = a.intersection(&b).collect::<Vec<uint>>();
2210         assert_eq!(actual.as_slice(), expected.as_slice());
2211     }
2212
2213     #[test]
2214     fn test_bitv_set_difference() {
2215         let mut a = BitvSet::new();
2216         let mut b = BitvSet::new();
2217
2218         assert!(a.insert(1));
2219         assert!(a.insert(3));
2220         assert!(a.insert(5));
2221         assert!(a.insert(200));
2222         assert!(a.insert(500));
2223
2224         assert!(b.insert(3));
2225         assert!(b.insert(200));
2226
2227         let expected = [1, 5, 500];
2228         let actual = a.difference(&b).collect::<Vec<uint>>();
2229         assert_eq!(actual.as_slice(), expected.as_slice());
2230     }
2231
2232     #[test]
2233     fn test_bitv_set_symmetric_difference() {
2234         let mut a = BitvSet::new();
2235         let mut b = BitvSet::new();
2236
2237         assert!(a.insert(1));
2238         assert!(a.insert(3));
2239         assert!(a.insert(5));
2240         assert!(a.insert(9));
2241         assert!(a.insert(11));
2242
2243         assert!(b.insert(3));
2244         assert!(b.insert(9));
2245         assert!(b.insert(14));
2246         assert!(b.insert(220));
2247
2248         let expected = [1, 5, 11, 14, 220];
2249         let actual = a.symmetric_difference(&b).collect::<Vec<uint>>();
2250         assert_eq!(actual.as_slice(), expected.as_slice());
2251     }
2252
2253     #[test]
2254     fn test_bitv_set_union() {
2255         let mut a = BitvSet::new();
2256         let mut b = BitvSet::new();
2257         assert!(a.insert(1));
2258         assert!(a.insert(3));
2259         assert!(a.insert(5));
2260         assert!(a.insert(9));
2261         assert!(a.insert(11));
2262         assert!(a.insert(160));
2263         assert!(a.insert(19));
2264         assert!(a.insert(24));
2265         assert!(a.insert(200));
2266
2267         assert!(b.insert(1));
2268         assert!(b.insert(5));
2269         assert!(b.insert(9));
2270         assert!(b.insert(13));
2271         assert!(b.insert(19));
2272
2273         let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160, 200];
2274         let actual = a.union(&b).collect::<Vec<uint>>();
2275         assert_eq!(actual.as_slice(), expected.as_slice());
2276     }
2277
2278     #[test]
2279     fn test_bitv_set_subset() {
2280         let mut set1 = BitvSet::new();
2281         let mut set2 = BitvSet::new();
2282
2283         assert!(set1.is_subset(&set2)); //  {}  {}
2284         set2.insert(100);
2285         assert!(set1.is_subset(&set2)); //  {}  { 1 }
2286         set2.insert(200);
2287         assert!(set1.is_subset(&set2)); //  {}  { 1, 2 }
2288         set1.insert(200);
2289         assert!(set1.is_subset(&set2)); //  { 2 }  { 1, 2 }
2290         set1.insert(300);
2291         assert!(!set1.is_subset(&set2)); // { 2, 3 }  { 1, 2 }
2292         set2.insert(300);
2293         assert!(set1.is_subset(&set2)); // { 2, 3 }  { 1, 2, 3 }
2294         set2.insert(400);
2295         assert!(set1.is_subset(&set2)); // { 2, 3 }  { 1, 2, 3, 4 }
2296         set2.remove(&100);
2297         assert!(set1.is_subset(&set2)); // { 2, 3 }  { 2, 3, 4 }
2298         set2.remove(&300);
2299         assert!(!set1.is_subset(&set2)); // { 2, 3 }  { 2, 4 }
2300         set1.remove(&300);
2301         assert!(set1.is_subset(&set2)); // { 2 }  { 2, 4 }
2302     }
2303
2304     #[test]
2305     fn test_bitv_set_is_disjoint() {
2306         let a = BitvSet::from_bitv(from_bytes(&[0b10100010]));
2307         let b = BitvSet::from_bitv(from_bytes(&[0b01000000]));
2308         let c = BitvSet::new();
2309         let d = BitvSet::from_bitv(from_bytes(&[0b00110000]));
2310
2311         assert!(!a.is_disjoint(&d));
2312         assert!(!d.is_disjoint(&a));
2313
2314         assert!(a.is_disjoint(&b))
2315         assert!(a.is_disjoint(&c))
2316         assert!(b.is_disjoint(&a))
2317         assert!(b.is_disjoint(&c))
2318         assert!(c.is_disjoint(&a))
2319         assert!(c.is_disjoint(&b))
2320     }
2321
2322     #[test]
2323     fn test_bitv_set_union_with() {
2324         //a should grow to include larger elements
2325         let mut a = BitvSet::new();
2326         a.insert(0);
2327         let mut b = BitvSet::new();
2328         b.insert(5);
2329         let expected = BitvSet::from_bitv(from_bytes(&[0b10000100]));
2330         a.union_with(&b);
2331         assert_eq!(a, expected);
2332
2333         // Standard
2334         let mut a = BitvSet::from_bitv(from_bytes(&[0b10100010]));
2335         let mut b = BitvSet::from_bitv(from_bytes(&[0b01100010]));
2336         let c = a.clone();
2337         a.union_with(&b);
2338         b.union_with(&c);
2339         assert_eq!(a.len(), 4);
2340         assert_eq!(b.len(), 4);
2341     }
2342
2343     #[test]
2344     fn test_bitv_set_intersect_with() {
2345         // Explicitly 0'ed bits
2346         let mut a = BitvSet::from_bitv(from_bytes(&[0b10100010]));
2347         let mut b = BitvSet::from_bitv(from_bytes(&[0b00000000]));
2348         let c = a.clone();
2349         a.intersect_with(&b);
2350         b.intersect_with(&c);
2351         assert!(a.is_empty());
2352         assert!(b.is_empty());
2353
2354         // Uninitialized bits should behave like 0's
2355         let mut a = BitvSet::from_bitv(from_bytes(&[0b10100010]));
2356         let mut b = BitvSet::new();
2357         let c = a.clone();
2358         a.intersect_with(&b);
2359         b.intersect_with(&c);
2360         assert!(a.is_empty());
2361         assert!(b.is_empty());
2362
2363         // Standard
2364         let mut a = BitvSet::from_bitv(from_bytes(&[0b10100010]));
2365         let mut b = BitvSet::from_bitv(from_bytes(&[0b01100010]));
2366         let c = a.clone();
2367         a.intersect_with(&b);
2368         b.intersect_with(&c);
2369         assert_eq!(a.len(), 2);
2370         assert_eq!(b.len(), 2);
2371     }
2372
2373     #[test]
2374     fn test_bitv_set_difference_with() {
2375         // Explicitly 0'ed bits
2376         let mut a = BitvSet::from_bitv(from_bytes(&[0b00000000]));
2377         let b = BitvSet::from_bitv(from_bytes(&[0b10100010]));
2378         a.difference_with(&b);
2379         assert!(a.is_empty());
2380
2381         // Uninitialized bits should behave like 0's
2382         let mut a = BitvSet::new();
2383         let b = BitvSet::from_bitv(from_bytes(&[0b11111111]));
2384         a.difference_with(&b);
2385         assert!(a.is_empty());
2386
2387         // Standard
2388         let mut a = BitvSet::from_bitv(from_bytes(&[0b10100010]));
2389         let mut b = BitvSet::from_bitv(from_bytes(&[0b01100010]));
2390         let c = a.clone();
2391         a.difference_with(&b);
2392         b.difference_with(&c);
2393         assert_eq!(a.len(), 1);
2394         assert_eq!(b.len(), 1);
2395     }
2396
2397     #[test]
2398     fn test_bitv_set_symmetric_difference_with() {
2399         //a should grow to include larger elements
2400         let mut a = BitvSet::new();
2401         a.insert(0);
2402         a.insert(1);
2403         let mut b = BitvSet::new();
2404         b.insert(1);
2405         b.insert(5);
2406         let expected = BitvSet::from_bitv(from_bytes(&[0b10000100]));
2407         a.symmetric_difference_with(&b);
2408         assert_eq!(a, expected);
2409
2410         let mut a = BitvSet::from_bitv(from_bytes(&[0b10100010]));
2411         let b = BitvSet::new();
2412         let c = a.clone();
2413         a.symmetric_difference_with(&b);
2414         assert_eq!(a, c);
2415
2416         // Standard
2417         let mut a = BitvSet::from_bitv(from_bytes(&[0b11100010]));
2418         let mut b = BitvSet::from_bitv(from_bytes(&[0b01101010]));
2419         let c = a.clone();
2420         a.symmetric_difference_with(&b);
2421         b.symmetric_difference_with(&c);
2422         assert_eq!(a.len(), 2);
2423         assert_eq!(b.len(), 2);
2424     }
2425
2426     #[test]
2427     fn test_bitv_set_eq() {
2428         let a = BitvSet::from_bitv(from_bytes(&[0b10100010]));
2429         let b = BitvSet::from_bitv(from_bytes(&[0b00000000]));
2430         let c = BitvSet::new();
2431
2432         assert!(a == a);
2433         assert!(a != b);
2434         assert!(a != c);
2435         assert!(b == b);
2436         assert!(b == c);
2437         assert!(c == c);
2438     }
2439
2440     #[test]
2441     fn test_bitv_set_cmp() {
2442         let a = BitvSet::from_bitv(from_bytes(&[0b10100010]));
2443         let b = BitvSet::from_bitv(from_bytes(&[0b00000000]));
2444         let c = BitvSet::new();
2445
2446         assert_eq!(a.cmp(&b), Greater);
2447         assert_eq!(a.cmp(&c), Greater);
2448         assert_eq!(b.cmp(&a), Less);
2449         assert_eq!(b.cmp(&c), Equal);
2450         assert_eq!(c.cmp(&a), Less);
2451         assert_eq!(c.cmp(&b), Equal);
2452     }
2453
2454     #[test]
2455     fn test_bitv_remove() {
2456         let mut a = BitvSet::new();
2457
2458         assert!(a.insert(1));
2459         assert!(a.remove(&1));
2460
2461         assert!(a.insert(100));
2462         assert!(a.remove(&100));
2463
2464         assert!(a.insert(1000));
2465         assert!(a.remove(&1000));
2466         a.shrink_to_fit();
2467         assert_eq!(a.capacity(), u32::BITS);
2468     }
2469
2470     #[test]
2471     fn test_bitv_lt() {
2472         let mut a = Bitv::with_capacity(5u, false);
2473         let mut b = Bitv::with_capacity(5u, false);
2474
2475         assert!(!(a < b) && !(b < a));
2476         b.set(2, true);
2477         assert!(a < b);
2478         a.set(3, true);
2479         assert!(a < b);
2480         a.set(2, true);
2481         assert!(!(a < b) && b < a);
2482         b.set(0, true);
2483         assert!(a < b);
2484     }
2485
2486     #[test]
2487     fn test_ord() {
2488         let mut a = Bitv::with_capacity(5u, false);
2489         let mut b = Bitv::with_capacity(5u, false);
2490
2491         assert!(a <= b && a >= b);
2492         a.set(1, true);
2493         assert!(a > b && a >= b);
2494         assert!(b < a && b <= a);
2495         b.set(1, true);
2496         b.set(2, true);
2497         assert!(b > a && b >= a);
2498         assert!(a < b && a <= b);
2499     }
2500
2501     #[test]
2502     fn test_bitv_clone() {
2503         let mut a = BitvSet::new();
2504
2505         assert!(a.insert(1));
2506         assert!(a.insert(100));
2507         assert!(a.insert(1000));
2508
2509         let mut b = a.clone();
2510
2511         assert!(a == b);
2512
2513         assert!(b.remove(&1));
2514         assert!(a.contains(&1));
2515
2516         assert!(a.remove(&1000));
2517         assert!(b.contains(&1000));
2518     }
2519
2520     #[test]
2521     fn test_small_bitv_tests() {
2522         let v = from_bytes(&[0]);
2523         assert!(!v.all());
2524         assert!(!v.any());
2525         assert!(v.none());
2526
2527         let v = from_bytes(&[0b00010100]);
2528         assert!(!v.all());
2529         assert!(v.any());
2530         assert!(!v.none());
2531
2532         let v = from_bytes(&[0xFF]);
2533         assert!(v.all());
2534         assert!(v.any());
2535         assert!(!v.none());
2536     }
2537
2538     #[test]
2539     fn test_big_bitv_tests() {
2540         let v = from_bytes(&[ // 88 bits
2541             0, 0, 0, 0,
2542             0, 0, 0, 0,
2543             0, 0, 0]);
2544         assert!(!v.all());
2545         assert!(!v.any());
2546         assert!(v.none());
2547
2548         let v = from_bytes(&[ // 88 bits
2549             0, 0, 0b00010100, 0,
2550             0, 0, 0, 0b00110100,
2551             0, 0, 0]);
2552         assert!(!v.all());
2553         assert!(v.any());
2554         assert!(!v.none());
2555
2556         let v = from_bytes(&[ // 88 bits
2557             0xFF, 0xFF, 0xFF, 0xFF,
2558             0xFF, 0xFF, 0xFF, 0xFF,
2559             0xFF, 0xFF, 0xFF]);
2560         assert!(v.all());
2561         assert!(v.any());
2562         assert!(!v.none());
2563     }
2564
2565     #[test]
2566     fn test_bitv_push_pop() {
2567         let mut s = Bitv::with_capacity(5 * u32::BITS - 2, false);
2568         assert_eq!(s.len(), 5 * u32::BITS - 2);
2569         assert_eq!(s.get(5 * u32::BITS - 3), false);
2570         s.push(true);
2571         s.push(true);
2572         assert_eq!(s.get(5 * u32::BITS - 2), true);
2573         assert_eq!(s.get(5 * u32::BITS - 1), true);
2574         // Here the internal vector will need to be extended
2575         s.push(false);
2576         assert_eq!(s.get(5 * u32::BITS), false);
2577         s.push(false);
2578         assert_eq!(s.get(5 * u32::BITS + 1), false);
2579         assert_eq!(s.len(), 5 * u32::BITS + 2);
2580         // Pop it all off
2581         assert_eq!(s.pop(), false);
2582         assert_eq!(s.pop(), false);
2583         assert_eq!(s.pop(), true);
2584         assert_eq!(s.pop(), true);
2585         assert_eq!(s.len(), 5 * u32::BITS - 2);
2586     }
2587
2588     #[test]
2589     fn test_bitv_truncate() {
2590         let mut s = Bitv::with_capacity(5 * u32::BITS, true);
2591
2592         assert_eq!(s, Bitv::with_capacity(5 * u32::BITS, true));
2593         assert_eq!(s.len(), 5 * u32::BITS);
2594         s.truncate(4 * u32::BITS);
2595         assert_eq!(s, Bitv::with_capacity(4 * u32::BITS, true));
2596         assert_eq!(s.len(), 4 * u32::BITS);
2597         // Truncating to a size > s.len() should be a noop
2598         s.truncate(5 * u32::BITS);
2599         assert_eq!(s, Bitv::with_capacity(4 * u32::BITS, true));
2600         assert_eq!(s.len(), 4 * u32::BITS);
2601         s.truncate(3 * u32::BITS - 10);
2602         assert_eq!(s, Bitv::with_capacity(3 * u32::BITS - 10, true));
2603         assert_eq!(s.len(), 3 * u32::BITS - 10);
2604         s.truncate(0);
2605         assert_eq!(s, Bitv::with_capacity(0, true));
2606         assert_eq!(s.len(), 0);
2607     }
2608
2609     #[test]
2610     fn test_bitv_reserve() {
2611         let mut s = Bitv::with_capacity(5 * u32::BITS, true);
2612         // Check capacity
2613         assert_eq!(s.capacity(), 5 * u32::BITS);
2614         s.reserve(2 * u32::BITS);
2615         assert_eq!(s.capacity(), 5 * u32::BITS);
2616         s.reserve(7 * u32::BITS);
2617         assert_eq!(s.capacity(), 7 * u32::BITS);
2618         s.reserve(7 * u32::BITS);
2619         assert_eq!(s.capacity(), 7 * u32::BITS);
2620         s.reserve(7 * u32::BITS + 1);
2621         assert_eq!(s.capacity(), 8 * u32::BITS);
2622         // Check that length hasn't changed
2623         assert_eq!(s.len(), 5 * u32::BITS);
2624         s.push(true);
2625         s.push(false);
2626         s.push(true);
2627         assert_eq!(s.get(5 * u32::BITS - 1), true);
2628         assert_eq!(s.get(5 * u32::BITS - 0), true);
2629         assert_eq!(s.get(5 * u32::BITS + 1), false);
2630         assert_eq!(s.get(5 * u32::BITS + 2), true);
2631     }
2632
2633     #[test]
2634     fn test_bitv_grow() {
2635         let mut bitv = from_bytes(&[0b10110110, 0b00000000, 0b10101010]);
2636         bitv.grow(32, true);
2637         assert_eq!(bitv, from_bytes(&[0b10110110, 0b00000000, 0b10101010,
2638                                      0xFF, 0xFF, 0xFF, 0xFF]));
2639         bitv.grow(64, false);
2640         assert_eq!(bitv, from_bytes(&[0b10110110, 0b00000000, 0b10101010,
2641                                      0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0]));
2642         bitv.grow(16, true);
2643         assert_eq!(bitv, from_bytes(&[0b10110110, 0b00000000, 0b10101010,
2644                                      0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]));
2645     }
2646
2647     #[test]
2648     fn test_bitv_extend() {
2649         let mut bitv = from_bytes(&[0b10110110, 0b00000000, 0b11111111]);
2650         let ext = from_bytes(&[0b01001001, 0b10010010, 0b10111101]);
2651         bitv.extend(ext.iter());
2652         assert_eq!(bitv, from_bytes(&[0b10110110, 0b00000000, 0b11111111,
2653                                      0b01001001, 0b10010010, 0b10111101]));
2654     }
2655
2656     #[test]
2657     fn test_bitv_set_show() {
2658         let mut s = BitvSet::new();
2659         s.insert(1);
2660         s.insert(10);
2661         s.insert(50);
2662         s.insert(2);
2663         assert_eq!("{1, 2, 10, 50}".to_string(), s.to_string());
2664     }
2665
2666     fn rng() -> rand::IsaacRng {
2667         let seed: &[_] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
2668         rand::SeedableRng::from_seed(seed)
2669     }
2670
2671     #[bench]
2672     fn bench_uint_small(b: &mut Bencher) {
2673         let mut r = rng();
2674         let mut bitv = 0 as uint;
2675         b.iter(|| {
2676             for _ in range(0u, 100) {
2677                 bitv |= 1 << ((r.next_u32() as uint) % u32::BITS);
2678             }
2679             black_box(&bitv)
2680         });
2681     }
2682
2683     #[bench]
2684     fn bench_bitv_set_big_fixed(b: &mut Bencher) {
2685         let mut r = rng();
2686         let mut bitv = Bitv::with_capacity(BENCH_BITS, false);
2687         b.iter(|| {
2688             for _ in range(0u, 100) {
2689                 bitv.set((r.next_u32() as uint) % BENCH_BITS, true);
2690             }
2691             black_box(&bitv)
2692         });
2693     }
2694
2695     #[bench]
2696     fn bench_bitv_set_big_variable(b: &mut Bencher) {
2697         let mut r = rng();
2698         let mut bitv = Bitv::with_capacity(BENCH_BITS, false);
2699         b.iter(|| {
2700             for _ in range(0u, 100) {
2701                 bitv.set((r.next_u32() as uint) % BENCH_BITS, r.gen());
2702             }
2703             black_box(&bitv);
2704         });
2705     }
2706
2707     #[bench]
2708     fn bench_bitv_set_small(b: &mut Bencher) {
2709         let mut r = rng();
2710         let mut bitv = Bitv::with_capacity(u32::BITS, false);
2711         b.iter(|| {
2712             for _ in range(0u, 100) {
2713                 bitv.set((r.next_u32() as uint) % u32::BITS, true);
2714             }
2715             black_box(&bitv);
2716         });
2717     }
2718
2719     #[bench]
2720     fn bench_bitvset_small(b: &mut Bencher) {
2721         let mut r = rng();
2722         let mut bitv = BitvSet::new();
2723         b.iter(|| {
2724             for _ in range(0u, 100) {
2725                 bitv.insert((r.next_u32() as uint) % u32::BITS);
2726             }
2727             black_box(&bitv);
2728         });
2729     }
2730
2731     #[bench]
2732     fn bench_bitvset_big(b: &mut Bencher) {
2733         let mut r = rng();
2734         let mut bitv = BitvSet::new();
2735         b.iter(|| {
2736             for _ in range(0u, 100) {
2737                 bitv.insert((r.next_u32() as uint) % BENCH_BITS);
2738             }
2739             black_box(&bitv);
2740         });
2741     }
2742
2743     #[bench]
2744     fn bench_bitv_big_union(b: &mut Bencher) {
2745         let mut b1 = Bitv::with_capacity(BENCH_BITS, false);
2746         let b2 = Bitv::with_capacity(BENCH_BITS, false);
2747         b.iter(|| {
2748             b1.union(&b2)
2749         })
2750     }
2751
2752     #[bench]
2753     fn bench_bitv_small_iter(b: &mut Bencher) {
2754         let bitv = Bitv::with_capacity(u32::BITS, false);
2755         b.iter(|| {
2756             let mut sum = 0u;
2757             for _ in range(0u, 10) {
2758                 for pres in bitv.iter() {
2759                     sum += pres as uint;
2760                 }
2761             }
2762             sum
2763         })
2764     }
2765
2766     #[bench]
2767     fn bench_bitv_big_iter(b: &mut Bencher) {
2768         let bitv = Bitv::with_capacity(BENCH_BITS, false);
2769         b.iter(|| {
2770             let mut sum = 0u;
2771             for pres in bitv.iter() {
2772                 sum += pres as uint;
2773             }
2774             sum
2775         })
2776     }
2777
2778     #[bench]
2779     fn bench_bitvset_iter(b: &mut Bencher) {
2780         let bitv = BitvSet::from_bitv(from_fn(BENCH_BITS,
2781                                               |idx| {idx % 3 == 0}));
2782         b.iter(|| {
2783             let mut sum = 0u;
2784             for idx in bitv.iter() {
2785                 sum += idx as uint;
2786             }
2787             sum
2788         })
2789     }
2790 }