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