]> git.lizzy.rs Git - rust.git/blob - src/libcollections/bitv.rs
librustc: Don't try to perform the magical
[rust.git] / src / libcollections / bitv.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 #![allow(missing_doc)]
12
13 use core::prelude::*;
14
15 use core::cmp;
16 use core::default::Default;
17 use core::fmt;
18 use core::iter::{Enumerate, Repeat, Map, Zip};
19 use core::ops;
20 use core::slice;
21 use core::uint;
22 use std::hash;
23
24 use {Collection, Mutable, Set, MutableSet};
25 use vec::Vec;
26
27 #[deriving(Clone)]
28 struct SmallBitv {
29     /// only the lowest nbits of this value are used. the rest is undefined.
30     bits: uint
31 }
32
33 /// a mask that has a 1 for each defined bit in a small_bitv, assuming n bits
34 #[inline]
35 fn small_mask(nbits: uint) -> uint {
36     (1 << nbits) - 1
37 }
38
39 impl SmallBitv {
40     fn new(bits: uint) -> SmallBitv {
41         SmallBitv {bits: bits}
42     }
43
44     #[inline]
45     fn bits_op(&mut self,
46                    right_bits: uint,
47                    nbits: uint,
48                    f: |uint, uint| -> uint)
49                    -> bool {
50         let mask = small_mask(nbits);
51         let old_b: uint = self.bits;
52         let new_b = f(old_b, right_bits);
53         self.bits = new_b;
54         mask & old_b != mask & new_b
55     }
56
57     #[inline]
58     fn union(&mut self, s: &SmallBitv, nbits: uint) -> bool {
59         self.bits_op(s.bits, nbits, |u1, u2| u1 | u2)
60     }
61
62     #[inline]
63     fn intersect(&mut self, s: &SmallBitv, nbits: uint) -> bool {
64         self.bits_op(s.bits, nbits, |u1, u2| u1 & u2)
65     }
66
67     #[inline]
68     fn become(&mut self, s: &SmallBitv, nbits: uint) -> bool {
69         self.bits_op(s.bits, nbits, |_u1, u2| u2)
70     }
71
72     #[inline]
73     fn difference(&mut self, s: &SmallBitv, nbits: uint) -> bool {
74         self.bits_op(s.bits, nbits, |u1, u2| u1 & !u2)
75     }
76
77     #[inline]
78     fn get(&self, i: uint) -> bool {
79         (self.bits & (1 << i)) != 0
80     }
81
82     #[inline]
83     fn set(&mut self, i: uint, x: bool) {
84         if x {
85             self.bits |= 1<<i;
86         }
87         else {
88             self.bits &= !(1<<i);
89         }
90     }
91
92     #[inline]
93     fn equals(&self, b: &SmallBitv, nbits: uint) -> bool {
94         let mask = small_mask(nbits);
95         mask & self.bits == mask & b.bits
96     }
97
98     #[inline]
99     fn clear(&mut self) { self.bits = 0; }
100
101     #[inline]
102     fn set_all(&mut self) { self.bits = !0; }
103
104     #[inline]
105     fn all(&self, nbits: uint) -> bool {
106         small_mask(nbits) & !self.bits == 0
107     }
108
109     #[inline]
110     fn none(&self, nbits: uint) -> bool {
111         small_mask(nbits) & self.bits == 0
112     }
113
114     #[inline]
115     fn negate(&mut self) { self.bits = !self.bits; }
116 }
117
118 #[deriving(Clone)]
119 struct BigBitv {
120     storage: Vec<uint>
121 }
122
123 /**
124  * A mask that has a 1 for each defined bit in the n'th element of a `BigBitv`,
125  * assuming n bits.
126  */
127 #[inline]
128 fn big_mask(nbits: uint, elem: uint) -> uint {
129     let rmd = nbits % uint::BITS;
130     let nelems = nbits/uint::BITS + if rmd == 0 {0} else {1};
131
132     if elem < nelems - 1 || rmd == 0 {
133         !0
134     } else {
135         (1 << rmd) - 1
136     }
137 }
138
139 impl BigBitv {
140     fn new(storage: Vec<uint>) -> BigBitv {
141         BigBitv {storage: storage}
142     }
143
144     #[inline]
145     fn process(&mut self,
146                    b: &BigBitv,
147                    nbits: uint,
148                    op: |uint, uint| -> uint)
149                    -> bool {
150         let len = b.storage.len();
151         assert_eq!(self.storage.len(), len);
152         let mut changed = false;
153         for (i, (a, b)) in self.storage.mut_iter()
154                                .zip(b.storage.iter())
155                                .enumerate() {
156             let mask = big_mask(nbits, i);
157             let w0 = *a & mask;
158             let w1 = *b & mask;
159             let w = op(w0, w1) & mask;
160             if w0 != w {
161                 changed = true;
162                 *a = w;
163             }
164         }
165         changed
166     }
167
168     #[inline]
169     fn each_storage(&mut self, op: |v: &mut uint| -> bool) -> bool {
170         self.storage.mut_iter().advance(|elt| op(elt))
171     }
172
173     #[inline]
174     fn negate(&mut self) {
175         self.each_storage(|w| { *w = !*w; true });
176     }
177
178     #[inline]
179     fn union(&mut self, b: &BigBitv, nbits: uint) -> bool {
180         self.process(b, nbits, |w1, w2| w1 | w2)
181     }
182
183     #[inline]
184     fn intersect(&mut self, b: &BigBitv, nbits: uint) -> bool {
185         self.process(b, nbits, |w1, w2| w1 & w2)
186     }
187
188     #[inline]
189     fn become(&mut self, b: &BigBitv, nbits: uint) -> bool {
190         self.process(b, nbits, |_, w| w)
191     }
192
193     #[inline]
194     fn difference(&mut self, b: &BigBitv, nbits: uint) -> bool {
195         self.process(b, nbits, |w1, w2| w1 & !w2)
196     }
197
198     #[inline]
199     fn get(&self, i: uint) -> bool {
200         let w = i / uint::BITS;
201         let b = i % uint::BITS;
202         let x = 1 & self.storage.get(w) >> b;
203         x == 1
204     }
205
206     #[inline]
207     fn set(&mut self, i: uint, x: bool) {
208         let w = i / uint::BITS;
209         let b = i % uint::BITS;
210         let flag = 1 << b;
211         *self.storage.get_mut(w) = if x { *self.storage.get(w) | flag }
212                           else { *self.storage.get(w) & !flag };
213     }
214
215     #[inline]
216     fn equals(&self, b: &BigBitv, nbits: uint) -> bool {
217         for (i, elt) in b.storage.iter().enumerate() {
218             let mask = big_mask(nbits, i);
219             if mask & *self.storage.get(i) != mask & *elt {
220                 return false;
221             }
222         }
223         true
224     }
225 }
226
227 #[deriving(Clone)]
228 enum BitvVariant { Big(BigBitv), Small(SmallBitv) }
229
230 enum Op {Union, Intersect, Assign, Difference}
231
232 /// The bitvector type
233 ///
234 /// # Example
235 ///
236 /// ```rust
237 /// use collections::bitv::Bitv;
238 ///
239 /// let mut bv = Bitv::new(10, false);
240 ///
241 /// // insert all primes less than 10
242 /// bv.set(2, true);
243 /// bv.set(3, true);
244 /// bv.set(5, true);
245 /// bv.set(7, true);
246 /// println!("{}", bv.to_str());
247 /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
248 ///
249 /// // flip all values in bitvector, producing non-primes less than 10
250 /// bv.negate();
251 /// println!("{}", bv.to_str());
252 /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
253 ///
254 /// // reset bitvector to empty
255 /// bv.clear();
256 /// println!("{}", bv.to_str());
257 /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
258 /// ```
259 #[deriving(Clone)]
260 pub struct Bitv {
261     /// Internal representation of the bit vector (small or large)
262     rep: BitvVariant,
263     /// The number of valid bits in the internal representation
264     nbits: uint
265 }
266
267 fn die() -> ! {
268     fail!("Tried to do operation on bit vectors with different sizes");
269 }
270
271 impl Bitv {
272     #[inline]
273     fn do_op(&mut self, op: Op, other: &Bitv) -> bool {
274         if self.nbits != other.nbits {
275             die();
276         }
277         match self.rep {
278           Small(ref mut s) => match other.rep {
279             Small(ref s1) => match op {
280               Union      => s.union(s1,      self.nbits),
281               Intersect  => s.intersect(s1,  self.nbits),
282               Assign     => s.become(s1,     self.nbits),
283               Difference => s.difference(s1, self.nbits)
284             },
285             Big(_) => die()
286           },
287           Big(ref mut s) => match other.rep {
288             Small(_) => die(),
289             Big(ref s1) => match op {
290               Union      => s.union(s1,      self.nbits),
291               Intersect  => s.intersect(s1,  self.nbits),
292               Assign     => s.become(s1,     self.nbits),
293               Difference => s.difference(s1, self.nbits)
294             }
295           }
296         }
297     }
298 }
299
300 impl Bitv {
301     /// Creates an empty Bitv that holds `nbits` elements, setting each element
302     /// to `init`.
303     pub fn new(nbits: uint, init: bool) -> Bitv {
304         let rep = if nbits < uint::BITS {
305             Small(SmallBitv::new(if init {(1<<nbits)-1} else {0}))
306         } else if nbits == uint::BITS {
307             Small(SmallBitv::new(if init {!0} else {0}))
308         } else {
309             let exact = nbits % uint::BITS == 0;
310             let nelems = nbits/uint::BITS + if exact {0} else {1};
311             let s =
312                 if init {
313                     if exact {
314                         Vec::from_elem(nelems, !0u)
315                     } else {
316                         let mut v = Vec::from_elem(nelems-1, !0u);
317                         v.push((1<<nbits % uint::BITS)-1);
318                         v
319                     }
320                 } else { Vec::from_elem(nelems, 0u)};
321             Big(BigBitv::new(s))
322         };
323         Bitv {rep: rep, nbits: nbits}
324     }
325
326     /**
327      * Calculates the union of two bitvectors
328      *
329      * Sets `self` to the union of `self` and `v1`. Both bitvectors must be
330      * the same length. Returns `true` if `self` changed.
331     */
332     #[inline]
333     pub fn union(&mut self, v1: &Bitv) -> bool { self.do_op(Union, v1) }
334
335     /**
336      * Calculates the intersection of two bitvectors
337      *
338      * Sets `self` to the intersection of `self` and `v1`. Both bitvectors
339      * must be the same length. Returns `true` if `self` changed.
340     */
341     #[inline]
342     pub fn intersect(&mut self, v1: &Bitv) -> bool {
343         self.do_op(Intersect, v1)
344     }
345
346     /**
347      * Assigns the value of `v1` to `self`
348      *
349      * Both bitvectors must be the same length. Returns `true` if `self` was
350      * changed
351      */
352     #[inline]
353     pub fn assign(&mut self, v: &Bitv) -> bool { self.do_op(Assign, v) }
354
355     /// Retrieve the value at index `i`
356     #[inline]
357     pub fn get(&self, i: uint) -> bool {
358         assert!((i < self.nbits));
359         match self.rep {
360             Big(ref b)   => b.get(i),
361             Small(ref s) => s.get(i)
362         }
363     }
364
365     /**
366      * Set the value of a bit at a given index
367      *
368      * `i` must be less than the length of the bitvector.
369      */
370     #[inline]
371     pub fn set(&mut self, i: uint, x: bool) {
372       assert!((i < self.nbits));
373       match self.rep {
374         Big(ref mut b)   => b.set(i, x),
375         Small(ref mut s) => s.set(i, x)
376       }
377     }
378
379     /// Set all bits to 0
380     #[inline]
381     pub fn clear(&mut self) {
382         match self.rep {
383             Small(ref mut b) => b.clear(),
384             Big(ref mut s) => {
385                 s.each_storage(|w| { *w = 0u; true });
386             }
387         }
388     }
389
390     /// Set all bits to 1
391     #[inline]
392     pub fn set_all(&mut self) {
393         match self.rep {
394             Small(ref mut b) => b.set_all(),
395             Big(ref mut s) => {
396                 s.each_storage(|w| { *w = !0u; true });
397             }
398         }
399     }
400
401     /// Flip all bits
402     #[inline]
403     pub fn negate(&mut self) {
404         match self.rep {
405             Small(ref mut s) => s.negate(),
406             Big(ref mut b) => b.negate(),
407         }
408     }
409
410     /**
411      * Calculate the difference between two bitvectors
412      *
413      * Sets each element of `v0` to the value of that element minus the
414      * element of `v1` at the same index. Both bitvectors must be the same
415      * length.
416      *
417      * Returns `true` if `v0` was changed.
418      */
419     #[inline]
420     pub fn difference(&mut self, v: &Bitv) -> bool {
421         self.do_op(Difference, v)
422     }
423
424     /// Returns `true` if all bits are 1
425     #[inline]
426     pub fn all(&self) -> bool {
427       match self.rep {
428         Small(ref b) => b.all(self.nbits),
429         _ => self.iter().all(|x| x)
430       }
431     }
432
433     /// Returns an iterator over the elements of the vector in order.
434     ///
435     /// # Example
436     ///
437     /// ```rust
438     /// use collections::bitv::Bitv;
439     /// let mut bv = Bitv::new(10, false);
440     /// bv.set(1, true);
441     /// bv.set(2, true);
442     /// bv.set(3, true);
443     /// bv.set(5, true);
444     /// bv.set(8, true);
445     /// // Count bits set to 1; result should be 5
446     /// println!("{}", bv.iter().filter(|x| *x).count());
447     /// ```
448     #[inline]
449     pub fn iter<'a>(&'a self) -> Bits<'a> {
450         Bits {bitv: self, next_idx: 0, end_idx: self.nbits}
451     }
452
453     /// Returns `true` if all bits are 0
454     pub fn none(&self) -> bool {
455       match self.rep {
456         Small(ref b) => b.none(self.nbits),
457         _ => self.iter().all(|x| !x)
458       }
459     }
460
461     #[inline]
462     /// Returns `true` if any bit is 1
463     pub fn any(&self) -> bool {
464         !self.none()
465     }
466
467     /**
468      * Converts `self` to a vector of `uint` with the same length.
469      *
470      * Each `uint` in the resulting vector has either value `0u` or `1u`.
471      */
472     pub fn to_vec(&self) -> Vec<uint> {
473         Vec::from_fn(self.nbits, |i| if self.get(i) { 1 } else { 0 })
474     }
475
476     /**
477      * Organise the bits into bytes, such that the first bit in the
478      * `Bitv` becomes the high-order bit of the first byte. If the
479      * size of the `Bitv` is not a multiple of 8 then trailing bits
480      * will be filled-in with false/0
481      */
482     pub fn to_bytes(&self) -> Vec<u8> {
483         fn bit (bitv: &Bitv, byte: uint, bit: uint) -> u8 {
484             let offset = byte * 8 + bit;
485             if offset >= bitv.nbits {
486                 0
487             } else {
488                 bitv[offset] as u8 << (7 - bit)
489             }
490         }
491
492         let len = self.nbits/8 +
493                   if self.nbits % 8 == 0 { 0 } else { 1 };
494         Vec::from_fn(len, |i|
495             bit(self, i, 0) |
496             bit(self, i, 1) |
497             bit(self, i, 2) |
498             bit(self, i, 3) |
499             bit(self, i, 4) |
500             bit(self, i, 5) |
501             bit(self, i, 6) |
502             bit(self, i, 7)
503         )
504     }
505
506     /**
507      * Transform `self` into a `Vec<bool>` by turning each bit into a `bool`.
508      */
509     pub fn to_bools(&self) -> Vec<bool> {
510         Vec::from_fn(self.nbits, |i| self[i])
511     }
512
513     /**
514      * Compare a bitvector to a vector of `bool`.
515      *
516      * Both the bitvector and vector must have the same length.
517      */
518     pub fn eq_vec(&self, v: &[bool]) -> bool {
519         assert_eq!(self.nbits, v.len());
520         let mut i = 0;
521         while i < self.nbits {
522             if self.get(i) != v[i] { return false; }
523             i = i + 1;
524         }
525         true
526     }
527
528     pub fn ones(&self, f: |uint| -> bool) -> bool {
529         range(0u, self.nbits).advance(|i| !self.get(i) || f(i))
530     }
531
532 }
533
534 /**
535  * Transform a byte-vector into a `Bitv`. Each byte becomes 8 bits,
536  * with the most significant bits of each byte coming first. Each
537  * bit becomes `true` if equal to 1 or `false` if equal to 0.
538  */
539 pub fn from_bytes(bytes: &[u8]) -> Bitv {
540     from_fn(bytes.len() * 8, |i| {
541         let b = bytes[i / 8] as uint;
542         let offset = i % 8;
543         b >> (7 - offset) & 1 == 1
544     })
545 }
546
547 /**
548  * Transform a `[bool]` into a `Bitv` by converting each `bool` into a bit.
549  */
550 pub fn from_bools(bools: &[bool]) -> Bitv {
551     from_fn(bools.len(), |i| bools[i])
552 }
553
554 /**
555  * Create a `Bitv` of the specified length where the value at each
556  * index is `f(index)`.
557  */
558 pub fn from_fn(len: uint, f: |index: uint| -> bool) -> Bitv {
559     let mut bitv = Bitv::new(len, false);
560     for i in range(0u, len) {
561         bitv.set(i, f(i));
562     }
563     bitv
564 }
565
566 impl ops::Index<uint,bool> for Bitv {
567     fn index(&self, i: &uint) -> bool {
568         self.get(*i)
569     }
570 }
571
572 impl fmt::Show for Bitv {
573     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
574         for bit in self.iter() {
575             try!(write!(fmt, "{}", if bit { 1u } else { 0u }));
576         }
577         Ok(())
578     }
579 }
580
581 impl<S: hash::Writer> hash::Hash<S> for Bitv {
582     fn hash(&self, state: &mut S) {
583         self.nbits.hash(state);
584         match self.rep {
585             Small(ref s) => (s.bits & small_mask(self.nbits)).hash(state),
586             Big(ref b) => {
587                 for (i, ele) in b.storage.iter().enumerate() {
588                     (ele & big_mask(self.nbits, i)).hash(state);
589                 }
590             }
591         }
592     }
593 }
594
595 impl cmp::PartialEq for Bitv {
596     #[inline]
597     fn eq(&self, other: &Bitv) -> bool {
598         if self.nbits != other.nbits { return false; }
599         match self.rep {
600             Small(ref b) => match other.rep {
601                 Small(ref b1) => b.equals(b1, self.nbits),
602                 _ => false
603             },
604             Big(ref s) => match other.rep {
605                 Big(ref s1) => s.equals(s1, self.nbits),
606                 Small(_) => return false
607             }
608         }
609     }
610 }
611
612 impl cmp::Eq for Bitv {}
613
614 #[inline]
615 fn iterate_bits(base: uint, bits: uint, f: |uint| -> bool) -> bool {
616     if bits == 0 {
617         return true;
618     }
619     for i in range(0u, uint::BITS) {
620         if bits & (1 << i) != 0 {
621             if !f(base + i) {
622                 return false;
623             }
624         }
625     }
626     return true;
627 }
628
629 /// An iterator for `Bitv`.
630 pub struct Bits<'a> {
631     bitv: &'a Bitv,
632     next_idx: uint,
633     end_idx: uint,
634 }
635
636 impl<'a> Iterator<bool> for Bits<'a> {
637     #[inline]
638     fn next(&mut self) -> Option<bool> {
639         if self.next_idx != self.end_idx {
640             let idx = self.next_idx;
641             self.next_idx += 1;
642             Some(self.bitv.get(idx))
643         } else {
644             None
645         }
646     }
647
648     fn size_hint(&self) -> (uint, Option<uint>) {
649         let rem = self.end_idx - self.next_idx;
650         (rem, Some(rem))
651     }
652 }
653
654 impl<'a> DoubleEndedIterator<bool> for Bits<'a> {
655     #[inline]
656     fn next_back(&mut self) -> Option<bool> {
657         if self.next_idx != self.end_idx {
658             self.end_idx -= 1;
659             Some(self.bitv.get(self.end_idx))
660         } else {
661             None
662         }
663     }
664 }
665
666 impl<'a> ExactSize<bool> for Bits<'a> {}
667
668 impl<'a> RandomAccessIterator<bool> for Bits<'a> {
669     #[inline]
670     fn indexable(&self) -> uint {
671         self.end_idx - self.next_idx
672     }
673
674     #[inline]
675     fn idx(&mut self, index: uint) -> Option<bool> {
676         if index >= self.indexable() {
677             None
678         } else {
679             Some(self.bitv.get(index))
680         }
681     }
682 }
683
684 /// An implementation of a set using a bit vector as an underlying
685 /// representation for holding numerical elements.
686 ///
687 /// It should also be noted that the amount of storage necessary for holding a
688 /// set of objects is proportional to the maximum of the objects when viewed
689 /// as a `uint`.
690 #[deriving(Clone)]
691 pub struct BitvSet {
692     size: uint,
693
694     // In theory this is a `Bitv` instead of always a `BigBitv`, but knowing that
695     // there's an array of storage makes our lives a whole lot easier when
696     // performing union/intersection/etc operations
697     bitv: BigBitv
698 }
699
700 impl Default for BitvSet {
701     #[inline]
702     fn default() -> BitvSet { BitvSet::new() }
703 }
704
705 impl BitvSet {
706     /// Creates a new bit vector set with initially no contents
707     pub fn new() -> BitvSet {
708         BitvSet{ size: 0, bitv: BigBitv::new(vec!(0)) }
709     }
710
711     /// Creates a new bit vector set from the given bit vector
712     pub fn from_bitv(bitv: Bitv) -> BitvSet {
713         let mut size = 0;
714         bitv.ones(|_| {
715             size += 1;
716             true
717         });
718         let Bitv{rep, ..} = bitv;
719         match rep {
720             Big(b) => BitvSet{ size: size, bitv: b },
721             Small(SmallBitv{bits}) =>
722                 BitvSet{ size: size, bitv: BigBitv{ storage: vec!(bits) } },
723         }
724     }
725
726     /// Returns the capacity in bits for this bit vector. Inserting any
727     /// element less than this amount will not trigger a resizing.
728     pub fn capacity(&self) -> uint { self.bitv.storage.len() * uint::BITS }
729
730     /// Consumes this set to return the underlying bit vector
731     pub fn unwrap(self) -> Bitv {
732         let cap = self.capacity();
733         let BitvSet{bitv, ..} = self;
734         return Bitv{ nbits:cap, rep: Big(bitv) };
735     }
736
737     #[inline]
738     fn other_op(&mut self, other: &BitvSet, f: |uint, uint| -> uint) {
739         fn nbits(mut w: uint) -> uint {
740             let mut bits = 0;
741             for _ in range(0u, uint::BITS) {
742                 if w == 0 {
743                     break;
744                 }
745                 bits += w & 1;
746                 w >>= 1;
747             }
748             return bits;
749         }
750         if self.capacity() < other.capacity() {
751             self.bitv.storage.grow(other.capacity() / uint::BITS, &0);
752         }
753         for (i, &w) in other.bitv.storage.iter().enumerate() {
754             let old = *self.bitv.storage.get(i);
755             let new = f(old, w);
756             *self.bitv.storage.get_mut(i) = new;
757             self.size += nbits(new) - nbits(old);
758         }
759     }
760
761     /// Union in-place with the specified other bit vector
762     pub fn union_with(&mut self, other: &BitvSet) {
763         self.other_op(other, |w1, w2| w1 | w2);
764     }
765
766     /// Intersect in-place with the specified other bit vector
767     pub fn intersect_with(&mut self, other: &BitvSet) {
768         self.other_op(other, |w1, w2| w1 & w2);
769     }
770
771     /// Difference in-place with the specified other bit vector
772     pub fn difference_with(&mut self, other: &BitvSet) {
773         self.other_op(other, |w1, w2| w1 & !w2);
774     }
775
776     /// Symmetric difference in-place with the specified other bit vector
777     pub fn symmetric_difference_with(&mut self, other: &BitvSet) {
778         self.other_op(other, |w1, w2| w1 ^ w2);
779     }
780
781     pub fn iter<'a>(&'a self) -> BitPositions<'a> {
782         BitPositions {set: self, next_idx: 0}
783     }
784
785     pub fn difference(&self, other: &BitvSet, f: |&uint| -> bool) -> bool {
786         for (i, w1, w2) in self.commons(other) {
787             if !iterate_bits(i, w1 & !w2, |b| f(&b)) {
788                 return false
789             }
790         };
791         /* everything we have that they don't also shows up */
792         self.outliers(other).advance(|(mine, i, w)|
793             !mine || iterate_bits(i, w, |b| f(&b))
794         )
795     }
796
797     pub fn symmetric_difference(&self, other: &BitvSet, f: |&uint| -> bool)
798                                 -> bool {
799         for (i, w1, w2) in self.commons(other) {
800             if !iterate_bits(i, w1 ^ w2, |b| f(&b)) {
801                 return false
802             }
803         };
804         self.outliers(other).advance(|(_, i, w)| iterate_bits(i, w, |b| f(&b)))
805     }
806
807     pub fn intersection(&self, other: &BitvSet, f: |&uint| -> bool) -> bool {
808         self.commons(other).advance(|(i, w1, w2)| iterate_bits(i, w1 & w2, |b| f(&b)))
809     }
810
811     pub fn union(&self, other: &BitvSet, f: |&uint| -> bool) -> bool {
812         for (i, w1, w2) in self.commons(other) {
813             if !iterate_bits(i, w1 | w2, |b| f(&b)) {
814                 return false
815             }
816         };
817         self.outliers(other).advance(|(_, i, w)| iterate_bits(i, w, |b| f(&b)))
818     }
819 }
820
821 impl cmp::PartialEq for BitvSet {
822     fn eq(&self, other: &BitvSet) -> bool {
823         if self.size != other.size {
824             return false;
825         }
826         for (_, w1, w2) in self.commons(other) {
827             if w1 != w2 {
828                 return false;
829             }
830         }
831         for (_, _, w) in self.outliers(other) {
832             if w != 0 {
833                 return false;
834             }
835         }
836         return true;
837     }
838
839     fn ne(&self, other: &BitvSet) -> bool { !self.eq(other) }
840 }
841
842 impl cmp::Eq for BitvSet {}
843
844 impl fmt::Show for BitvSet {
845     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
846         try!(write!(fmt, "{{"));
847         let mut first = true;
848         for n in self.iter() {
849             if !first {
850                 try!(write!(fmt, ", "));
851             }
852             try!(write!(fmt, "{}", n));
853             first = false;
854         }
855         write!(fmt, "}}")
856     }
857 }
858
859 impl<S: hash::Writer> hash::Hash<S> for BitvSet {
860     fn hash(&self, state: &mut S) {
861         for pos in self.iter() {
862             pos.hash(state);
863         }
864     }
865 }
866
867 impl Collection for BitvSet {
868     #[inline]
869     fn len(&self) -> uint { self.size }
870 }
871
872 impl Mutable for BitvSet {
873     fn clear(&mut self) {
874         self.bitv.each_storage(|w| { *w = 0; true });
875         self.size = 0;
876     }
877 }
878
879 impl Set<uint> for BitvSet {
880     fn contains(&self, value: &uint) -> bool {
881         *value < self.bitv.storage.len() * uint::BITS && self.bitv.get(*value)
882     }
883
884     fn is_disjoint(&self, other: &BitvSet) -> bool {
885         self.intersection(other, |_| false)
886     }
887
888     fn is_subset(&self, other: &BitvSet) -> bool {
889         for (_, w1, w2) in self.commons(other) {
890             if w1 & w2 != w1 {
891                 return false;
892             }
893         }
894         /* If anything is not ours, then everything is not ours so we're
895            definitely a subset in that case. Otherwise if there's any stray
896            ones that 'other' doesn't have, we're not a subset. */
897         for (mine, _, w) in self.outliers(other) {
898             if !mine {
899                 return true;
900             } else if w != 0 {
901                 return false;
902             }
903         }
904         return true;
905     }
906
907     fn is_superset(&self, other: &BitvSet) -> bool {
908         other.is_subset(self)
909     }
910 }
911
912 impl MutableSet<uint> for BitvSet {
913     fn insert(&mut self, value: uint) -> bool {
914         if self.contains(&value) {
915             return false;
916         }
917         let nbits = self.capacity();
918         if value >= nbits {
919             let newsize = cmp::max(value, nbits * 2) / uint::BITS + 1;
920             assert!(newsize > self.bitv.storage.len());
921             self.bitv.storage.grow(newsize, &0);
922         }
923         self.size += 1;
924         self.bitv.set(value, true);
925         return true;
926     }
927
928     fn remove(&mut self, value: &uint) -> bool {
929         if !self.contains(value) {
930             return false;
931         }
932         self.size -= 1;
933         self.bitv.set(*value, false);
934
935         // Attempt to truncate our storage
936         let mut i = self.bitv.storage.len();
937         while i > 1 && *self.bitv.storage.get(i - 1) == 0 {
938             i -= 1;
939         }
940         self.bitv.storage.truncate(i);
941
942         return true;
943     }
944 }
945
946 impl BitvSet {
947     /// Visits each of the words that the two bit vectors (`self` and `other`)
948     /// both have in common. The three yielded arguments are (bit location,
949     /// w1, w2) where the bit location is the number of bits offset so far,
950     /// and w1/w2 are the words coming from the two vectors self, other.
951     fn commons<'a>(&'a self, other: &'a BitvSet)
952         -> Map<'static, ((uint, &'a uint), &'a Vec<uint>), (uint, uint, uint),
953                Zip<Enumerate<slice::Items<'a, uint>>, Repeat<&'a Vec<uint>>>> {
954         let min = cmp::min(self.bitv.storage.len(), other.bitv.storage.len());
955         self.bitv.storage.slice(0, min).iter().enumerate()
956             .zip(Repeat::new(&other.bitv.storage))
957             .map(|((i, &w), o_store)| (i * uint::BITS, w, *o_store.get(i)))
958     }
959
960     /// Visits each word in `self` or `other` that extends beyond the other. This
961     /// will only iterate through one of the vectors, and it only iterates
962     /// over the portion that doesn't overlap with the other one.
963     ///
964     /// The yielded arguments are a `bool`, the bit offset, and a word. The `bool`
965     /// is true if the word comes from `self`, and `false` if it comes from
966     /// `other`.
967     fn outliers<'a>(&'a self, other: &'a BitvSet)
968         -> Map<'static, ((uint, &'a uint), uint), (bool, uint, uint),
969                Zip<Enumerate<slice::Items<'a, uint>>, Repeat<uint>>> {
970         let slen = self.bitv.storage.len();
971         let olen = other.bitv.storage.len();
972
973         if olen < slen {
974             self.bitv.storage.slice_from(olen).iter().enumerate()
975                 .zip(Repeat::new(olen))
976                 .map(|((i, &w), min)| (true, (i + min) * uint::BITS, w))
977         } else {
978             other.bitv.storage.slice_from(slen).iter().enumerate()
979                 .zip(Repeat::new(slen))
980                 .map(|((i, &w), min)| (false, (i + min) * uint::BITS, w))
981         }
982     }
983 }
984
985 pub struct BitPositions<'a> {
986     set: &'a BitvSet,
987     next_idx: uint
988 }
989
990 impl<'a> Iterator<uint> for BitPositions<'a> {
991     #[inline]
992     fn next(&mut self) -> Option<uint> {
993         while self.next_idx < self.set.capacity() {
994             let idx = self.next_idx;
995             self.next_idx += 1;
996
997             if self.set.contains(&idx) {
998                 return Some(idx);
999             }
1000         }
1001
1002         return None;
1003     }
1004
1005     fn size_hint(&self) -> (uint, Option<uint>) {
1006         (0, Some(self.set.capacity() - self.next_idx))
1007     }
1008 }
1009
1010 #[cfg(test)]
1011 mod tests {
1012     use std::prelude::*;
1013     use std::uint;
1014     use std::rand;
1015     use std::rand::Rng;
1016     use test::Bencher;
1017
1018     use {Set, Mutable, MutableSet};
1019     use bitv::{Bitv, SmallBitv, BigBitv, BitvSet, from_bools, from_fn,
1020                from_bytes};
1021     use bitv;
1022     use vec::Vec;
1023
1024     static BENCH_BITS : uint = 1 << 14;
1025
1026     #[test]
1027     fn test_to_str() {
1028         let zerolen = Bitv::new(0u, false);
1029         assert_eq!(zerolen.to_str().as_slice(), "");
1030
1031         let eightbits = Bitv::new(8u, false);
1032         assert_eq!(eightbits.to_str().as_slice(), "00000000")
1033     }
1034
1035     #[test]
1036     fn test_0_elements() {
1037         let act = Bitv::new(0u, false);
1038         let exp = Vec::from_elem(0u, false);
1039         assert!(act.eq_vec(exp.as_slice()));
1040     }
1041
1042     #[test]
1043     fn test_1_element() {
1044         let mut act = Bitv::new(1u, false);
1045         assert!(act.eq_vec([false]));
1046         act = Bitv::new(1u, true);
1047         assert!(act.eq_vec([true]));
1048     }
1049
1050     #[test]
1051     fn test_2_elements() {
1052         let mut b = bitv::Bitv::new(2, false);
1053         b.set(0, true);
1054         b.set(1, false);
1055         assert_eq!(b.to_str().as_slice(), "10");
1056     }
1057
1058     #[test]
1059     fn test_10_elements() {
1060         let mut act;
1061         // all 0
1062
1063         act = Bitv::new(10u, false);
1064         assert!((act.eq_vec(
1065                     [false, false, false, false, false, false, false, false, false, false])));
1066         // all 1
1067
1068         act = Bitv::new(10u, true);
1069         assert!((act.eq_vec([true, true, true, true, true, true, true, true, true, true])));
1070         // mixed
1071
1072         act = Bitv::new(10u, false);
1073         act.set(0u, true);
1074         act.set(1u, true);
1075         act.set(2u, true);
1076         act.set(3u, true);
1077         act.set(4u, true);
1078         assert!((act.eq_vec([true, true, true, true, true, false, false, false, false, false])));
1079         // mixed
1080
1081         act = Bitv::new(10u, false);
1082         act.set(5u, true);
1083         act.set(6u, true);
1084         act.set(7u, true);
1085         act.set(8u, true);
1086         act.set(9u, true);
1087         assert!((act.eq_vec([false, false, false, false, false, true, true, true, true, true])));
1088         // mixed
1089
1090         act = Bitv::new(10u, false);
1091         act.set(0u, true);
1092         act.set(3u, true);
1093         act.set(6u, true);
1094         act.set(9u, true);
1095         assert!((act.eq_vec([true, false, false, true, false, false, true, false, false, true])));
1096     }
1097
1098     #[test]
1099     fn test_31_elements() {
1100         let mut act;
1101         // all 0
1102
1103         act = Bitv::new(31u, false);
1104         assert!(act.eq_vec(
1105                 [false, false, false, false, false, false, false, false, false, false, false,
1106                 false, false, false, false, false, false, false, false, false, false, false, false,
1107                 false, false, false, false, false, false, false, false]));
1108         // all 1
1109
1110         act = Bitv::new(31u, true);
1111         assert!(act.eq_vec(
1112                 [true, true, true, true, true, true, true, true, true, true, true, true, true,
1113                 true, true, true, true, true, true, true, true, true, true, true, true, true, true,
1114                 true, true, true, true]));
1115         // mixed
1116
1117         act = Bitv::new(31u, false);
1118         act.set(0u, true);
1119         act.set(1u, true);
1120         act.set(2u, true);
1121         act.set(3u, true);
1122         act.set(4u, true);
1123         act.set(5u, true);
1124         act.set(6u, true);
1125         act.set(7u, true);
1126         assert!(act.eq_vec(
1127                 [true, true, true, true, true, true, true, true, false, false, false, false, false,
1128                 false, false, false, false, false, false, false, false, false, false, false, false,
1129                 false, false, false, false, false, false]));
1130         // mixed
1131
1132         act = Bitv::new(31u, false);
1133         act.set(16u, true);
1134         act.set(17u, true);
1135         act.set(18u, true);
1136         act.set(19u, true);
1137         act.set(20u, true);
1138         act.set(21u, true);
1139         act.set(22u, true);
1140         act.set(23u, true);
1141         assert!(act.eq_vec(
1142                 [false, false, false, false, false, false, false, false, false, false, false,
1143                 false, false, false, false, false, true, true, true, true, true, true, true, true,
1144                 false, false, false, false, false, false, false]));
1145         // mixed
1146
1147         act = Bitv::new(31u, false);
1148         act.set(24u, true);
1149         act.set(25u, true);
1150         act.set(26u, true);
1151         act.set(27u, true);
1152         act.set(28u, true);
1153         act.set(29u, true);
1154         act.set(30u, true);
1155         assert!(act.eq_vec(
1156                 [false, false, false, false, false, false, false, false, false, false, false,
1157                 false, false, false, false, false, false, false, false, false, false, false, false,
1158                 false, true, true, true, true, true, true, true]));
1159         // mixed
1160
1161         act = Bitv::new(31u, false);
1162         act.set(3u, true);
1163         act.set(17u, true);
1164         act.set(30u, true);
1165         assert!(act.eq_vec(
1166                 [false, false, false, true, false, false, false, false, false, false, false, false,
1167                 false, false, false, false, false, true, false, false, false, false, false, false,
1168                 false, false, false, false, false, false, true]));
1169     }
1170
1171     #[test]
1172     fn test_32_elements() {
1173         let mut act;
1174         // all 0
1175
1176         act = Bitv::new(32u, false);
1177         assert!(act.eq_vec(
1178                 [false, false, false, false, false, false, false, false, false, false, false,
1179                 false, false, false, false, false, false, false, false, false, false, false, false,
1180                 false, false, false, false, false, false, false, false, false]));
1181         // all 1
1182
1183         act = Bitv::new(32u, true);
1184         assert!(act.eq_vec(
1185                 [true, true, true, true, true, true, true, true, true, true, true, true, true,
1186                 true, true, true, true, true, true, true, true, true, true, true, true, true, true,
1187                 true, true, true, true, true]));
1188         // mixed
1189
1190         act = Bitv::new(32u, false);
1191         act.set(0u, true);
1192         act.set(1u, true);
1193         act.set(2u, true);
1194         act.set(3u, true);
1195         act.set(4u, true);
1196         act.set(5u, true);
1197         act.set(6u, true);
1198         act.set(7u, true);
1199         assert!(act.eq_vec(
1200                 [true, true, true, true, true, true, true, true, false, false, false, false, false,
1201                 false, false, false, false, false, false, false, false, false, false, false, false,
1202                 false, false, false, false, false, false, false]));
1203         // mixed
1204
1205         act = Bitv::new(32u, false);
1206         act.set(16u, true);
1207         act.set(17u, true);
1208         act.set(18u, true);
1209         act.set(19u, true);
1210         act.set(20u, true);
1211         act.set(21u, true);
1212         act.set(22u, true);
1213         act.set(23u, true);
1214         assert!(act.eq_vec(
1215                 [false, false, false, false, false, false, false, false, false, false, false,
1216                 false, false, false, false, false, true, true, true, true, true, true, true, true,
1217                 false, false, false, false, false, false, false, false]));
1218         // mixed
1219
1220         act = Bitv::new(32u, false);
1221         act.set(24u, true);
1222         act.set(25u, true);
1223         act.set(26u, true);
1224         act.set(27u, true);
1225         act.set(28u, true);
1226         act.set(29u, true);
1227         act.set(30u, true);
1228         act.set(31u, true);
1229         assert!(act.eq_vec(
1230                 [false, false, false, false, false, false, false, false, false, false, false,
1231                 false, false, false, false, false, false, false, false, false, false, false, false,
1232                 false, true, true, true, true, true, true, true, true]));
1233         // mixed
1234
1235         act = Bitv::new(32u, false);
1236         act.set(3u, true);
1237         act.set(17u, true);
1238         act.set(30u, true);
1239         act.set(31u, true);
1240         assert!(act.eq_vec(
1241                 [false, false, false, true, false, false, false, false, false, false, false, false,
1242                 false, false, false, false, false, true, false, false, false, false, false, false,
1243                 false, false, false, false, false, false, true, true]));
1244     }
1245
1246     #[test]
1247     fn test_33_elements() {
1248         let mut act;
1249         // all 0
1250
1251         act = Bitv::new(33u, false);
1252         assert!(act.eq_vec(
1253                 [false, false, false, false, false, false, false, false, false, false, false,
1254                 false, false, false, false, false, false, false, false, false, false, false, false,
1255                 false, false, false, false, false, false, false, false, false, false]));
1256         // all 1
1257
1258         act = Bitv::new(33u, true);
1259         assert!(act.eq_vec(
1260                 [true, true, true, true, true, true, true, true, true, true, true, true, true,
1261                 true, true, true, true, true, true, true, true, true, true, true, true, true, true,
1262                 true, true, true, true, true, true]));
1263         // mixed
1264
1265         act = Bitv::new(33u, false);
1266         act.set(0u, true);
1267         act.set(1u, true);
1268         act.set(2u, true);
1269         act.set(3u, true);
1270         act.set(4u, true);
1271         act.set(5u, true);
1272         act.set(6u, true);
1273         act.set(7u, true);
1274         assert!(act.eq_vec(
1275                 [true, true, true, true, true, true, true, true, false, false, false, false, false,
1276                 false, false, false, false, false, false, false, false, false, false, false, false,
1277                 false, false, false, false, false, false, false, false]));
1278         // mixed
1279
1280         act = Bitv::new(33u, false);
1281         act.set(16u, true);
1282         act.set(17u, true);
1283         act.set(18u, true);
1284         act.set(19u, true);
1285         act.set(20u, true);
1286         act.set(21u, true);
1287         act.set(22u, true);
1288         act.set(23u, true);
1289         assert!(act.eq_vec(
1290                 [false, false, false, false, false, false, false, false, false, false, false,
1291                 false, false, false, false, false, true, true, true, true, true, true, true, true,
1292                 false, false, false, false, false, false, false, false, false]));
1293         // mixed
1294
1295         act = Bitv::new(33u, false);
1296         act.set(24u, true);
1297         act.set(25u, true);
1298         act.set(26u, true);
1299         act.set(27u, true);
1300         act.set(28u, true);
1301         act.set(29u, true);
1302         act.set(30u, true);
1303         act.set(31u, true);
1304         assert!(act.eq_vec(
1305                 [false, false, false, false, false, false, false, false, false, false, false,
1306                 false, false, false, false, false, false, false, false, false, false, false, false,
1307                 false, true, true, true, true, true, true, true, true, false]));
1308         // mixed
1309
1310         act = Bitv::new(33u, false);
1311         act.set(3u, true);
1312         act.set(17u, true);
1313         act.set(30u, true);
1314         act.set(31u, true);
1315         act.set(32u, true);
1316         assert!(act.eq_vec(
1317                 [false, false, false, true, false, false, false, false, false, false, false, false,
1318                 false, false, false, false, false, true, false, false, false, false, false, false,
1319                 false, false, false, false, false, false, true, true, true]));
1320     }
1321
1322     #[test]
1323     fn test_equal_differing_sizes() {
1324         let v0 = Bitv::new(10u, false);
1325         let v1 = Bitv::new(11u, false);
1326         assert!(v0 != v1);
1327     }
1328
1329     #[test]
1330     fn test_equal_greatly_differing_sizes() {
1331         let v0 = Bitv::new(10u, false);
1332         let v1 = Bitv::new(110u, false);
1333         assert!(v0 != v1);
1334     }
1335
1336     #[test]
1337     fn test_equal_sneaky_small() {
1338         let mut a = bitv::Bitv::new(1, false);
1339         a.set(0, true);
1340
1341         let mut b = bitv::Bitv::new(1, true);
1342         b.set(0, true);
1343
1344         assert_eq!(a, b);
1345     }
1346
1347     #[test]
1348     fn test_equal_sneaky_big() {
1349         let mut a = bitv::Bitv::new(100, false);
1350         for i in range(0u, 100) {
1351             a.set(i, true);
1352         }
1353
1354         let mut b = bitv::Bitv::new(100, true);
1355         for i in range(0u, 100) {
1356             b.set(i, true);
1357         }
1358
1359         assert_eq!(a, b);
1360     }
1361
1362     #[test]
1363     fn test_from_bytes() {
1364         let bitv = from_bytes([0b10110110, 0b00000000, 0b11111111]);
1365         let str = format!("{}{}{}", "10110110", "00000000", "11111111");
1366         assert_eq!(bitv.to_str().as_slice(), str.as_slice());
1367     }
1368
1369     #[test]
1370     fn test_to_bytes() {
1371         let mut bv = Bitv::new(3, true);
1372         bv.set(1, false);
1373         assert_eq!(bv.to_bytes(), vec!(0b10100000));
1374
1375         let mut bv = Bitv::new(9, false);
1376         bv.set(2, true);
1377         bv.set(8, true);
1378         assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000));
1379     }
1380
1381     #[test]
1382     fn test_from_bools() {
1383         assert!(from_bools([true, false, true, true]).to_str().as_slice() ==
1384                 "1011");
1385     }
1386
1387     #[test]
1388     fn test_to_bools() {
1389         let bools = vec!(false, false, true, false, false, true, true, false);
1390         assert_eq!(from_bytes([0b00100110]).to_bools(), bools);
1391     }
1392
1393     #[test]
1394     fn test_bitv_iterator() {
1395         let bools = [true, false, true, true];
1396         let bitv = from_bools(bools);
1397
1398         for (act, &ex) in bitv.iter().zip(bools.iter()) {
1399             assert_eq!(ex, act);
1400         }
1401     }
1402
1403     #[test]
1404     fn test_bitv_set_iterator() {
1405         let bools = [true, false, true, true];
1406         let bitv = BitvSet::from_bitv(from_bools(bools));
1407
1408         let idxs: Vec<uint> = bitv.iter().collect();
1409         assert_eq!(idxs, vec!(0, 2, 3));
1410     }
1411
1412     #[test]
1413     fn test_bitv_set_frombitv_init() {
1414         let bools = [true, false];
1415         let lengths = [10, 64, 100];
1416         for &b in bools.iter() {
1417             for &l in lengths.iter() {
1418                 let bitset = BitvSet::from_bitv(Bitv::new(l, b));
1419                 assert_eq!(bitset.contains(&1u), b)
1420                 assert_eq!(bitset.contains(&(l-1u)), b)
1421                 assert!(!bitset.contains(&l))
1422             }
1423         }
1424     }
1425
1426     #[test]
1427     fn test_small_difference() {
1428         let mut b1 = Bitv::new(3, false);
1429         let mut b2 = Bitv::new(3, false);
1430         b1.set(0, true);
1431         b1.set(1, true);
1432         b2.set(1, true);
1433         b2.set(2, true);
1434         assert!(b1.difference(&b2));
1435         assert!(b1[0]);
1436         assert!(!b1[1]);
1437         assert!(!b1[2]);
1438     }
1439
1440     #[test]
1441     fn test_big_difference() {
1442         let mut b1 = Bitv::new(100, false);
1443         let mut b2 = Bitv::new(100, false);
1444         b1.set(0, true);
1445         b1.set(40, true);
1446         b2.set(40, true);
1447         b2.set(80, true);
1448         assert!(b1.difference(&b2));
1449         assert!(b1[0]);
1450         assert!(!b1[40]);
1451         assert!(!b1[80]);
1452     }
1453
1454     #[test]
1455     fn test_small_clear() {
1456         let mut b = Bitv::new(14, true);
1457         b.clear();
1458         b.ones(|i| {
1459             fail!("found 1 at {:?}", i)
1460         });
1461     }
1462
1463     #[test]
1464     fn test_big_clear() {
1465         let mut b = Bitv::new(140, true);
1466         b.clear();
1467         b.ones(|i| {
1468             fail!("found 1 at {:?}", i)
1469         });
1470     }
1471
1472     #[test]
1473     fn test_bitv_set_basic() {
1474         let mut b = BitvSet::new();
1475         assert!(b.insert(3));
1476         assert!(!b.insert(3));
1477         assert!(b.contains(&3));
1478         assert!(b.insert(400));
1479         assert!(!b.insert(400));
1480         assert!(b.contains(&400));
1481         assert_eq!(b.len(), 2);
1482     }
1483
1484     #[test]
1485     fn test_bitv_set_intersection() {
1486         let mut a = BitvSet::new();
1487         let mut b = BitvSet::new();
1488
1489         assert!(a.insert(11));
1490         assert!(a.insert(1));
1491         assert!(a.insert(3));
1492         assert!(a.insert(77));
1493         assert!(a.insert(103));
1494         assert!(a.insert(5));
1495
1496         assert!(b.insert(2));
1497         assert!(b.insert(11));
1498         assert!(b.insert(77));
1499         assert!(b.insert(5));
1500         assert!(b.insert(3));
1501
1502         let mut i = 0;
1503         let expected = [3, 5, 11, 77];
1504         a.intersection(&b, |x| {
1505             assert_eq!(*x, expected[i]);
1506             i += 1;
1507             true
1508         });
1509         assert_eq!(i, expected.len());
1510     }
1511
1512     #[test]
1513     fn test_bitv_set_difference() {
1514         let mut a = BitvSet::new();
1515         let mut b = BitvSet::new();
1516
1517         assert!(a.insert(1));
1518         assert!(a.insert(3));
1519         assert!(a.insert(5));
1520         assert!(a.insert(200));
1521         assert!(a.insert(500));
1522
1523         assert!(b.insert(3));
1524         assert!(b.insert(200));
1525
1526         let mut i = 0;
1527         let expected = [1, 5, 500];
1528         a.difference(&b, |x| {
1529             assert_eq!(*x, expected[i]);
1530             i += 1;
1531             true
1532         });
1533         assert_eq!(i, expected.len());
1534     }
1535
1536     #[test]
1537     fn test_bitv_set_symmetric_difference() {
1538         let mut a = BitvSet::new();
1539         let mut b = BitvSet::new();
1540
1541         assert!(a.insert(1));
1542         assert!(a.insert(3));
1543         assert!(a.insert(5));
1544         assert!(a.insert(9));
1545         assert!(a.insert(11));
1546
1547         assert!(b.insert(3));
1548         assert!(b.insert(9));
1549         assert!(b.insert(14));
1550         assert!(b.insert(220));
1551
1552         let mut i = 0;
1553         let expected = [1, 5, 11, 14, 220];
1554         a.symmetric_difference(&b, |x| {
1555             assert_eq!(*x, expected[i]);
1556             i += 1;
1557             true
1558         });
1559         assert_eq!(i, expected.len());
1560     }
1561
1562     #[test]
1563     fn test_bitv_set_union() {
1564         let mut a = BitvSet::new();
1565         let mut b = BitvSet::new();
1566         assert!(a.insert(1));
1567         assert!(a.insert(3));
1568         assert!(a.insert(5));
1569         assert!(a.insert(9));
1570         assert!(a.insert(11));
1571         assert!(a.insert(160));
1572         assert!(a.insert(19));
1573         assert!(a.insert(24));
1574
1575         assert!(b.insert(1));
1576         assert!(b.insert(5));
1577         assert!(b.insert(9));
1578         assert!(b.insert(13));
1579         assert!(b.insert(19));
1580
1581         let mut i = 0;
1582         let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160];
1583         a.union(&b, |x| {
1584             assert_eq!(*x, expected[i]);
1585             i += 1;
1586             true
1587         });
1588         assert_eq!(i, expected.len());
1589     }
1590
1591     #[test]
1592     fn test_bitv_remove() {
1593         let mut a = BitvSet::new();
1594
1595         assert!(a.insert(1));
1596         assert!(a.remove(&1));
1597
1598         assert!(a.insert(100));
1599         assert!(a.remove(&100));
1600
1601         assert!(a.insert(1000));
1602         assert!(a.remove(&1000));
1603         assert_eq!(a.capacity(), uint::BITS);
1604     }
1605
1606     #[test]
1607     fn test_bitv_clone() {
1608         let mut a = BitvSet::new();
1609
1610         assert!(a.insert(1));
1611         assert!(a.insert(100));
1612         assert!(a.insert(1000));
1613
1614         let mut b = a.clone();
1615
1616         assert!(a == b);
1617
1618         assert!(b.remove(&1));
1619         assert!(a.contains(&1));
1620
1621         assert!(a.remove(&1000));
1622         assert!(b.contains(&1000));
1623     }
1624
1625     #[test]
1626     fn test_small_bitv_tests() {
1627         let v = from_bytes([0]);
1628         assert!(!v.all());
1629         assert!(!v.any());
1630         assert!(v.none());
1631
1632         let v = from_bytes([0b00010100]);
1633         assert!(!v.all());
1634         assert!(v.any());
1635         assert!(!v.none());
1636
1637         let v = from_bytes([0xFF]);
1638         assert!(v.all());
1639         assert!(v.any());
1640         assert!(!v.none());
1641     }
1642
1643     #[test]
1644     fn test_big_bitv_tests() {
1645         let v = from_bytes([ // 88 bits
1646             0, 0, 0, 0,
1647             0, 0, 0, 0,
1648             0, 0, 0]);
1649         assert!(!v.all());
1650         assert!(!v.any());
1651         assert!(v.none());
1652
1653         let v = from_bytes([ // 88 bits
1654             0, 0, 0b00010100, 0,
1655             0, 0, 0, 0b00110100,
1656             0, 0, 0]);
1657         assert!(!v.all());
1658         assert!(v.any());
1659         assert!(!v.none());
1660
1661         let v = from_bytes([ // 88 bits
1662             0xFF, 0xFF, 0xFF, 0xFF,
1663             0xFF, 0xFF, 0xFF, 0xFF,
1664             0xFF, 0xFF, 0xFF]);
1665         assert!(v.all());
1666         assert!(v.any());
1667         assert!(!v.none());
1668     }
1669
1670     #[test]
1671     fn test_bitv_set_show() {
1672         let mut s = BitvSet::new();
1673         s.insert(1);
1674         s.insert(10);
1675         s.insert(50);
1676         s.insert(2);
1677         assert_eq!("{1, 2, 10, 50}".to_string(), s.to_str());
1678     }
1679
1680     fn rng() -> rand::IsaacRng {
1681         let seed = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
1682         rand::SeedableRng::from_seed(seed)
1683     }
1684
1685     #[bench]
1686     fn bench_uint_small(b: &mut Bencher) {
1687         let mut r = rng();
1688         let mut bitv = 0 as uint;
1689         b.iter(|| {
1690             bitv |= 1 << ((r.next_u32() as uint) % uint::BITS);
1691             &bitv
1692         })
1693     }
1694
1695     #[bench]
1696     fn bench_small_bitv_small(b: &mut Bencher) {
1697         let mut r = rng();
1698         let mut bitv = SmallBitv::new(uint::BITS);
1699         b.iter(|| {
1700             bitv.set((r.next_u32() as uint) % uint::BITS, true);
1701             &bitv
1702         })
1703     }
1704
1705     #[bench]
1706     fn bench_big_bitv_small(b: &mut Bencher) {
1707         let mut r = rng();
1708         let mut bitv = BigBitv::new(vec!(0));
1709         b.iter(|| {
1710             bitv.set((r.next_u32() as uint) % uint::BITS, true);
1711             &bitv
1712         })
1713     }
1714
1715     #[bench]
1716     fn bench_big_bitv_big(b: &mut Bencher) {
1717         let mut r = rng();
1718         let mut storage = vec!();
1719         storage.grow(BENCH_BITS / uint::BITS, &0u);
1720         let mut bitv = BigBitv::new(storage);
1721         b.iter(|| {
1722             bitv.set((r.next_u32() as uint) % BENCH_BITS, true);
1723             &bitv
1724         })
1725     }
1726
1727     #[bench]
1728     fn bench_bitv_big(b: &mut Bencher) {
1729         let mut r = rng();
1730         let mut bitv = Bitv::new(BENCH_BITS, false);
1731         b.iter(|| {
1732             bitv.set((r.next_u32() as uint) % BENCH_BITS, true);
1733             &bitv
1734         })
1735     }
1736
1737     #[bench]
1738     fn bench_bitv_small(b: &mut Bencher) {
1739         let mut r = rng();
1740         let mut bitv = Bitv::new(uint::BITS, false);
1741         b.iter(|| {
1742             bitv.set((r.next_u32() as uint) % uint::BITS, true);
1743             &bitv
1744         })
1745     }
1746
1747     #[bench]
1748     fn bench_bitv_set_small(b: &mut Bencher) {
1749         let mut r = rng();
1750         let mut bitv = BitvSet::new();
1751         b.iter(|| {
1752             bitv.insert((r.next_u32() as uint) % uint::BITS);
1753             &bitv
1754         })
1755     }
1756
1757     #[bench]
1758     fn bench_bitv_set_big(b: &mut Bencher) {
1759         let mut r = rng();
1760         let mut bitv = BitvSet::new();
1761         b.iter(|| {
1762             bitv.insert((r.next_u32() as uint) % BENCH_BITS);
1763             &bitv
1764         })
1765     }
1766
1767     #[bench]
1768     fn bench_bitv_big_union(b: &mut Bencher) {
1769         let mut b1 = Bitv::new(BENCH_BITS, false);
1770         let b2 = Bitv::new(BENCH_BITS, false);
1771         b.iter(|| {
1772             b1.union(&b2);
1773         })
1774     }
1775
1776     #[bench]
1777     fn bench_btv_small_iter(b: &mut Bencher) {
1778         let bitv = Bitv::new(uint::BITS, false);
1779         b.iter(|| {
1780             let mut _sum = 0;
1781             for pres in bitv.iter() {
1782                 _sum += pres as uint;
1783             }
1784         })
1785     }
1786
1787     #[bench]
1788     fn bench_bitv_big_iter(b: &mut Bencher) {
1789         let bitv = Bitv::new(BENCH_BITS, false);
1790         b.iter(|| {
1791             let mut _sum = 0;
1792             for pres in bitv.iter() {
1793                 _sum += pres as uint;
1794             }
1795         })
1796     }
1797
1798     #[bench]
1799     fn bench_bitvset_iter(b: &mut Bencher) {
1800         let bitv = BitvSet::from_bitv(from_fn(BENCH_BITS,
1801                                               |idx| {idx % 3 == 0}));
1802         b.iter(|| {
1803             let mut _sum = 0;
1804             for idx in bitv.iter() {
1805                 _sum += idx;
1806             }
1807         })
1808     }
1809 }