]> git.lizzy.rs Git - rust.git/blob - src/libcollections/bit.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[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 `usize`.
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 usize) {
58 //!         // if i is a prime
59 //!         if bv[i] {
60 //!             // Mark all multiples of i as non-prime (any multiples below i * i
61 //!             // will have been marked as non-prime previously)
62 //!             for j in iter::range_step(i * i, max_prime, i) { bv.set(j, false) }
63 //!         }
64 //!     }
65 //!     BitvSet::from_bitv(bv)
66 //! };
67 //!
68 //! // Simple primality tests below our max bound
69 //! let print_primes = 20;
70 //! print!("The primes below {} are: ", print_primes);
71 //! for x in 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, usize};
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: usize
166 }
167
168 // FIXME(Gankro): NopeNopeNopeNopeNope (wait for IndexGet to be a thing)
169 impl Index<usize> for Bitv {
170     type Output = bool;
171
172     #[inline]
173     fn index(&self, i: &usize) -> &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: usize) -> usize {
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 usize::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: usize) -> 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(10, false);
270     /// assert_eq!(bv.len(), 10);
271     /// for x in bv.iter() {
272     ///     assert_eq!(x, false);
273     /// }
274     /// ```
275     pub fn from_elem(nbits: usize, 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: usize) -> 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: usize, mut f: F) -> Bitv where F: FnMut(usize) -> bool {
355         let mut bitv = Bitv::from_elem(len, false);
356         for i in 0..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: usize) -> 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: usize, 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: usize, bit: usize) -> 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: usize) {
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 `usize`.
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: usize) {
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 `usize`.
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: usize) {
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) -> usize {
792         self.storage.capacity().checked_mul(u32::BITS).unwrap_or(usize::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 `usize`.
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: usize, 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) -> usize { 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: usize,
1016     end_idx: usize,
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) -> (usize, Option<usize>) {
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) -> usize {
1060         self.end_idx - self.next_idx
1061     }
1062
1063     #[inline]
1064     fn idx(&mut self, index: usize) -> Option<bool> {
1065         if index >= self.indexable() {
1066             None
1067         } else {
1068             Some(self.bitv[index])
1069         }
1070     }
1071 }
1072
1073 #[stable(feature = "rust1", since = "1.0.0")]
1074 impl<'a> IntoIterator for &'a Bitv {
1075     type Item = bool;
1076     type IntoIter = Iter<'a>;
1077
1078     fn into_iter(self) -> Iter<'a> {
1079         self.iter()
1080     }
1081 }
1082
1083 /// An implementation of a set using a bit vector as an underlying
1084 /// representation for holding unsigned numerical elements.
1085 ///
1086 /// It should also be noted that the amount of storage necessary for holding a
1087 /// set of objects is proportional to the maximum of the objects when viewed
1088 /// as a `usize`.
1089 ///
1090 /// # Examples
1091 ///
1092 /// ```
1093 /// use std::collections::{BitvSet, Bitv};
1094 ///
1095 /// // It's a regular set
1096 /// let mut s = BitvSet::new();
1097 /// s.insert(0);
1098 /// s.insert(3);
1099 /// s.insert(7);
1100 ///
1101 /// s.remove(&7);
1102 ///
1103 /// if !s.contains(&7) {
1104 ///     println!("There is no 7");
1105 /// }
1106 ///
1107 /// // Can initialize from a `Bitv`
1108 /// let other = BitvSet::from_bitv(Bitv::from_bytes(&[0b11010000]));
1109 ///
1110 /// s.union_with(&other);
1111 ///
1112 /// // Print 0, 1, 3 in some order
1113 /// for x in s.iter() {
1114 ///     println!("{}", x);
1115 /// }
1116 ///
1117 /// // Can convert back to a `Bitv`
1118 /// let bv: Bitv = s.into_bitv();
1119 /// assert!(bv[3]);
1120 /// ```
1121 #[derive(Clone)]
1122 #[unstable(feature = "collections",
1123            reason = "RFC 509")]
1124 pub struct BitvSet {
1125     bitv: Bitv,
1126 }
1127
1128 #[stable(feature = "rust1", since = "1.0.0")]
1129 impl Default for BitvSet {
1130     #[inline]
1131     fn default() -> BitvSet { BitvSet::new() }
1132 }
1133
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 impl FromIterator<usize> for BitvSet {
1136     fn from_iter<I:Iterator<Item=usize>>(iterator: I) -> BitvSet {
1137         let mut ret = BitvSet::new();
1138         ret.extend(iterator);
1139         ret
1140     }
1141 }
1142
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 impl Extend<usize> for BitvSet {
1145     #[inline]
1146     fn extend<I: Iterator<Item=usize>>(&mut self, iterator: I) {
1147         for i in iterator {
1148             self.insert(i);
1149         }
1150     }
1151 }
1152
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 impl PartialOrd for BitvSet {
1155     #[inline]
1156     fn partial_cmp(&self, other: &BitvSet) -> Option<Ordering> {
1157         let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1158         iter::order::partial_cmp(a_iter, b_iter)
1159     }
1160 }
1161
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 impl Ord for BitvSet {
1164     #[inline]
1165     fn cmp(&self, other: &BitvSet) -> Ordering {
1166         let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1167         iter::order::cmp(a_iter, b_iter)
1168     }
1169 }
1170
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl cmp::PartialEq for BitvSet {
1173     #[inline]
1174     fn eq(&self, other: &BitvSet) -> bool {
1175         let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1176         iter::order::eq(a_iter, b_iter)
1177     }
1178 }
1179
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 impl cmp::Eq for BitvSet {}
1182
1183 impl BitvSet {
1184     /// Creates a new empty `BitvSet`.
1185     ///
1186     /// # Examples
1187     ///
1188     /// ```
1189     /// use std::collections::BitvSet;
1190     ///
1191     /// let mut s = BitvSet::new();
1192     /// ```
1193     #[inline]
1194     #[stable(feature = "rust1", since = "1.0.0")]
1195     pub fn new() -> BitvSet {
1196         BitvSet { bitv: Bitv::new() }
1197     }
1198
1199     /// Creates a new `BitvSet` with initially no contents, able to
1200     /// hold `nbits` elements without resizing.
1201     ///
1202     /// # Examples
1203     ///
1204     /// ```
1205     /// use std::collections::BitvSet;
1206     ///
1207     /// let mut s = BitvSet::with_capacity(100);
1208     /// assert!(s.capacity() >= 100);
1209     /// ```
1210     #[inline]
1211     #[stable(feature = "rust1", since = "1.0.0")]
1212     pub fn with_capacity(nbits: usize) -> BitvSet {
1213         let bitv = Bitv::from_elem(nbits, false);
1214         BitvSet::from_bitv(bitv)
1215     }
1216
1217     /// Creates a new `BitvSet` from the given bit vector.
1218     ///
1219     /// # Examples
1220     ///
1221     /// ```
1222     /// use std::collections::{Bitv, BitvSet};
1223     ///
1224     /// let bv = Bitv::from_bytes(&[0b01100000]);
1225     /// let s = BitvSet::from_bitv(bv);
1226     ///
1227     /// // Print 1, 2 in arbitrary order
1228     /// for x in s.iter() {
1229     ///     println!("{}", x);
1230     /// }
1231     /// ```
1232     #[inline]
1233     pub fn from_bitv(bitv: Bitv) -> BitvSet {
1234         BitvSet { bitv: bitv }
1235     }
1236
1237     /// Returns the capacity in bits for this bit vector. Inserting any
1238     /// element less than this amount will not trigger a resizing.
1239     ///
1240     /// # Examples
1241     ///
1242     /// ```
1243     /// use std::collections::BitvSet;
1244     ///
1245     /// let mut s = BitvSet::with_capacity(100);
1246     /// assert!(s.capacity() >= 100);
1247     /// ```
1248     #[inline]
1249     #[stable(feature = "rust1", since = "1.0.0")]
1250     pub fn capacity(&self) -> usize {
1251         self.bitv.capacity()
1252     }
1253
1254     /// Reserves capacity for the given `BitvSet` to contain `len` distinct elements. In the case
1255     /// of `BitvSet` this means reallocations will not occur as long as all inserted elements
1256     /// are less than `len`.
1257     ///
1258     /// The collection may reserve more space to avoid frequent reallocations.
1259     ///
1260     ///
1261     /// # Examples
1262     ///
1263     /// ```
1264     /// use std::collections::BitvSet;
1265     ///
1266     /// let mut s = BitvSet::new();
1267     /// s.reserve_len(10);
1268     /// assert!(s.capacity() >= 10);
1269     /// ```
1270     #[stable(feature = "rust1", since = "1.0.0")]
1271     pub fn reserve_len(&mut self, len: usize) {
1272         let cur_len = self.bitv.len();
1273         if len >= cur_len {
1274             self.bitv.reserve(len - cur_len);
1275         }
1276     }
1277
1278     /// Reserves the minimum capacity for the given `BitvSet` to contain `len` distinct elements.
1279     /// In the case of `BitvSet` this means reallocations will not occur as long as all inserted
1280     /// elements are less than `len`.
1281     ///
1282     /// Note that the allocator may give the collection more space than it requests. Therefore
1283     /// capacity can not be relied upon to be precisely minimal. Prefer `reserve_len` if future
1284     /// insertions are expected.
1285     ///
1286     ///
1287     /// # Examples
1288     ///
1289     /// ```
1290     /// use std::collections::BitvSet;
1291     ///
1292     /// let mut s = BitvSet::new();
1293     /// s.reserve_len_exact(10);
1294     /// assert!(s.capacity() >= 10);
1295     /// ```
1296     #[stable(feature = "rust1", since = "1.0.0")]
1297     pub fn reserve_len_exact(&mut self, len: usize) {
1298         let cur_len = self.bitv.len();
1299         if len >= cur_len {
1300             self.bitv.reserve_exact(len - cur_len);
1301         }
1302     }
1303
1304
1305     /// Consumes this set to return the underlying bit vector.
1306     ///
1307     /// # Examples
1308     ///
1309     /// ```
1310     /// use std::collections::BitvSet;
1311     ///
1312     /// let mut s = BitvSet::new();
1313     /// s.insert(0);
1314     /// s.insert(3);
1315     ///
1316     /// let bv = s.into_bitv();
1317     /// assert!(bv[0]);
1318     /// assert!(bv[3]);
1319     /// ```
1320     #[inline]
1321     pub fn into_bitv(self) -> Bitv {
1322         self.bitv
1323     }
1324
1325     /// Returns a reference to the underlying bit vector.
1326     ///
1327     /// # Examples
1328     ///
1329     /// ```
1330     /// use std::collections::BitvSet;
1331     ///
1332     /// let mut s = BitvSet::new();
1333     /// s.insert(0);
1334     ///
1335     /// let bv = s.get_ref();
1336     /// assert_eq!(bv[0], true);
1337     /// ```
1338     #[inline]
1339     pub fn get_ref(&self) -> &Bitv {
1340         &self.bitv
1341     }
1342
1343     #[inline]
1344     fn other_op<F>(&mut self, other: &BitvSet, mut f: F) where F: FnMut(u32, u32) -> u32 {
1345         // Unwrap Bitvs
1346         let self_bitv = &mut self.bitv;
1347         let other_bitv = &other.bitv;
1348
1349         let self_len = self_bitv.len();
1350         let other_len = other_bitv.len();
1351
1352         // Expand the vector if necessary
1353         if self_len < other_len {
1354             self_bitv.grow(other_len - self_len, false);
1355         }
1356
1357         // virtually pad other with 0's for equal lengths
1358         let other_words = {
1359             let (_, result) = match_words(self_bitv, other_bitv);
1360             result
1361         };
1362
1363         // Apply values found in other
1364         for (i, w) in other_words {
1365             let old = self_bitv.storage[i];
1366             let new = f(old, w);
1367             self_bitv.storage[i] = new;
1368         }
1369     }
1370
1371     /// Truncates the underlying vector to the least length required.
1372     ///
1373     /// # Examples
1374     ///
1375     /// ```
1376     /// use std::collections::BitvSet;
1377     ///
1378     /// let mut s = BitvSet::new();
1379     /// s.insert(32183231);
1380     /// s.remove(&32183231);
1381     ///
1382     /// // Internal storage will probably be bigger than necessary
1383     /// println!("old capacity: {}", s.capacity());
1384     ///
1385     /// // Now should be smaller
1386     /// s.shrink_to_fit();
1387     /// println!("new capacity: {}", s.capacity());
1388     /// ```
1389     #[inline]
1390     #[stable(feature = "rust1", since = "1.0.0")]
1391     pub fn shrink_to_fit(&mut self) {
1392         let bitv = &mut self.bitv;
1393         // Obtain original length
1394         let old_len = bitv.storage.len();
1395         // Obtain coarse trailing zero length
1396         let n = bitv.storage.iter().rev().take_while(|&&n| n == 0).count();
1397         // Truncate
1398         let trunc_len = cmp::max(old_len - n, 1);
1399         bitv.storage.truncate(trunc_len);
1400         bitv.nbits = trunc_len * u32::BITS;
1401     }
1402
1403     /// Iterator over each u32 stored in the `BitvSet`.
1404     ///
1405     /// # Examples
1406     ///
1407     /// ```
1408     /// use std::collections::{Bitv, BitvSet};
1409     ///
1410     /// let s = BitvSet::from_bitv(Bitv::from_bytes(&[0b01001010]));
1411     ///
1412     /// // Print 1, 4, 6 in arbitrary order
1413     /// for x in s.iter() {
1414     ///     println!("{}", x);
1415     /// }
1416     /// ```
1417     #[inline]
1418     #[stable(feature = "rust1", since = "1.0.0")]
1419     pub fn iter(&self) -> bitv_set::Iter {
1420         SetIter {set: self, next_idx: 0}
1421     }
1422
1423     /// Iterator over each u32 stored in `self` union `other`.
1424     /// See [union_with](#method.union_with) for an efficient in-place version.
1425     ///
1426     /// # Examples
1427     ///
1428     /// ```
1429     /// use std::collections::{Bitv, BitvSet};
1430     ///
1431     /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
1432     /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
1433     ///
1434     /// // Print 0, 1, 2, 4 in arbitrary order
1435     /// for x in a.union(&b) {
1436     ///     println!("{}", x);
1437     /// }
1438     /// ```
1439     #[inline]
1440     #[stable(feature = "rust1", since = "1.0.0")]
1441     pub fn union<'a>(&'a self, other: &'a BitvSet) -> Union<'a> {
1442         fn or(w1: u32, w2: u32) -> u32 { w1 | w2 }
1443
1444         Union(TwoBitPositions {
1445             set: self,
1446             other: other,
1447             merge: or,
1448             current_word: 0,
1449             next_idx: 0
1450         })
1451     }
1452
1453     /// Iterator over each usize stored in `self` intersect `other`.
1454     /// See [intersect_with](#method.intersect_with) for an efficient in-place version.
1455     ///
1456     /// # Examples
1457     ///
1458     /// ```
1459     /// use std::collections::{Bitv, BitvSet};
1460     ///
1461     /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
1462     /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
1463     ///
1464     /// // Print 2
1465     /// for x in a.intersection(&b) {
1466     ///     println!("{}", x);
1467     /// }
1468     /// ```
1469     #[inline]
1470     #[stable(feature = "rust1", since = "1.0.0")]
1471     pub fn intersection<'a>(&'a self, other: &'a BitvSet) -> Intersection<'a> {
1472         fn bitand(w1: u32, w2: u32) -> u32 { w1 & w2 }
1473         let min = cmp::min(self.bitv.len(), other.bitv.len());
1474         Intersection(TwoBitPositions {
1475             set: self,
1476             other: other,
1477             merge: bitand,
1478             current_word: 0,
1479             next_idx: 0
1480         }.take(min))
1481     }
1482
1483     /// Iterator over each usize stored in the `self` setminus `other`.
1484     /// See [difference_with](#method.difference_with) for an efficient in-place version.
1485     ///
1486     /// # Examples
1487     ///
1488     /// ```
1489     /// use std::collections::{BitvSet, Bitv};
1490     ///
1491     /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
1492     /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
1493     ///
1494     /// // Print 1, 4 in arbitrary order
1495     /// for x in a.difference(&b) {
1496     ///     println!("{}", x);
1497     /// }
1498     ///
1499     /// // Note that difference is not symmetric,
1500     /// // and `b - a` means something else.
1501     /// // This prints 0
1502     /// for x in b.difference(&a) {
1503     ///     println!("{}", x);
1504     /// }
1505     /// ```
1506     #[inline]
1507     #[stable(feature = "rust1", since = "1.0.0")]
1508     pub fn difference<'a>(&'a self, other: &'a BitvSet) -> Difference<'a> {
1509         fn diff(w1: u32, w2: u32) -> u32 { w1 & !w2 }
1510
1511         Difference(TwoBitPositions {
1512             set: self,
1513             other: other,
1514             merge: diff,
1515             current_word: 0,
1516             next_idx: 0
1517         })
1518     }
1519
1520     /// Iterator over each u32 stored in the symmetric difference of `self` and `other`.
1521     /// See [symmetric_difference_with](#method.symmetric_difference_with) for
1522     /// an efficient in-place version.
1523     ///
1524     /// # Examples
1525     ///
1526     /// ```
1527     /// use std::collections::{BitvSet, Bitv};
1528     ///
1529     /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
1530     /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
1531     ///
1532     /// // Print 0, 1, 4 in arbitrary order
1533     /// for x in a.symmetric_difference(&b) {
1534     ///     println!("{}", x);
1535     /// }
1536     /// ```
1537     #[inline]
1538     #[stable(feature = "rust1", since = "1.0.0")]
1539     pub fn symmetric_difference<'a>(&'a self, other: &'a BitvSet) -> SymmetricDifference<'a> {
1540         fn bitxor(w1: u32, w2: u32) -> u32 { w1 ^ w2 }
1541
1542         SymmetricDifference(TwoBitPositions {
1543             set: self,
1544             other: other,
1545             merge: bitxor,
1546             current_word: 0,
1547             next_idx: 0
1548         })
1549     }
1550
1551     /// Unions in-place with the specified other bit vector.
1552     ///
1553     /// # Examples
1554     ///
1555     /// ```
1556     /// use std::collections::{BitvSet, Bitv};
1557     ///
1558     /// let a   = 0b01101000;
1559     /// let b   = 0b10100000;
1560     /// let res = 0b11101000;
1561     ///
1562     /// let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
1563     /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
1564     /// let res = BitvSet::from_bitv(Bitv::from_bytes(&[res]));
1565     ///
1566     /// a.union_with(&b);
1567     /// assert_eq!(a, res);
1568     /// ```
1569     #[inline]
1570     pub fn union_with(&mut self, other: &BitvSet) {
1571         self.other_op(other, |w1, w2| w1 | w2);
1572     }
1573
1574     /// Intersects in-place with the specified other bit vector.
1575     ///
1576     /// # Examples
1577     ///
1578     /// ```
1579     /// use std::collections::{BitvSet, Bitv};
1580     ///
1581     /// let a   = 0b01101000;
1582     /// let b   = 0b10100000;
1583     /// let res = 0b00100000;
1584     ///
1585     /// let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
1586     /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
1587     /// let res = BitvSet::from_bitv(Bitv::from_bytes(&[res]));
1588     ///
1589     /// a.intersect_with(&b);
1590     /// assert_eq!(a, res);
1591     /// ```
1592     #[inline]
1593     pub fn intersect_with(&mut self, other: &BitvSet) {
1594         self.other_op(other, |w1, w2| w1 & w2);
1595     }
1596
1597     /// Makes this bit vector the difference with the specified other bit vector
1598     /// in-place.
1599     ///
1600     /// # Examples
1601     ///
1602     /// ```
1603     /// use std::collections::{BitvSet, Bitv};
1604     ///
1605     /// let a   = 0b01101000;
1606     /// let b   = 0b10100000;
1607     /// let a_b = 0b01001000; // a - b
1608     /// let b_a = 0b10000000; // b - a
1609     ///
1610     /// let mut bva = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
1611     /// let bvb = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
1612     /// let bva_b = BitvSet::from_bitv(Bitv::from_bytes(&[a_b]));
1613     /// let bvb_a = BitvSet::from_bitv(Bitv::from_bytes(&[b_a]));
1614     ///
1615     /// bva.difference_with(&bvb);
1616     /// assert_eq!(bva, bva_b);
1617     ///
1618     /// let bva = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
1619     /// let mut bvb = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
1620     ///
1621     /// bvb.difference_with(&bva);
1622     /// assert_eq!(bvb, bvb_a);
1623     /// ```
1624     #[inline]
1625     pub fn difference_with(&mut self, other: &BitvSet) {
1626         self.other_op(other, |w1, w2| w1 & !w2);
1627     }
1628
1629     /// Makes this bit vector the symmetric difference with the specified other
1630     /// bit vector in-place.
1631     ///
1632     /// # Examples
1633     ///
1634     /// ```
1635     /// use std::collections::{BitvSet, Bitv};
1636     ///
1637     /// let a   = 0b01101000;
1638     /// let b   = 0b10100000;
1639     /// let res = 0b11001000;
1640     ///
1641     /// let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
1642     /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
1643     /// let res = BitvSet::from_bitv(Bitv::from_bytes(&[res]));
1644     ///
1645     /// a.symmetric_difference_with(&b);
1646     /// assert_eq!(a, res);
1647     /// ```
1648     #[inline]
1649     pub fn symmetric_difference_with(&mut self, other: &BitvSet) {
1650         self.other_op(other, |w1, w2| w1 ^ w2);
1651     }
1652
1653     /// Return the number of set bits in this set.
1654     #[inline]
1655     #[stable(feature = "rust1", since = "1.0.0")]
1656     pub fn len(&self) -> usize  {
1657         self.bitv.blocks().fold(0, |acc, n| acc + n.count_ones())
1658     }
1659
1660     /// Returns whether there are no bits set in this set
1661     #[inline]
1662     #[stable(feature = "rust1", since = "1.0.0")]
1663     pub fn is_empty(&self) -> bool {
1664         self.bitv.none()
1665     }
1666
1667     /// Clears all bits in this set
1668     #[inline]
1669     #[stable(feature = "rust1", since = "1.0.0")]
1670     pub fn clear(&mut self) {
1671         self.bitv.clear();
1672     }
1673
1674     /// Returns `true` if this set contains the specified integer.
1675     #[inline]
1676     #[stable(feature = "rust1", since = "1.0.0")]
1677     pub fn contains(&self, value: &usize) -> bool {
1678         let bitv = &self.bitv;
1679         *value < bitv.nbits && bitv[*value]
1680     }
1681
1682     /// Returns `true` if the set has no elements in common with `other`.
1683     /// This is equivalent to checking for an empty intersection.
1684     #[inline]
1685     #[stable(feature = "rust1", since = "1.0.0")]
1686     pub fn is_disjoint(&self, other: &BitvSet) -> bool {
1687         self.intersection(other).next().is_none()
1688     }
1689
1690     /// Returns `true` if the set is a subset of another.
1691     #[inline]
1692     #[stable(feature = "rust1", since = "1.0.0")]
1693     pub fn is_subset(&self, other: &BitvSet) -> bool {
1694         let self_bitv = &self.bitv;
1695         let other_bitv = &other.bitv;
1696         let other_blocks = blocks_for_bits(other_bitv.len());
1697
1698         // Check that `self` intersect `other` is self
1699         self_bitv.blocks().zip(other_bitv.blocks()).all(|(w1, w2)| w1 & w2 == w1) &&
1700         // Make sure if `self` has any more blocks than `other`, they're all 0
1701         self_bitv.blocks().skip(other_blocks).all(|w| w == 0)
1702     }
1703
1704     /// Returns `true` if the set is a superset of another.
1705     #[inline]
1706     #[stable(feature = "rust1", since = "1.0.0")]
1707     pub fn is_superset(&self, other: &BitvSet) -> bool {
1708         other.is_subset(self)
1709     }
1710
1711     /// Adds a value to the set. Returns `true` if the value was not already
1712     /// present in the set.
1713     #[stable(feature = "rust1", since = "1.0.0")]
1714     pub fn insert(&mut self, value: usize) -> bool {
1715         if self.contains(&value) {
1716             return false;
1717         }
1718
1719         // Ensure we have enough space to hold the new element
1720         let len = self.bitv.len();
1721         if value >= len {
1722             self.bitv.grow(value - len + 1, false)
1723         }
1724
1725         self.bitv.set(value, true);
1726         return true;
1727     }
1728
1729     /// Removes a value from the set. Returns `true` if the value was
1730     /// present in the set.
1731     #[stable(feature = "rust1", since = "1.0.0")]
1732     pub fn remove(&mut self, value: &usize) -> bool {
1733         if !self.contains(value) {
1734             return false;
1735         }
1736
1737         self.bitv.set(*value, false);
1738
1739         return true;
1740     }
1741 }
1742
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 impl fmt::Debug for BitvSet {
1745     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1746         try!(write!(fmt, "BitvSet {{"));
1747         let mut first = true;
1748         for n in self {
1749             if !first {
1750                 try!(write!(fmt, ", "));
1751             }
1752             try!(write!(fmt, "{:?}", n));
1753             first = false;
1754         }
1755         write!(fmt, "}}")
1756     }
1757 }
1758
1759 impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for BitvSet {
1760     fn hash(&self, state: &mut S) {
1761         for pos in self {
1762             pos.hash(state);
1763         }
1764     }
1765 }
1766
1767 /// An iterator for `BitvSet`.
1768 #[derive(Clone)]
1769 #[stable(feature = "rust1", since = "1.0.0")]
1770 pub struct SetIter<'a> {
1771     set: &'a BitvSet,
1772     next_idx: usize
1773 }
1774
1775 /// An iterator combining two `BitvSet` iterators.
1776 #[derive(Clone)]
1777 struct TwoBitPositions<'a> {
1778     set: &'a BitvSet,
1779     other: &'a BitvSet,
1780     merge: fn(u32, u32) -> u32,
1781     current_word: u32,
1782     next_idx: usize
1783 }
1784
1785 #[stable(feature = "rust1", since = "1.0.0")]
1786 pub struct Union<'a>(TwoBitPositions<'a>);
1787 #[stable(feature = "rust1", since = "1.0.0")]
1788 pub struct Intersection<'a>(Take<TwoBitPositions<'a>>);
1789 #[stable(feature = "rust1", since = "1.0.0")]
1790 pub struct Difference<'a>(TwoBitPositions<'a>);
1791 #[stable(feature = "rust1", since = "1.0.0")]
1792 pub struct SymmetricDifference<'a>(TwoBitPositions<'a>);
1793
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 impl<'a> Iterator for SetIter<'a> {
1796     type Item = usize;
1797
1798     fn next(&mut self) -> Option<usize> {
1799         while self.next_idx < self.set.bitv.len() {
1800             let idx = self.next_idx;
1801             self.next_idx += 1;
1802
1803             if self.set.contains(&idx) {
1804                 return Some(idx);
1805             }
1806         }
1807
1808         return None;
1809     }
1810
1811     #[inline]
1812     fn size_hint(&self) -> (usize, Option<usize>) {
1813         (0, Some(self.set.bitv.len() - self.next_idx))
1814     }
1815 }
1816
1817 #[stable(feature = "rust1", since = "1.0.0")]
1818 impl<'a> Iterator for TwoBitPositions<'a> {
1819     type Item = usize;
1820
1821     fn next(&mut self) -> Option<usize> {
1822         while self.next_idx < self.set.bitv.len() ||
1823               self.next_idx < self.other.bitv.len() {
1824             let bit_idx = self.next_idx % u32::BITS;
1825             if bit_idx == 0 {
1826                 let s_bitv = &self.set.bitv;
1827                 let o_bitv = &self.other.bitv;
1828                 // Merging the two words is a bit of an awkward dance since
1829                 // one Bitv might be longer than the other
1830                 let word_idx = self.next_idx / u32::BITS;
1831                 let w1 = if word_idx < s_bitv.storage.len() {
1832                              s_bitv.storage[word_idx]
1833                          } else { 0 };
1834                 let w2 = if word_idx < o_bitv.storage.len() {
1835                              o_bitv.storage[word_idx]
1836                          } else { 0 };
1837                 self.current_word = (self.merge)(w1, w2);
1838             }
1839
1840             self.next_idx += 1;
1841             if self.current_word & (1 << bit_idx) != 0 {
1842                 return Some(self.next_idx - 1);
1843             }
1844         }
1845         return None;
1846     }
1847
1848     #[inline]
1849     fn size_hint(&self) -> (usize, Option<usize>) {
1850         let cap = cmp::max(self.set.bitv.len(), self.other.bitv.len());
1851         (0, Some(cap - self.next_idx))
1852     }
1853 }
1854
1855 #[stable(feature = "rust1", since = "1.0.0")]
1856 impl<'a> Iterator for Union<'a> {
1857     type Item = usize;
1858
1859     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
1860     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
1861 }
1862
1863 #[stable(feature = "rust1", since = "1.0.0")]
1864 impl<'a> Iterator for Intersection<'a> {
1865     type Item = usize;
1866
1867     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
1868     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
1869 }
1870
1871 #[stable(feature = "rust1", since = "1.0.0")]
1872 impl<'a> Iterator for Difference<'a> {
1873     type Item = usize;
1874
1875     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
1876     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
1877 }
1878
1879 #[stable(feature = "rust1", since = "1.0.0")]
1880 impl<'a> Iterator for SymmetricDifference<'a> {
1881     type Item = usize;
1882
1883     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
1884     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
1885 }
1886
1887 #[stable(feature = "rust1", since = "1.0.0")]
1888 impl<'a> IntoIterator for &'a BitvSet {
1889     type Item = usize;
1890     type IntoIter = SetIter<'a>;
1891
1892     fn into_iter(self) -> SetIter<'a> {
1893         self.iter()
1894     }
1895 }
1896
1897 #[cfg(test)]
1898 mod tests {
1899     use prelude::*;
1900     use core::u32;
1901
1902     use super::Bitv;
1903
1904     #[test]
1905     fn test_to_str() {
1906         let zerolen = Bitv::new();
1907         assert_eq!(format!("{:?}", zerolen), "");
1908
1909         let eightbits = Bitv::from_elem(8, false);
1910         assert_eq!(format!("{:?}", eightbits), "00000000")
1911     }
1912
1913     #[test]
1914     fn test_0_elements() {
1915         let act = Bitv::new();
1916         let exp = Vec::new();
1917         assert!(act.eq_vec(&exp));
1918         assert!(act.none() && act.all());
1919     }
1920
1921     #[test]
1922     fn test_1_element() {
1923         let mut act = Bitv::from_elem(1, false);
1924         assert!(act.eq_vec(&[false]));
1925         assert!(act.none() && !act.all());
1926         act = Bitv::from_elem(1, true);
1927         assert!(act.eq_vec(&[true]));
1928         assert!(!act.none() && act.all());
1929     }
1930
1931     #[test]
1932     fn test_2_elements() {
1933         let mut b = Bitv::from_elem(2, false);
1934         b.set(0, true);
1935         b.set(1, false);
1936         assert_eq!(format!("{:?}", b), "10");
1937         assert!(!b.none() && !b.all());
1938     }
1939
1940     #[test]
1941     fn test_10_elements() {
1942         let mut act;
1943         // all 0
1944
1945         act = Bitv::from_elem(10, false);
1946         assert!((act.eq_vec(
1947                     &[false, false, false, false, false, false, false, false, false, false])));
1948         assert!(act.none() && !act.all());
1949         // all 1
1950
1951         act = Bitv::from_elem(10, true);
1952         assert!((act.eq_vec(&[true, true, true, true, true, true, true, true, true, true])));
1953         assert!(!act.none() && act.all());
1954         // mixed
1955
1956         act = Bitv::from_elem(10, false);
1957         act.set(0, true);
1958         act.set(1, true);
1959         act.set(2, true);
1960         act.set(3, true);
1961         act.set(4, true);
1962         assert!((act.eq_vec(&[true, true, true, true, true, false, false, false, false, false])));
1963         assert!(!act.none() && !act.all());
1964         // mixed
1965
1966         act = Bitv::from_elem(10, false);
1967         act.set(5, true);
1968         act.set(6, true);
1969         act.set(7, true);
1970         act.set(8, true);
1971         act.set(9, true);
1972         assert!((act.eq_vec(&[false, false, false, false, false, true, true, true, true, true])));
1973         assert!(!act.none() && !act.all());
1974         // mixed
1975
1976         act = Bitv::from_elem(10, false);
1977         act.set(0, true);
1978         act.set(3, true);
1979         act.set(6, true);
1980         act.set(9, true);
1981         assert!((act.eq_vec(&[true, false, false, true, false, false, true, false, false, true])));
1982         assert!(!act.none() && !act.all());
1983     }
1984
1985     #[test]
1986     fn test_31_elements() {
1987         let mut act;
1988         // all 0
1989
1990         act = Bitv::from_elem(31, false);
1991         assert!(act.eq_vec(
1992                 &[false, false, false, false, false, false, false, false, false, false, false,
1993                   false, false, false, false, false, false, false, false, false, false, false,
1994                   false, false, false, false, false, false, false, false, false]));
1995         assert!(act.none() && !act.all());
1996         // all 1
1997
1998         act = Bitv::from_elem(31, true);
1999         assert!(act.eq_vec(
2000                 &[true, true, true, true, true, true, true, true, true, true, true, true, true,
2001                   true, true, true, true, true, true, true, true, true, true, true, true, true,
2002                   true, true, true, true, true]));
2003         assert!(!act.none() && act.all());
2004         // mixed
2005
2006         act = Bitv::from_elem(31, false);
2007         act.set(0, true);
2008         act.set(1, true);
2009         act.set(2, true);
2010         act.set(3, true);
2011         act.set(4, true);
2012         act.set(5, true);
2013         act.set(6, true);
2014         act.set(7, true);
2015         assert!(act.eq_vec(
2016                 &[true, true, true, true, true, true, true, true, false, false, false, false, false,
2017                   false, false, false, false, false, false, false, false, false, false, false,
2018                   false, false, false, false, false, false, false]));
2019         assert!(!act.none() && !act.all());
2020         // mixed
2021
2022         act = Bitv::from_elem(31, false);
2023         act.set(16, true);
2024         act.set(17, true);
2025         act.set(18, true);
2026         act.set(19, true);
2027         act.set(20, true);
2028         act.set(21, true);
2029         act.set(22, true);
2030         act.set(23, true);
2031         assert!(act.eq_vec(
2032                 &[false, false, false, false, false, false, false, false, false, false, false,
2033                   false, false, false, false, false, true, true, true, true, true, true, true, true,
2034                   false, false, false, false, false, false, false]));
2035         assert!(!act.none() && !act.all());
2036         // mixed
2037
2038         act = Bitv::from_elem(31, false);
2039         act.set(24, true);
2040         act.set(25, true);
2041         act.set(26, true);
2042         act.set(27, true);
2043         act.set(28, true);
2044         act.set(29, true);
2045         act.set(30, true);
2046         assert!(act.eq_vec(
2047                 &[false, false, false, false, false, false, false, false, false, false, false,
2048                   false, false, false, false, false, false, false, false, false, false, false,
2049                   false, false, true, true, true, true, true, true, true]));
2050         assert!(!act.none() && !act.all());
2051         // mixed
2052
2053         act = Bitv::from_elem(31, false);
2054         act.set(3, true);
2055         act.set(17, true);
2056         act.set(30, true);
2057         assert!(act.eq_vec(
2058                 &[false, false, false, true, false, false, false, false, false, false, false, false,
2059                   false, false, false, false, false, true, false, false, false, false, false, false,
2060                   false, false, false, false, false, false, true]));
2061         assert!(!act.none() && !act.all());
2062     }
2063
2064     #[test]
2065     fn test_32_elements() {
2066         let mut act;
2067         // all 0
2068
2069         act = Bitv::from_elem(32, false);
2070         assert!(act.eq_vec(
2071                 &[false, false, false, false, false, false, false, false, false, false, false,
2072                   false, false, false, false, false, false, false, false, false, false, false,
2073                   false, false, false, false, false, false, false, false, false, false]));
2074         assert!(act.none() && !act.all());
2075         // all 1
2076
2077         act = Bitv::from_elem(32, true);
2078         assert!(act.eq_vec(
2079                 &[true, true, true, true, true, true, true, true, true, true, true, true, true,
2080                   true, true, true, true, true, true, true, true, true, true, true, true, true,
2081                   true, true, true, true, true, true]));
2082         assert!(!act.none() && act.all());
2083         // mixed
2084
2085         act = Bitv::from_elem(32, false);
2086         act.set(0, true);
2087         act.set(1, true);
2088         act.set(2, true);
2089         act.set(3, true);
2090         act.set(4, true);
2091         act.set(5, true);
2092         act.set(6, true);
2093         act.set(7, true);
2094         assert!(act.eq_vec(
2095                 &[true, true, true, true, true, true, true, true, false, false, false, false, false,
2096                   false, false, false, false, false, false, false, false, false, false, false,
2097                   false, false, false, false, false, false, false, false]));
2098         assert!(!act.none() && !act.all());
2099         // mixed
2100
2101         act = Bitv::from_elem(32, false);
2102         act.set(16, true);
2103         act.set(17, true);
2104         act.set(18, true);
2105         act.set(19, true);
2106         act.set(20, true);
2107         act.set(21, true);
2108         act.set(22, true);
2109         act.set(23, true);
2110         assert!(act.eq_vec(
2111                 &[false, false, false, false, false, false, false, false, false, false, false,
2112                   false, false, false, false, false, true, true, true, true, true, true, true, true,
2113                   false, false, false, false, false, false, false, false]));
2114         assert!(!act.none() && !act.all());
2115         // mixed
2116
2117         act = Bitv::from_elem(32, false);
2118         act.set(24, true);
2119         act.set(25, true);
2120         act.set(26, true);
2121         act.set(27, true);
2122         act.set(28, true);
2123         act.set(29, true);
2124         act.set(30, true);
2125         act.set(31, true);
2126         assert!(act.eq_vec(
2127                 &[false, false, false, false, false, false, false, false, false, false, false,
2128                   false, false, false, false, false, false, false, false, false, false, false,
2129                   false, false, true, true, true, true, true, true, true, true]));
2130         assert!(!act.none() && !act.all());
2131         // mixed
2132
2133         act = Bitv::from_elem(32, false);
2134         act.set(3, true);
2135         act.set(17, true);
2136         act.set(30, true);
2137         act.set(31, true);
2138         assert!(act.eq_vec(
2139                 &[false, false, false, true, false, false, false, false, false, false, false, false,
2140                   false, false, false, false, false, true, false, false, false, false, false, false,
2141                   false, false, false, false, false, false, true, true]));
2142         assert!(!act.none() && !act.all());
2143     }
2144
2145     #[test]
2146     fn test_33_elements() {
2147         let mut act;
2148         // all 0
2149
2150         act = Bitv::from_elem(33, false);
2151         assert!(act.eq_vec(
2152                 &[false, false, false, false, false, false, false, false, false, false, false,
2153                   false, false, false, false, false, false, false, false, false, false, false,
2154                   false, false, false, false, false, false, false, false, false, false, false]));
2155         assert!(act.none() && !act.all());
2156         // all 1
2157
2158         act = Bitv::from_elem(33, true);
2159         assert!(act.eq_vec(
2160                 &[true, true, true, true, true, true, true, true, true, true, true, true, true,
2161                   true, true, true, true, true, true, true, true, true, true, true, true, true,
2162                   true, true, true, true, true, true, true]));
2163         assert!(!act.none() && act.all());
2164         // mixed
2165
2166         act = Bitv::from_elem(33, false);
2167         act.set(0, true);
2168         act.set(1, true);
2169         act.set(2, true);
2170         act.set(3, true);
2171         act.set(4, true);
2172         act.set(5, true);
2173         act.set(6, true);
2174         act.set(7, true);
2175         assert!(act.eq_vec(
2176                 &[true, true, true, true, true, true, true, true, false, false, false, false, false,
2177                   false, false, false, false, false, false, false, false, false, false, false,
2178                   false, false, false, false, false, false, false, false, false]));
2179         assert!(!act.none() && !act.all());
2180         // mixed
2181
2182         act = Bitv::from_elem(33, false);
2183         act.set(16, true);
2184         act.set(17, true);
2185         act.set(18, true);
2186         act.set(19, true);
2187         act.set(20, true);
2188         act.set(21, true);
2189         act.set(22, true);
2190         act.set(23, true);
2191         assert!(act.eq_vec(
2192                 &[false, false, false, false, false, false, false, false, false, false, false,
2193                   false, false, false, false, false, true, true, true, true, true, true, true, true,
2194                   false, false, false, false, false, false, false, false, false]));
2195         assert!(!act.none() && !act.all());
2196         // mixed
2197
2198         act = Bitv::from_elem(33, false);
2199         act.set(24, true);
2200         act.set(25, true);
2201         act.set(26, true);
2202         act.set(27, true);
2203         act.set(28, true);
2204         act.set(29, true);
2205         act.set(30, true);
2206         act.set(31, true);
2207         assert!(act.eq_vec(
2208                 &[false, false, false, false, false, false, false, false, false, false, false,
2209                   false, false, false, false, false, false, false, false, false, false, false,
2210                   false, false, true, true, true, true, true, true, true, true, false]));
2211         assert!(!act.none() && !act.all());
2212         // mixed
2213
2214         act = Bitv::from_elem(33, false);
2215         act.set(3, true);
2216         act.set(17, true);
2217         act.set(30, true);
2218         act.set(31, true);
2219         act.set(32, true);
2220         assert!(act.eq_vec(
2221                 &[false, false, false, true, false, false, false, false, false, false, false, false,
2222                   false, false, false, false, false, true, false, false, false, false, false, false,
2223                   false, false, false, false, false, false, true, true, true]));
2224         assert!(!act.none() && !act.all());
2225     }
2226
2227     #[test]
2228     fn test_equal_differing_sizes() {
2229         let v0 = Bitv::from_elem(10, false);
2230         let v1 = Bitv::from_elem(11, false);
2231         assert!(v0 != v1);
2232     }
2233
2234     #[test]
2235     fn test_equal_greatly_differing_sizes() {
2236         let v0 = Bitv::from_elem(10, false);
2237         let v1 = Bitv::from_elem(110, false);
2238         assert!(v0 != v1);
2239     }
2240
2241     #[test]
2242     fn test_equal_sneaky_small() {
2243         let mut a = Bitv::from_elem(1, false);
2244         a.set(0, true);
2245
2246         let mut b = Bitv::from_elem(1, true);
2247         b.set(0, true);
2248
2249         assert_eq!(a, b);
2250     }
2251
2252     #[test]
2253     fn test_equal_sneaky_big() {
2254         let mut a = Bitv::from_elem(100, false);
2255         for i in 0..100 {
2256             a.set(i, true);
2257         }
2258
2259         let mut b = Bitv::from_elem(100, true);
2260         for i in 0..100 {
2261             b.set(i, true);
2262         }
2263
2264         assert_eq!(a, b);
2265     }
2266
2267     #[test]
2268     fn test_from_bytes() {
2269         let bitv = Bitv::from_bytes(&[0b10110110, 0b00000000, 0b11111111]);
2270         let str = concat!("10110110", "00000000", "11111111");
2271         assert_eq!(format!("{:?}", bitv), str);
2272     }
2273
2274     #[test]
2275     fn test_to_bytes() {
2276         let mut bv = Bitv::from_elem(3, true);
2277         bv.set(1, false);
2278         assert_eq!(bv.to_bytes(), vec!(0b10100000));
2279
2280         let mut bv = Bitv::from_elem(9, false);
2281         bv.set(2, true);
2282         bv.set(8, true);
2283         assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000));
2284     }
2285
2286     #[test]
2287     fn test_from_bools() {
2288         let bools = vec![true, false, true, true];
2289         let bitv: Bitv = bools.iter().map(|n| *n).collect();
2290         assert_eq!(format!("{:?}", bitv), "1011");
2291     }
2292
2293     #[test]
2294     fn test_to_bools() {
2295         let bools = vec![false, false, true, false, false, true, true, false];
2296         assert_eq!(Bitv::from_bytes(&[0b00100110]).iter().collect::<Vec<bool>>(), bools);
2297     }
2298
2299     #[test]
2300     fn test_bitv_iterator() {
2301         let bools = vec![true, false, true, true];
2302         let bitv: Bitv = bools.iter().map(|n| *n).collect();
2303
2304         assert_eq!(bitv.iter().collect::<Vec<bool>>(), bools);
2305
2306         let long: Vec<_> = (0i32..10000).map(|i| i % 2 == 0).collect();
2307         let bitv: Bitv = long.iter().map(|n| *n).collect();
2308         assert_eq!(bitv.iter().collect::<Vec<bool>>(), long)
2309     }
2310
2311     #[test]
2312     fn test_small_difference() {
2313         let mut b1 = Bitv::from_elem(3, false);
2314         let mut b2 = Bitv::from_elem(3, false);
2315         b1.set(0, true);
2316         b1.set(1, true);
2317         b2.set(1, true);
2318         b2.set(2, true);
2319         assert!(b1.difference(&b2));
2320         assert!(b1[0]);
2321         assert!(!b1[1]);
2322         assert!(!b1[2]);
2323     }
2324
2325     #[test]
2326     fn test_big_difference() {
2327         let mut b1 = Bitv::from_elem(100, false);
2328         let mut b2 = Bitv::from_elem(100, false);
2329         b1.set(0, true);
2330         b1.set(40, true);
2331         b2.set(40, true);
2332         b2.set(80, true);
2333         assert!(b1.difference(&b2));
2334         assert!(b1[0]);
2335         assert!(!b1[40]);
2336         assert!(!b1[80]);
2337     }
2338
2339     #[test]
2340     fn test_small_clear() {
2341         let mut b = Bitv::from_elem(14, true);
2342         assert!(!b.none() && b.all());
2343         b.clear();
2344         assert!(b.none() && !b.all());
2345     }
2346
2347     #[test]
2348     fn test_big_clear() {
2349         let mut b = Bitv::from_elem(140, true);
2350         assert!(!b.none() && b.all());
2351         b.clear();
2352         assert!(b.none() && !b.all());
2353     }
2354
2355     #[test]
2356     fn test_bitv_lt() {
2357         let mut a = Bitv::from_elem(5, false);
2358         let mut b = Bitv::from_elem(5, false);
2359
2360         assert!(!(a < b) && !(b < a));
2361         b.set(2, true);
2362         assert!(a < b);
2363         a.set(3, true);
2364         assert!(a < b);
2365         a.set(2, true);
2366         assert!(!(a < b) && b < a);
2367         b.set(0, true);
2368         assert!(a < b);
2369     }
2370
2371     #[test]
2372     fn test_ord() {
2373         let mut a = Bitv::from_elem(5, false);
2374         let mut b = Bitv::from_elem(5, false);
2375
2376         assert!(a <= b && a >= b);
2377         a.set(1, true);
2378         assert!(a > b && a >= b);
2379         assert!(b < a && b <= a);
2380         b.set(1, true);
2381         b.set(2, true);
2382         assert!(b > a && b >= a);
2383         assert!(a < b && a <= b);
2384     }
2385
2386
2387     #[test]
2388     fn test_small_bitv_tests() {
2389         let v = Bitv::from_bytes(&[0]);
2390         assert!(!v.all());
2391         assert!(!v.any());
2392         assert!(v.none());
2393
2394         let v = Bitv::from_bytes(&[0b00010100]);
2395         assert!(!v.all());
2396         assert!(v.any());
2397         assert!(!v.none());
2398
2399         let v = Bitv::from_bytes(&[0xFF]);
2400         assert!(v.all());
2401         assert!(v.any());
2402         assert!(!v.none());
2403     }
2404
2405     #[test]
2406     fn test_big_bitv_tests() {
2407         let v = Bitv::from_bytes(&[ // 88 bits
2408             0, 0, 0, 0,
2409             0, 0, 0, 0,
2410             0, 0, 0]);
2411         assert!(!v.all());
2412         assert!(!v.any());
2413         assert!(v.none());
2414
2415         let v = Bitv::from_bytes(&[ // 88 bits
2416             0, 0, 0b00010100, 0,
2417             0, 0, 0, 0b00110100,
2418             0, 0, 0]);
2419         assert!(!v.all());
2420         assert!(v.any());
2421         assert!(!v.none());
2422
2423         let v = Bitv::from_bytes(&[ // 88 bits
2424             0xFF, 0xFF, 0xFF, 0xFF,
2425             0xFF, 0xFF, 0xFF, 0xFF,
2426             0xFF, 0xFF, 0xFF]);
2427         assert!(v.all());
2428         assert!(v.any());
2429         assert!(!v.none());
2430     }
2431
2432     #[test]
2433     fn test_bitv_push_pop() {
2434         let mut s = Bitv::from_elem(5 * u32::BITS - 2, false);
2435         assert_eq!(s.len(), 5 * u32::BITS - 2);
2436         assert_eq!(s[5 * u32::BITS - 3], false);
2437         s.push(true);
2438         s.push(true);
2439         assert_eq!(s[5 * u32::BITS - 2], true);
2440         assert_eq!(s[5 * u32::BITS - 1], true);
2441         // Here the internal vector will need to be extended
2442         s.push(false);
2443         assert_eq!(s[5 * u32::BITS], false);
2444         s.push(false);
2445         assert_eq!(s[5 * u32::BITS + 1], false);
2446         assert_eq!(s.len(), 5 * u32::BITS + 2);
2447         // Pop it all off
2448         assert_eq!(s.pop(), Some(false));
2449         assert_eq!(s.pop(), Some(false));
2450         assert_eq!(s.pop(), Some(true));
2451         assert_eq!(s.pop(), Some(true));
2452         assert_eq!(s.len(), 5 * u32::BITS - 2);
2453     }
2454
2455     #[test]
2456     fn test_bitv_truncate() {
2457         let mut s = Bitv::from_elem(5 * u32::BITS, true);
2458
2459         assert_eq!(s, Bitv::from_elem(5 * u32::BITS, true));
2460         assert_eq!(s.len(), 5 * u32::BITS);
2461         s.truncate(4 * u32::BITS);
2462         assert_eq!(s, Bitv::from_elem(4 * u32::BITS, true));
2463         assert_eq!(s.len(), 4 * u32::BITS);
2464         // Truncating to a size > s.len() should be a noop
2465         s.truncate(5 * u32::BITS);
2466         assert_eq!(s, Bitv::from_elem(4 * u32::BITS, true));
2467         assert_eq!(s.len(), 4 * u32::BITS);
2468         s.truncate(3 * u32::BITS - 10);
2469         assert_eq!(s, Bitv::from_elem(3 * u32::BITS - 10, true));
2470         assert_eq!(s.len(), 3 * u32::BITS - 10);
2471         s.truncate(0);
2472         assert_eq!(s, Bitv::from_elem(0, true));
2473         assert_eq!(s.len(), 0);
2474     }
2475
2476     #[test]
2477     fn test_bitv_reserve() {
2478         let mut s = Bitv::from_elem(5 * u32::BITS, true);
2479         // Check capacity
2480         assert!(s.capacity() >= 5 * u32::BITS);
2481         s.reserve(2 * u32::BITS);
2482         assert!(s.capacity() >= 7 * u32::BITS);
2483         s.reserve(7 * u32::BITS);
2484         assert!(s.capacity() >= 12 * u32::BITS);
2485         s.reserve_exact(7 * u32::BITS);
2486         assert!(s.capacity() >= 12 * u32::BITS);
2487         s.reserve(7 * u32::BITS + 1);
2488         assert!(s.capacity() >= 12 * u32::BITS + 1);
2489         // Check that length hasn't changed
2490         assert_eq!(s.len(), 5 * u32::BITS);
2491         s.push(true);
2492         s.push(false);
2493         s.push(true);
2494         assert_eq!(s[5 * u32::BITS - 1], true);
2495         assert_eq!(s[5 * u32::BITS - 0], true);
2496         assert_eq!(s[5 * u32::BITS + 1], false);
2497         assert_eq!(s[5 * u32::BITS + 2], true);
2498     }
2499
2500     #[test]
2501     fn test_bitv_grow() {
2502         let mut bitv = Bitv::from_bytes(&[0b10110110, 0b00000000, 0b10101010]);
2503         bitv.grow(32, true);
2504         assert_eq!(bitv, Bitv::from_bytes(&[0b10110110, 0b00000000, 0b10101010,
2505                                      0xFF, 0xFF, 0xFF, 0xFF]));
2506         bitv.grow(64, false);
2507         assert_eq!(bitv, Bitv::from_bytes(&[0b10110110, 0b00000000, 0b10101010,
2508                                      0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0]));
2509         bitv.grow(16, true);
2510         assert_eq!(bitv, Bitv::from_bytes(&[0b10110110, 0b00000000, 0b10101010,
2511                                      0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]));
2512     }
2513
2514     #[test]
2515     fn test_bitv_extend() {
2516         let mut bitv = Bitv::from_bytes(&[0b10110110, 0b00000000, 0b11111111]);
2517         let ext = Bitv::from_bytes(&[0b01001001, 0b10010010, 0b10111101]);
2518         bitv.extend(ext.iter());
2519         assert_eq!(bitv, Bitv::from_bytes(&[0b10110110, 0b00000000, 0b11111111,
2520                                      0b01001001, 0b10010010, 0b10111101]));
2521     }
2522 }
2523
2524
2525
2526
2527 #[cfg(test)]
2528 mod bitv_bench {
2529     use std::prelude::v1::*;
2530     use std::rand;
2531     use std::rand::Rng;
2532     use std::u32;
2533     use test::{Bencher, black_box};
2534
2535     use super::Bitv;
2536
2537     static BENCH_BITS : usize = 1 << 14;
2538
2539     fn rng() -> rand::IsaacRng {
2540         let seed: &[_] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
2541         rand::SeedableRng::from_seed(seed)
2542     }
2543
2544     #[bench]
2545     fn bench_usize_small(b: &mut Bencher) {
2546         let mut r = rng();
2547         let mut bitv = 0 as usize;
2548         b.iter(|| {
2549             for _ in 0..100 {
2550                 bitv |= 1 << ((r.next_u32() as usize) % u32::BITS);
2551             }
2552             black_box(&bitv);
2553         });
2554     }
2555
2556     #[bench]
2557     fn bench_bitv_set_big_fixed(b: &mut Bencher) {
2558         let mut r = rng();
2559         let mut bitv = Bitv::from_elem(BENCH_BITS, false);
2560         b.iter(|| {
2561             for _ in 0..100 {
2562                 bitv.set((r.next_u32() as usize) % BENCH_BITS, true);
2563             }
2564             black_box(&bitv);
2565         });
2566     }
2567
2568     #[bench]
2569     fn bench_bitv_set_big_variable(b: &mut Bencher) {
2570         let mut r = rng();
2571         let mut bitv = Bitv::from_elem(BENCH_BITS, false);
2572         b.iter(|| {
2573             for _ in 0..100 {
2574                 bitv.set((r.next_u32() as usize) % BENCH_BITS, r.gen());
2575             }
2576             black_box(&bitv);
2577         });
2578     }
2579
2580     #[bench]
2581     fn bench_bitv_set_small(b: &mut Bencher) {
2582         let mut r = rng();
2583         let mut bitv = Bitv::from_elem(u32::BITS, false);
2584         b.iter(|| {
2585             for _ in 0..100 {
2586                 bitv.set((r.next_u32() as usize) % u32::BITS, true);
2587             }
2588             black_box(&bitv);
2589         });
2590     }
2591
2592     #[bench]
2593     fn bench_bitv_big_union(b: &mut Bencher) {
2594         let mut b1 = Bitv::from_elem(BENCH_BITS, false);
2595         let b2 = Bitv::from_elem(BENCH_BITS, false);
2596         b.iter(|| {
2597             b1.union(&b2)
2598         })
2599     }
2600
2601     #[bench]
2602     fn bench_bitv_small_iter(b: &mut Bencher) {
2603         let bitv = Bitv::from_elem(u32::BITS, false);
2604         b.iter(|| {
2605             let mut sum = 0;
2606             for _ in 0..10 {
2607                 for pres in &bitv {
2608                     sum += pres as usize;
2609                 }
2610             }
2611             sum
2612         })
2613     }
2614
2615     #[bench]
2616     fn bench_bitv_big_iter(b: &mut Bencher) {
2617         let bitv = Bitv::from_elem(BENCH_BITS, false);
2618         b.iter(|| {
2619             let mut sum = 0;
2620             for pres in &bitv {
2621                 sum += pres as usize;
2622             }
2623             sum
2624         })
2625     }
2626 }
2627
2628
2629
2630
2631
2632
2633
2634 #[cfg(test)]
2635 mod bitv_set_test {
2636     use prelude::*;
2637     use std::iter::range_step;
2638
2639     use super::{Bitv, BitvSet};
2640
2641     #[test]
2642     fn test_bitv_set_show() {
2643         let mut s = BitvSet::new();
2644         s.insert(1);
2645         s.insert(10);
2646         s.insert(50);
2647         s.insert(2);
2648         assert_eq!("BitvSet {1, 2, 10, 50}", format!("{:?}", s));
2649     }
2650
2651     #[test]
2652     fn test_bitv_set_from_usizes() {
2653         let usizes = vec![0, 2, 2, 3];
2654         let a: BitvSet = usizes.into_iter().collect();
2655         let mut b = BitvSet::new();
2656         b.insert(0);
2657         b.insert(2);
2658         b.insert(3);
2659         assert_eq!(a, b);
2660     }
2661
2662     #[test]
2663     fn test_bitv_set_iterator() {
2664         let usizes = vec![0, 2, 2, 3];
2665         let bitv: BitvSet = usizes.into_iter().collect();
2666
2667         let idxs: Vec<_> = bitv.iter().collect();
2668         assert_eq!(idxs, vec![0, 2, 3]);
2669
2670         let long: BitvSet = (0..10000).filter(|&n| n % 2 == 0).collect();
2671         let real: Vec<_> = range_step(0, 10000, 2).collect();
2672
2673         let idxs: Vec<_> = long.iter().collect();
2674         assert_eq!(idxs, real);
2675     }
2676
2677     #[test]
2678     fn test_bitv_set_frombitv_init() {
2679         let bools = [true, false];
2680         let lengths = [10, 64, 100];
2681         for &b in &bools {
2682             for &l in &lengths {
2683                 let bitset = BitvSet::from_bitv(Bitv::from_elem(l, b));
2684                 assert_eq!(bitset.contains(&1), b);
2685                 assert_eq!(bitset.contains(&(l-1)), b);
2686                 assert!(!bitset.contains(&l));
2687             }
2688         }
2689     }
2690
2691     #[test]
2692     fn test_bitv_masking() {
2693         let b = Bitv::from_elem(140, true);
2694         let mut bs = BitvSet::from_bitv(b);
2695         assert!(bs.contains(&139));
2696         assert!(!bs.contains(&140));
2697         assert!(bs.insert(150));
2698         assert!(!bs.contains(&140));
2699         assert!(!bs.contains(&149));
2700         assert!(bs.contains(&150));
2701         assert!(!bs.contains(&151));
2702     }
2703
2704     #[test]
2705     fn test_bitv_set_basic() {
2706         let mut b = BitvSet::new();
2707         assert!(b.insert(3));
2708         assert!(!b.insert(3));
2709         assert!(b.contains(&3));
2710         assert!(b.insert(4));
2711         assert!(!b.insert(4));
2712         assert!(b.contains(&3));
2713         assert!(b.insert(400));
2714         assert!(!b.insert(400));
2715         assert!(b.contains(&400));
2716         assert_eq!(b.len(), 3);
2717     }
2718
2719     #[test]
2720     fn test_bitv_set_intersection() {
2721         let mut a = BitvSet::new();
2722         let mut b = BitvSet::new();
2723
2724         assert!(a.insert(11));
2725         assert!(a.insert(1));
2726         assert!(a.insert(3));
2727         assert!(a.insert(77));
2728         assert!(a.insert(103));
2729         assert!(a.insert(5));
2730
2731         assert!(b.insert(2));
2732         assert!(b.insert(11));
2733         assert!(b.insert(77));
2734         assert!(b.insert(5));
2735         assert!(b.insert(3));
2736
2737         let expected = [3, 5, 11, 77];
2738         let actual: Vec<_> = a.intersection(&b).collect();
2739         assert_eq!(actual, expected);
2740     }
2741
2742     #[test]
2743     fn test_bitv_set_difference() {
2744         let mut a = BitvSet::new();
2745         let mut b = BitvSet::new();
2746
2747         assert!(a.insert(1));
2748         assert!(a.insert(3));
2749         assert!(a.insert(5));
2750         assert!(a.insert(200));
2751         assert!(a.insert(500));
2752
2753         assert!(b.insert(3));
2754         assert!(b.insert(200));
2755
2756         let expected = [1, 5, 500];
2757         let actual: Vec<_> = a.difference(&b).collect();
2758         assert_eq!(actual, expected);
2759     }
2760
2761     #[test]
2762     fn test_bitv_set_symmetric_difference() {
2763         let mut a = BitvSet::new();
2764         let mut b = BitvSet::new();
2765
2766         assert!(a.insert(1));
2767         assert!(a.insert(3));
2768         assert!(a.insert(5));
2769         assert!(a.insert(9));
2770         assert!(a.insert(11));
2771
2772         assert!(b.insert(3));
2773         assert!(b.insert(9));
2774         assert!(b.insert(14));
2775         assert!(b.insert(220));
2776
2777         let expected = [1, 5, 11, 14, 220];
2778         let actual: Vec<_> = a.symmetric_difference(&b).collect();
2779         assert_eq!(actual, expected);
2780     }
2781
2782     #[test]
2783     fn test_bitv_set_union() {
2784         let mut a = BitvSet::new();
2785         let mut b = BitvSet::new();
2786         assert!(a.insert(1));
2787         assert!(a.insert(3));
2788         assert!(a.insert(5));
2789         assert!(a.insert(9));
2790         assert!(a.insert(11));
2791         assert!(a.insert(160));
2792         assert!(a.insert(19));
2793         assert!(a.insert(24));
2794         assert!(a.insert(200));
2795
2796         assert!(b.insert(1));
2797         assert!(b.insert(5));
2798         assert!(b.insert(9));
2799         assert!(b.insert(13));
2800         assert!(b.insert(19));
2801
2802         let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160, 200];
2803         let actual: Vec<_> = a.union(&b).collect();
2804         assert_eq!(actual, expected);
2805     }
2806
2807     #[test]
2808     fn test_bitv_set_subset() {
2809         let mut set1 = BitvSet::new();
2810         let mut set2 = BitvSet::new();
2811
2812         assert!(set1.is_subset(&set2)); //  {}  {}
2813         set2.insert(100);
2814         assert!(set1.is_subset(&set2)); //  {}  { 1 }
2815         set2.insert(200);
2816         assert!(set1.is_subset(&set2)); //  {}  { 1, 2 }
2817         set1.insert(200);
2818         assert!(set1.is_subset(&set2)); //  { 2 }  { 1, 2 }
2819         set1.insert(300);
2820         assert!(!set1.is_subset(&set2)); // { 2, 3 }  { 1, 2 }
2821         set2.insert(300);
2822         assert!(set1.is_subset(&set2)); // { 2, 3 }  { 1, 2, 3 }
2823         set2.insert(400);
2824         assert!(set1.is_subset(&set2)); // { 2, 3 }  { 1, 2, 3, 4 }
2825         set2.remove(&100);
2826         assert!(set1.is_subset(&set2)); // { 2, 3 }  { 2, 3, 4 }
2827         set2.remove(&300);
2828         assert!(!set1.is_subset(&set2)); // { 2, 3 }  { 2, 4 }
2829         set1.remove(&300);
2830         assert!(set1.is_subset(&set2)); // { 2 }  { 2, 4 }
2831     }
2832
2833     #[test]
2834     fn test_bitv_set_is_disjoint() {
2835         let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2836         let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01000000]));
2837         let c = BitvSet::new();
2838         let d = BitvSet::from_bitv(Bitv::from_bytes(&[0b00110000]));
2839
2840         assert!(!a.is_disjoint(&d));
2841         assert!(!d.is_disjoint(&a));
2842
2843         assert!(a.is_disjoint(&b));
2844         assert!(a.is_disjoint(&c));
2845         assert!(b.is_disjoint(&a));
2846         assert!(b.is_disjoint(&c));
2847         assert!(c.is_disjoint(&a));
2848         assert!(c.is_disjoint(&b));
2849     }
2850
2851     #[test]
2852     fn test_bitv_set_union_with() {
2853         //a should grow to include larger elements
2854         let mut a = BitvSet::new();
2855         a.insert(0);
2856         let mut b = BitvSet::new();
2857         b.insert(5);
2858         let expected = BitvSet::from_bitv(Bitv::from_bytes(&[0b10000100]));
2859         a.union_with(&b);
2860         assert_eq!(a, expected);
2861
2862         // Standard
2863         let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2864         let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01100010]));
2865         let c = a.clone();
2866         a.union_with(&b);
2867         b.union_with(&c);
2868         assert_eq!(a.len(), 4);
2869         assert_eq!(b.len(), 4);
2870     }
2871
2872     #[test]
2873     fn test_bitv_set_intersect_with() {
2874         // Explicitly 0'ed bits
2875         let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2876         let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
2877         let c = a.clone();
2878         a.intersect_with(&b);
2879         b.intersect_with(&c);
2880         assert!(a.is_empty());
2881         assert!(b.is_empty());
2882
2883         // Uninitialized bits should behave like 0's
2884         let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2885         let mut b = BitvSet::new();
2886         let c = a.clone();
2887         a.intersect_with(&b);
2888         b.intersect_with(&c);
2889         assert!(a.is_empty());
2890         assert!(b.is_empty());
2891
2892         // Standard
2893         let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2894         let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01100010]));
2895         let c = a.clone();
2896         a.intersect_with(&b);
2897         b.intersect_with(&c);
2898         assert_eq!(a.len(), 2);
2899         assert_eq!(b.len(), 2);
2900     }
2901
2902     #[test]
2903     fn test_bitv_set_difference_with() {
2904         // Explicitly 0'ed bits
2905         let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
2906         let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2907         a.difference_with(&b);
2908         assert!(a.is_empty());
2909
2910         // Uninitialized bits should behave like 0's
2911         let mut a = BitvSet::new();
2912         let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b11111111]));
2913         a.difference_with(&b);
2914         assert!(a.is_empty());
2915
2916         // Standard
2917         let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2918         let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01100010]));
2919         let c = a.clone();
2920         a.difference_with(&b);
2921         b.difference_with(&c);
2922         assert_eq!(a.len(), 1);
2923         assert_eq!(b.len(), 1);
2924     }
2925
2926     #[test]
2927     fn test_bitv_set_symmetric_difference_with() {
2928         //a should grow to include larger elements
2929         let mut a = BitvSet::new();
2930         a.insert(0);
2931         a.insert(1);
2932         let mut b = BitvSet::new();
2933         b.insert(1);
2934         b.insert(5);
2935         let expected = BitvSet::from_bitv(Bitv::from_bytes(&[0b10000100]));
2936         a.symmetric_difference_with(&b);
2937         assert_eq!(a, expected);
2938
2939         let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2940         let b = BitvSet::new();
2941         let c = a.clone();
2942         a.symmetric_difference_with(&b);
2943         assert_eq!(a, c);
2944
2945         // Standard
2946         let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b11100010]));
2947         let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101010]));
2948         let c = a.clone();
2949         a.symmetric_difference_with(&b);
2950         b.symmetric_difference_with(&c);
2951         assert_eq!(a.len(), 2);
2952         assert_eq!(b.len(), 2);
2953     }
2954
2955     #[test]
2956     fn test_bitv_set_eq() {
2957         let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2958         let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
2959         let c = BitvSet::new();
2960
2961         assert!(a == a);
2962         assert!(a != b);
2963         assert!(a != c);
2964         assert!(b == b);
2965         assert!(b == c);
2966         assert!(c == c);
2967     }
2968
2969     #[test]
2970     fn test_bitv_set_cmp() {
2971         let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2972         let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
2973         let c = BitvSet::new();
2974
2975         assert_eq!(a.cmp(&b), Greater);
2976         assert_eq!(a.cmp(&c), Greater);
2977         assert_eq!(b.cmp(&a), Less);
2978         assert_eq!(b.cmp(&c), Equal);
2979         assert_eq!(c.cmp(&a), Less);
2980         assert_eq!(c.cmp(&b), Equal);
2981     }
2982
2983     #[test]
2984     fn test_bitv_remove() {
2985         let mut a = BitvSet::new();
2986
2987         assert!(a.insert(1));
2988         assert!(a.remove(&1));
2989
2990         assert!(a.insert(100));
2991         assert!(a.remove(&100));
2992
2993         assert!(a.insert(1000));
2994         assert!(a.remove(&1000));
2995         a.shrink_to_fit();
2996     }
2997
2998     #[test]
2999     fn test_bitv_clone() {
3000         let mut a = BitvSet::new();
3001
3002         assert!(a.insert(1));
3003         assert!(a.insert(100));
3004         assert!(a.insert(1000));
3005
3006         let mut b = a.clone();
3007
3008         assert!(a == b);
3009
3010         assert!(b.remove(&1));
3011         assert!(a.contains(&1));
3012
3013         assert!(a.remove(&1000));
3014         assert!(b.contains(&1000));
3015     }
3016 }
3017
3018
3019
3020
3021
3022 #[cfg(test)]
3023 mod bitv_set_bench {
3024     use std::prelude::v1::*;
3025     use std::rand;
3026     use std::rand::Rng;
3027     use std::u32;
3028     use test::{Bencher, black_box};
3029
3030     use super::{Bitv, BitvSet};
3031
3032     static BENCH_BITS : usize = 1 << 14;
3033
3034     fn rng() -> rand::IsaacRng {
3035         let seed: &[_] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
3036         rand::SeedableRng::from_seed(seed)
3037     }
3038
3039     #[bench]
3040     fn bench_bitvset_small(b: &mut Bencher) {
3041         let mut r = rng();
3042         let mut bitv = BitvSet::new();
3043         b.iter(|| {
3044             for _ in 0..100 {
3045                 bitv.insert((r.next_u32() as usize) % u32::BITS);
3046             }
3047             black_box(&bitv);
3048         });
3049     }
3050
3051     #[bench]
3052     fn bench_bitvset_big(b: &mut Bencher) {
3053         let mut r = rng();
3054         let mut bitv = BitvSet::new();
3055         b.iter(|| {
3056             for _ in 0..100 {
3057                 bitv.insert((r.next_u32() as usize) % BENCH_BITS);
3058             }
3059             black_box(&bitv);
3060         });
3061     }
3062
3063     #[bench]
3064     fn bench_bitvset_iter(b: &mut Bencher) {
3065         let bitv = BitvSet::from_bitv(Bitv::from_fn(BENCH_BITS,
3066                                               |idx| {idx % 3 == 0}));
3067         b.iter(|| {
3068             let mut sum = 0;
3069             for idx in &bitv {
3070                 sum += idx as usize;
3071             }
3072             sum
3073         })
3074     }
3075 }