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