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