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