]> git.lizzy.rs Git - rust.git/blob - src/libcollections/bitv.rs
Convert most code to new inner attribute syntax.
[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::uint;
19 use std::slice;
20
21 #[deriving(Clone)]
22 struct SmallBitv {
23     /// only the lowest nbits of this value are used. the rest is undefined.
24     bits: uint
25 }
26
27 /// a mask that has a 1 for each defined bit in a small_bitv, assuming n bits
28 #[inline]
29 fn small_mask(nbits: uint) -> uint {
30     (1 << nbits) - 1
31 }
32
33 impl SmallBitv {
34     pub fn new(bits: uint) -> SmallBitv {
35         SmallBitv {bits: bits}
36     }
37
38     #[inline]
39     pub fn bits_op(&mut self,
40                    right_bits: uint,
41                    nbits: uint,
42                    f: |uint, uint| -> uint)
43                    -> bool {
44         let mask = small_mask(nbits);
45         let old_b: uint = self.bits;
46         let new_b = f(old_b, right_bits);
47         self.bits = new_b;
48         mask & old_b != mask & new_b
49     }
50
51     #[inline]
52     pub fn union(&mut self, s: &SmallBitv, nbits: uint) -> bool {
53         self.bits_op(s.bits, nbits, |u1, u2| u1 | u2)
54     }
55
56     #[inline]
57     pub fn intersect(&mut self, s: &SmallBitv, nbits: uint) -> bool {
58         self.bits_op(s.bits, nbits, |u1, u2| u1 & u2)
59     }
60
61     #[inline]
62     pub fn become(&mut self, s: &SmallBitv, nbits: uint) -> bool {
63         self.bits_op(s.bits, nbits, |_u1, u2| u2)
64     }
65
66     #[inline]
67     pub fn difference(&mut self, s: &SmallBitv, nbits: uint) -> bool {
68         self.bits_op(s.bits, nbits, |u1, u2| u1 & !u2)
69     }
70
71     #[inline]
72     pub fn get(&self, i: uint) -> bool {
73         (self.bits & (1 << i)) != 0
74     }
75
76     #[inline]
77     pub fn set(&mut self, i: uint, x: bool) {
78         if x {
79             self.bits |= 1<<i;
80         }
81         else {
82             self.bits &= !(1<<i);
83         }
84     }
85
86     #[inline]
87     pub fn equals(&self, b: &SmallBitv, nbits: uint) -> bool {
88         let mask = small_mask(nbits);
89         mask & self.bits == mask & b.bits
90     }
91
92     #[inline]
93     pub fn clear(&mut self) { self.bits = 0; }
94
95     #[inline]
96     pub fn set_all(&mut self) { self.bits = !0; }
97
98     #[inline]
99     pub fn is_true(&self, nbits: uint) -> bool {
100         small_mask(nbits) & !self.bits == 0
101     }
102
103     #[inline]
104     pub fn is_false(&self, nbits: uint) -> bool {
105         small_mask(nbits) & self.bits == 0
106     }
107
108     #[inline]
109     pub fn negate(&mut self) { self.bits = !self.bits; }
110 }
111
112 #[deriving(Clone)]
113 struct BigBitv {
114     storage: ~[uint]
115 }
116
117 /**
118  * A mask that has a 1 for each defined bit in the n'th element of a `BigBitv`,
119  * assuming n bits.
120  */
121 #[inline]
122 fn big_mask(nbits: uint, elem: uint) -> uint {
123     let rmd = nbits % uint::BITS;
124     let nelems = nbits/uint::BITS + if rmd == 0 {0} else {1};
125
126     if elem < nelems - 1 || rmd == 0 {
127         !0
128     } else {
129         (1 << rmd) - 1
130     }
131 }
132
133 impl BigBitv {
134     pub fn new(storage: ~[uint]) -> BigBitv {
135         BigBitv {storage: storage}
136     }
137
138     #[inline]
139     pub fn process(&mut self,
140                    b: &BigBitv,
141                    nbits: uint,
142                    op: |uint, uint| -> uint)
143                    -> bool {
144         let len = b.storage.len();
145         assert_eq!(self.storage.len(), len);
146         let mut changed = false;
147         for (i, (a, b)) in self.storage.mut_iter()
148                                .zip(b.storage.iter())
149                                .enumerate() {
150             let mask = big_mask(nbits, i);
151             let w0 = *a & mask;
152             let w1 = *b & mask;
153             let w = op(w0, w1) & mask;
154             if w0 != w {
155                 changed = true;
156                 *a = w;
157             }
158         }
159         changed
160     }
161
162     #[inline]
163     pub fn each_storage(&mut self, op: |v: &mut uint| -> bool) -> bool {
164         self.storage.mut_iter().advance(|elt| op(elt))
165     }
166
167     #[inline]
168     pub fn negate(&mut self) {
169         self.each_storage(|w| { *w = !*w; true });
170     }
171
172     #[inline]
173     pub fn union(&mut self, b: &BigBitv, nbits: uint) -> bool {
174         self.process(b, nbits, |w1, w2| w1 | w2)
175     }
176
177     #[inline]
178     pub fn intersect(&mut self, b: &BigBitv, nbits: uint) -> bool {
179         self.process(b, nbits, |w1, w2| w1 & w2)
180     }
181
182     #[inline]
183     pub fn become(&mut self, b: &BigBitv, nbits: uint) -> bool {
184         self.process(b, nbits, |_, w| w)
185     }
186
187     #[inline]
188     pub fn difference(&mut self, b: &BigBitv, nbits: uint) -> bool {
189         self.process(b, nbits, |w1, w2| w1 & !w2)
190     }
191
192     #[inline]
193     pub fn get(&self, i: uint) -> bool {
194         let w = i / uint::BITS;
195         let b = i % uint::BITS;
196         let x = 1 & self.storage[w] >> b;
197         x == 1
198     }
199
200     #[inline]
201     pub fn set(&mut self, i: uint, x: bool) {
202         let w = i / uint::BITS;
203         let b = i % uint::BITS;
204         let flag = 1 << b;
205         self.storage[w] = if x { self.storage[w] | flag }
206                           else { self.storage[w] & !flag };
207     }
208
209     #[inline]
210     pub fn equals(&self, b: &BigBitv, nbits: uint) -> bool {
211         for (i, elt) in b.storage.iter().enumerate() {
212             let mask = big_mask(nbits, i);
213             if mask & self.storage[i] != mask & *elt {
214                 return false;
215             }
216         }
217         true
218     }
219 }
220
221 #[deriving(Clone)]
222 enum BitvVariant { Big(BigBitv), Small(SmallBitv) }
223
224 enum Op {Union, Intersect, Assign, Difference}
225
226 /// The bitvector type
227 #[deriving(Clone)]
228 pub struct Bitv {
229     /// Internal representation of the bit vector (small or large)
230     priv rep: BitvVariant,
231     /// The number of valid bits in the internal representation
232     priv nbits: uint
233 }
234
235 fn die() -> ! {
236     fail!("Tried to do operation on bit vectors with different sizes");
237 }
238
239 impl Bitv {
240     #[inline]
241     fn do_op(&mut self, op: Op, other: &Bitv) -> bool {
242         if self.nbits != other.nbits {
243             die();
244         }
245         match self.rep {
246           Small(ref mut s) => match other.rep {
247             Small(ref s1) => match op {
248               Union      => s.union(s1,      self.nbits),
249               Intersect  => s.intersect(s1,  self.nbits),
250               Assign     => s.become(s1,     self.nbits),
251               Difference => s.difference(s1, self.nbits)
252             },
253             Big(_) => die()
254           },
255           Big(ref mut s) => match other.rep {
256             Small(_) => die(),
257             Big(ref s1) => match op {
258               Union      => s.union(s1,      self.nbits),
259               Intersect  => s.intersect(s1,  self.nbits),
260               Assign     => s.become(s1,     self.nbits),
261               Difference => s.difference(s1, self.nbits)
262             }
263           }
264         }
265     }
266
267 }
268
269 impl Bitv {
270     pub fn new(nbits: uint, init: bool) -> Bitv {
271         let rep = if nbits < uint::BITS {
272             Small(SmallBitv::new(if init {(1<<nbits)-1} else {0}))
273         } else if nbits == uint::BITS {
274             Small(SmallBitv::new(if init {!0} else {0}))
275         } else {
276             let exact = nbits % uint::BITS == 0;
277             let nelems = nbits/uint::BITS + if exact {0} else {1};
278             let s =
279                 if init {
280                     if exact {
281                         slice::from_elem(nelems, !0u)
282                     } else {
283                         let mut v = slice::from_elem(nelems-1, !0u);
284                         v.push((1<<nbits % uint::BITS)-1);
285                         v
286                     }
287                 } else { slice::from_elem(nelems, 0u)};
288             Big(BigBitv::new(s))
289         };
290         Bitv {rep: rep, nbits: nbits}
291     }
292
293     /**
294      * Calculates the union of two bitvectors
295      *
296      * Sets `self` to the union of `self` and `v1`. Both bitvectors must be
297      * the same length. Returns `true` if `self` changed.
298     */
299     #[inline]
300     pub fn union(&mut self, v1: &Bitv) -> bool { self.do_op(Union, v1) }
301
302     /**
303      * Calculates the intersection of two bitvectors
304      *
305      * Sets `self` to the intersection of `self` and `v1`. Both bitvectors
306      * must be the same length. Returns `true` if `self` changed.
307     */
308     #[inline]
309     pub fn intersect(&mut self, v1: &Bitv) -> bool {
310         self.do_op(Intersect, v1)
311     }
312
313     /**
314      * Assigns the value of `v1` to `self`
315      *
316      * Both bitvectors must be the same length. Returns `true` if `self` was
317      * changed
318      */
319     #[inline]
320     pub fn assign(&mut self, v: &Bitv) -> bool { self.do_op(Assign, v) }
321
322     /// Retrieve the value at index `i`
323     #[inline]
324     pub fn get(&self, i: uint) -> bool {
325         assert!((i < self.nbits));
326         match self.rep {
327             Big(ref b)   => b.get(i),
328             Small(ref s) => s.get(i)
329         }
330     }
331
332     /**
333      * Set the value of a bit at a given index
334      *
335      * `i` must be less than the length of the bitvector.
336      */
337     #[inline]
338     pub fn set(&mut self, i: uint, x: bool) {
339       assert!((i < self.nbits));
340       match self.rep {
341         Big(ref mut b)   => b.set(i, x),
342         Small(ref mut s) => s.set(i, x)
343       }
344     }
345
346     /**
347      * Compares two bitvectors
348      *
349      * Both bitvectors must be the same length. Returns `true` if both
350      * bitvectors contain identical elements.
351      */
352     #[inline]
353     pub fn equal(&self, v1: &Bitv) -> bool {
354       if self.nbits != v1.nbits { return false; }
355       match self.rep {
356         Small(ref b) => match v1.rep {
357           Small(ref b1) => b.equals(b1, self.nbits),
358           _ => false
359         },
360         Big(ref s) => match v1.rep {
361           Big(ref s1) => s.equals(s1, self.nbits),
362           Small(_) => return false
363         }
364       }
365     }
366
367     /// Set all bits to 0
368     #[inline]
369     pub fn clear(&mut self) {
370         match self.rep {
371             Small(ref mut b) => b.clear(),
372             Big(ref mut s) => {
373                 s.each_storage(|w| { *w = 0u; true });
374             }
375         }
376     }
377
378     /// Set all bits to 1
379     #[inline]
380     pub fn set_all(&mut self) {
381         match self.rep {
382             Small(ref mut b) => b.set_all(),
383             Big(ref mut s) => {
384                 s.each_storage(|w| { *w = !0u; true });
385             }
386         }
387     }
388
389     /// Flip all bits
390     #[inline]
391     pub fn negate(&mut self) {
392         match self.rep {
393             Small(ref mut s) => s.negate(),
394             Big(ref mut b) => b.negate(),
395         }
396     }
397
398     /**
399      * Calculate the difference between two bitvectors
400      *
401      * Sets each element of `v0` to the value of that element minus the
402      * element of `v1` at the same index. Both bitvectors must be the same
403      * length.
404      *
405      * Returns `true` if `v0` was changed.
406      */
407     #[inline]
408     pub fn difference(&mut self, v: &Bitv) -> bool {
409         self.do_op(Difference, v)
410     }
411
412     /// Returns `true` if all bits are 1
413     #[inline]
414     pub fn is_true(&self) -> bool {
415       match self.rep {
416         Small(ref b) => b.is_true(self.nbits),
417         _ => {
418           for i in self.iter() { if !i { return false; } }
419           true
420         }
421       }
422     }
423
424     #[inline]
425     pub fn iter<'a>(&'a self) -> Bits<'a> {
426         Bits {bitv: self, next_idx: 0, end_idx: self.nbits}
427     }
428
429     #[inline]
430     pub fn rev_iter<'a>(&'a self) -> Rev<Bits<'a>> {
431         self.iter().rev()
432     }
433
434     /// Returns `true` if all bits are 0
435     pub fn is_false(&self) -> bool {
436       match self.rep {
437         Small(ref b) => b.is_false(self.nbits),
438         Big(_) => {
439           for i in self.iter() { if i { return false; } }
440           true
441         }
442       }
443     }
444
445     pub fn init_to_vec(&self, i: uint) -> uint {
446       return if self.get(i) { 1 } else { 0 };
447     }
448
449     /**
450      * Converts `self` to a vector of `uint` with the same length.
451      *
452      * Each `uint` in the resulting vector has either value `0u` or `1u`.
453      */
454     pub fn to_vec(&self) -> ~[uint] {
455         slice::from_fn(self.nbits, |x| self.init_to_vec(x))
456     }
457
458     /**
459      * Organise the bits into bytes, such that the first bit in the
460      * `Bitv` becomes the high-order bit of the first byte. If the
461      * size of the `Bitv` is not a multiple of 8 then trailing bits
462      * will be filled-in with false/0
463      */
464     pub fn to_bytes(&self) -> ~[u8] {
465         fn bit (bitv: &Bitv, byte: uint, bit: uint) -> u8 {
466             let offset = byte * 8 + bit;
467             if offset >= bitv.nbits {
468                 0
469             } else {
470                 bitv[offset] as u8 << (7 - bit)
471             }
472         }
473
474         let len = self.nbits/8 +
475                   if self.nbits % 8 == 0 { 0 } else { 1 };
476         slice::from_fn(len, |i|
477             bit(self, i, 0) |
478             bit(self, i, 1) |
479             bit(self, i, 2) |
480             bit(self, i, 3) |
481             bit(self, i, 4) |
482             bit(self, i, 5) |
483             bit(self, i, 6) |
484             bit(self, i, 7)
485         )
486     }
487
488     /**
489      * Transform `self` into a `[bool]` by turning each bit into a `bool`.
490      */
491     pub fn to_bools(&self) -> ~[bool] {
492         slice::from_fn(self.nbits, |i| self[i])
493     }
494
495     /**
496      * Converts `self` to a string.
497      *
498      * The resulting string has the same length as `self`, and each
499      * character is either '0' or '1'.
500      */
501      pub fn to_str(&self) -> ~str {
502         let mut rs = ~"";
503         for i in self.iter() {
504             if i {
505                 rs.push_char('1');
506             } else {
507                 rs.push_char('0');
508             }
509         };
510         rs
511      }
512
513
514     /**
515      * Compare a bitvector to a vector of `bool`.
516      *
517      * Both the bitvector and vector must have the same length.
518      */
519     pub fn eq_vec(&self, v: &[bool]) -> bool {
520         assert_eq!(self.nbits, v.len());
521         let mut i = 0;
522         while i < self.nbits {
523             if self.get(i) != v[i] { return false; }
524             i = i + 1;
525         }
526         true
527     }
528
529     pub fn ones(&self, f: |uint| -> bool) -> bool {
530         range(0u, self.nbits).advance(|i| !self.get(i) || f(i))
531     }
532
533 }
534
535 /**
536  * Transform a byte-vector into a `Bitv`. Each byte becomes 8 bits,
537  * with the most significant bits of each byte coming first. Each
538  * bit becomes `true` if equal to 1 or `false` if equal to 0.
539  */
540 pub fn from_bytes(bytes: &[u8]) -> Bitv {
541     from_fn(bytes.len() * 8, |i| {
542         let b = bytes[i / 8] as uint;
543         let offset = i % 8;
544         b >> (7 - offset) & 1 == 1
545     })
546 }
547
548 /**
549  * Transform a `[bool]` into a `Bitv` by converting each `bool` into a bit.
550  */
551 pub fn from_bools(bools: &[bool]) -> Bitv {
552     from_fn(bools.len(), |i| bools[i])
553 }
554
555 /**
556  * Create a `Bitv` of the specified length where the value at each
557  * index is `f(index)`.
558  */
559 pub fn from_fn(len: uint, f: |index: uint| -> bool) -> Bitv {
560     let mut bitv = Bitv::new(len, false);
561     for i in range(0u, len) {
562         bitv.set(i, f(i));
563     }
564     bitv
565 }
566
567 impl ops::Index<uint,bool> for Bitv {
568     fn index(&self, i: &uint) -> bool {
569         self.get(*i)
570     }
571 }
572
573 #[inline]
574 fn iterate_bits(base: uint, bits: uint, f: |uint| -> bool) -> bool {
575     if bits == 0 {
576         return true;
577     }
578     for i in range(0u, uint::BITS) {
579         if bits & (1 << i) != 0 {
580             if !f(base + i) {
581                 return false;
582             }
583         }
584     }
585     return true;
586 }
587
588 /// An iterator for `Bitv`.
589 pub struct Bits<'a> {
590     priv bitv: &'a Bitv,
591     priv next_idx: uint,
592     priv end_idx: uint,
593 }
594
595 impl<'a> Iterator<bool> for Bits<'a> {
596     #[inline]
597     fn next(&mut self) -> Option<bool> {
598         if self.next_idx != self.end_idx {
599             let idx = self.next_idx;
600             self.next_idx += 1;
601             Some(self.bitv.get(idx))
602         } else {
603             None
604         }
605     }
606
607     fn size_hint(&self) -> (uint, Option<uint>) {
608         let rem = self.end_idx - self.next_idx;
609         (rem, Some(rem))
610     }
611 }
612
613 impl<'a> DoubleEndedIterator<bool> for Bits<'a> {
614     #[inline]
615     fn next_back(&mut self) -> Option<bool> {
616         if self.next_idx != self.end_idx {
617             self.end_idx -= 1;
618             Some(self.bitv.get(self.end_idx))
619         } else {
620             None
621         }
622     }
623 }
624
625 impl<'a> ExactSize<bool> for Bits<'a> {}
626
627 impl<'a> RandomAccessIterator<bool> for Bits<'a> {
628     #[inline]
629     fn indexable(&self) -> uint {
630         self.end_idx - self.next_idx
631     }
632
633     #[inline]
634     fn idx(&self, index: uint) -> Option<bool> {
635         if index >= self.indexable() {
636             None
637         } else {
638             Some(self.bitv.get(index))
639         }
640     }
641 }
642
643 /// An implementation of a set using a bit vector as an underlying
644 /// representation for holding numerical elements.
645 ///
646 /// It should also be noted that the amount of storage necessary for holding a
647 /// set of objects is proportional to the maximum of the objects when viewed
648 /// as a `uint`.
649 #[deriving(Clone)]
650 pub struct BitvSet {
651     priv size: uint,
652
653     // In theory this is a `Bitv` instead of always a `BigBitv`, but knowing that
654     // there's an array of storage makes our lives a whole lot easier when
655     // performing union/intersection/etc operations
656     priv bitv: BigBitv
657 }
658
659 impl BitvSet {
660     /// Creates a new bit vector set with initially no contents
661     pub fn new() -> BitvSet {
662         BitvSet{ size: 0, bitv: BigBitv::new(~[0]) }
663     }
664
665     /// Creates a new bit vector set from the given bit vector
666     pub fn from_bitv(bitv: Bitv) -> BitvSet {
667         let mut size = 0;
668         bitv.ones(|_| {
669             size += 1;
670             true
671         });
672         let Bitv{rep, ..} = bitv;
673         match rep {
674             Big(b) => BitvSet{ size: size, bitv: b },
675             Small(SmallBitv{bits}) =>
676                 BitvSet{ size: size, bitv: BigBitv{ storage: ~[bits] } },
677         }
678     }
679
680     /// Returns the capacity in bits for this bit vector. Inserting any
681     /// element less than this amount will not trigger a resizing.
682     pub fn capacity(&self) -> uint { self.bitv.storage.len() * uint::BITS }
683
684     /// Consumes this set to return the underlying bit vector
685     pub fn unwrap(self) -> Bitv {
686         let cap = self.capacity();
687         let BitvSet{bitv, ..} = self;
688         return Bitv{ nbits:cap, rep: Big(bitv) };
689     }
690
691     #[inline]
692     fn other_op(&mut self, other: &BitvSet, f: |uint, uint| -> uint) {
693         fn nbits(mut w: uint) -> uint {
694             let mut bits = 0;
695             for _ in range(0u, uint::BITS) {
696                 if w == 0 {
697                     break;
698                 }
699                 bits += w & 1;
700                 w >>= 1;
701             }
702             return bits;
703         }
704         if self.capacity() < other.capacity() {
705             self.bitv.storage.grow(other.capacity() / uint::BITS, &0);
706         }
707         for (i, &w) in other.bitv.storage.iter().enumerate() {
708             let old = self.bitv.storage[i];
709             let new = f(old, w);
710             self.bitv.storage[i] = new;
711             self.size += nbits(new) - nbits(old);
712         }
713     }
714
715     /// Union in-place with the specified other bit vector
716     pub fn union_with(&mut self, other: &BitvSet) {
717         self.other_op(other, |w1, w2| w1 | w2);
718     }
719
720     /// Intersect in-place with the specified other bit vector
721     pub fn intersect_with(&mut self, other: &BitvSet) {
722         self.other_op(other, |w1, w2| w1 & w2);
723     }
724
725     /// Difference in-place with the specified other bit vector
726     pub fn difference_with(&mut self, other: &BitvSet) {
727         self.other_op(other, |w1, w2| w1 & !w2);
728     }
729
730     /// Symmetric difference in-place with the specified other bit vector
731     pub fn symmetric_difference_with(&mut self, other: &BitvSet) {
732         self.other_op(other, |w1, w2| w1 ^ w2);
733     }
734
735     pub fn iter<'a>(&'a self) -> BitPositions<'a> {
736         BitPositions {set: self, next_idx: 0}
737     }
738
739     pub fn difference(&self, other: &BitvSet, f: |&uint| -> bool) -> bool {
740         for (i, w1, w2) in self.commons(other) {
741             if !iterate_bits(i, w1 & !w2, |b| f(&b)) {
742                 return false
743             }
744         };
745         /* everything we have that they don't also shows up */
746         self.outliers(other).advance(|(mine, i, w)|
747             !mine || iterate_bits(i, w, |b| f(&b))
748         )
749     }
750
751     pub fn symmetric_difference(&self, other: &BitvSet, f: |&uint| -> bool)
752                                 -> bool {
753         for (i, w1, w2) in self.commons(other) {
754             if !iterate_bits(i, w1 ^ w2, |b| f(&b)) {
755                 return false
756             }
757         };
758         self.outliers(other).advance(|(_, i, w)| iterate_bits(i, w, |b| f(&b)))
759     }
760
761     pub fn intersection(&self, other: &BitvSet, f: |&uint| -> bool) -> bool {
762         self.commons(other).advance(|(i, w1, w2)| iterate_bits(i, w1 & w2, |b| f(&b)))
763     }
764
765     pub fn union(&self, other: &BitvSet, f: |&uint| -> bool) -> bool {
766         for (i, w1, w2) in self.commons(other) {
767             if !iterate_bits(i, w1 | w2, |b| f(&b)) {
768                 return false
769             }
770         };
771         self.outliers(other).advance(|(_, i, w)| iterate_bits(i, w, |b| f(&b)))
772     }
773 }
774
775 impl cmp::Eq for BitvSet {
776     fn eq(&self, other: &BitvSet) -> bool {
777         if self.size != other.size {
778             return false;
779         }
780         for (_, w1, w2) in self.commons(other) {
781             if w1 != w2 {
782                 return false;
783             }
784         }
785         for (_, _, w) in self.outliers(other) {
786             if w != 0 {
787                 return false;
788             }
789         }
790         return true;
791     }
792
793     fn ne(&self, other: &BitvSet) -> bool { !self.eq(other) }
794 }
795
796 impl Container for BitvSet {
797     #[inline]
798     fn len(&self) -> uint { self.size }
799 }
800
801 impl Mutable for BitvSet {
802     fn clear(&mut self) {
803         self.bitv.each_storage(|w| { *w = 0; true });
804         self.size = 0;
805     }
806 }
807
808 impl Set<uint> for BitvSet {
809     fn contains(&self, value: &uint) -> bool {
810         *value < self.bitv.storage.len() * uint::BITS && self.bitv.get(*value)
811     }
812
813     fn is_disjoint(&self, other: &BitvSet) -> bool {
814         self.intersection(other, |_| false)
815     }
816
817     fn is_subset(&self, other: &BitvSet) -> bool {
818         for (_, w1, w2) in self.commons(other) {
819             if w1 & w2 != w1 {
820                 return false;
821             }
822         }
823         /* If anything is not ours, then everything is not ours so we're
824            definitely a subset in that case. Otherwise if there's any stray
825            ones that 'other' doesn't have, we're not a subset. */
826         for (mine, _, w) in self.outliers(other) {
827             if !mine {
828                 return true;
829             } else if w != 0 {
830                 return false;
831             }
832         }
833         return true;
834     }
835
836     fn is_superset(&self, other: &BitvSet) -> bool {
837         other.is_subset(self)
838     }
839 }
840
841 impl MutableSet<uint> for BitvSet {
842     fn insert(&mut self, value: uint) -> bool {
843         if self.contains(&value) {
844             return false;
845         }
846         let nbits = self.capacity();
847         if value >= nbits {
848             let newsize = cmp::max(value, nbits * 2) / uint::BITS + 1;
849             assert!(newsize > self.bitv.storage.len());
850             self.bitv.storage.grow(newsize, &0);
851         }
852         self.size += 1;
853         self.bitv.set(value, true);
854         return true;
855     }
856
857     fn remove(&mut self, value: &uint) -> bool {
858         if !self.contains(value) {
859             return false;
860         }
861         self.size -= 1;
862         self.bitv.set(*value, false);
863
864         // Attempt to truncate our storage
865         let mut i = self.bitv.storage.len();
866         while i > 1 && self.bitv.storage[i - 1] == 0 {
867             i -= 1;
868         }
869         self.bitv.storage.truncate(i);
870
871         return true;
872     }
873 }
874
875 impl BitvSet {
876     /// Visits each of the words that the two bit vectors (`self` and `other`)
877     /// both have in common. The three yielded arguments are (bit location,
878     /// w1, w2) where the bit location is the number of bits offset so far,
879     /// and w1/w2 are the words coming from the two vectors self, other.
880     fn commons<'a>(&'a self, other: &'a BitvSet)
881         -> Map<'static, ((uint, &'a uint), &'a ~[uint]), (uint, uint, uint),
882                Zip<Enumerate<slice::Items<'a, uint>>, Repeat<&'a ~[uint]>>> {
883         let min = cmp::min(self.bitv.storage.len(), other.bitv.storage.len());
884         self.bitv.storage.slice(0, min).iter().enumerate()
885             .zip(Repeat::new(&other.bitv.storage))
886             .map(|((i, &w), o_store)| (i * uint::BITS, w, o_store[i]))
887     }
888
889     /// Visits each word in `self` or `other` that extends beyond the other. This
890     /// will only iterate through one of the vectors, and it only iterates
891     /// over the portion that doesn't overlap with the other one.
892     ///
893     /// The yielded arguments are a `bool`, the bit offset, and a word. The `bool`
894     /// is true if the word comes from `self`, and `false` if it comes from
895     /// `other`.
896     fn outliers<'a>(&'a self, other: &'a BitvSet)
897         -> Map<'static, ((uint, &'a uint), uint), (bool, uint, uint),
898                Zip<Enumerate<slice::Items<'a, uint>>, Repeat<uint>>> {
899         let slen = self.bitv.storage.len();
900         let olen = other.bitv.storage.len();
901
902         if olen < slen {
903             self.bitv.storage.slice_from(olen).iter().enumerate()
904                 .zip(Repeat::new(olen))
905                 .map(|((i, &w), min)| (true, (i + min) * uint::BITS, w))
906         } else {
907             other.bitv.storage.slice_from(slen).iter().enumerate()
908                 .zip(Repeat::new(slen))
909                 .map(|((i, &w), min)| (false, (i + min) * uint::BITS, w))
910         }
911     }
912 }
913
914 pub struct BitPositions<'a> {
915     priv set: &'a BitvSet,
916     priv next_idx: uint
917 }
918
919 impl<'a> Iterator<uint> for BitPositions<'a> {
920     #[inline]
921     fn next(&mut self) -> Option<uint> {
922         while self.next_idx < self.set.capacity() {
923             let idx = self.next_idx;
924             self.next_idx += 1;
925
926             if self.set.contains(&idx) {
927                 return Some(idx);
928             }
929         }
930
931         return None;
932     }
933
934     fn size_hint(&self) -> (uint, Option<uint>) {
935         (0, Some(self.set.capacity() - self.next_idx))
936     }
937 }
938
939 #[cfg(test)]
940 mod tests {
941     extern crate test;
942     use self::test::BenchHarness;
943
944     use bitv::{Bitv, SmallBitv, BigBitv, BitvSet, from_bools, from_fn,
945                from_bytes};
946     use bitv;
947
948     use std::uint;
949     use std::slice;
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(), ~"");
959
960         let eightbits = Bitv::new(8u, false);
961         assert_eq!(eightbits.to_str(), ~"00000000");
962     }
963
964     #[test]
965     fn test_0_elements() {
966         let act = Bitv::new(0u, false);
967         let exp = slice::from_elem::<bool>(0u, false);
968         assert!(act.eq_vec(exp));
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");
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" + "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(), ~[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(), ~[0b00100000, 0b10000000]);
1308     }
1309
1310     #[test]
1311     fn test_from_bools() {
1312         assert!(from_bools([true, false, true, true]).to_str() ==
1313             ~"1011");
1314     }
1315
1316     #[test]
1317     fn test_to_bools() {
1318         let bools = ~[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: ~[uint] = bitv.iter().collect();
1338         assert_eq!(idxs, ~[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     fn rng() -> rand::IsaacRng {
1555         let seed = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
1556         rand::SeedableRng::from_seed(seed)
1557     }
1558
1559     #[bench]
1560     fn bench_uint_small(b: &mut BenchHarness) {
1561         let mut r = rng();
1562         let mut bitv = 0 as uint;
1563         b.iter(|| {
1564             bitv |= 1 << ((r.next_u32() as uint) % uint::BITS);
1565             &bitv
1566         })
1567     }
1568
1569     #[bench]
1570     fn bench_small_bitv_small(b: &mut BenchHarness) {
1571         let mut r = rng();
1572         let mut bitv = SmallBitv::new(uint::BITS);
1573         b.iter(|| {
1574             bitv.set((r.next_u32() as uint) % uint::BITS, true);
1575             &bitv
1576         })
1577     }
1578
1579     #[bench]
1580     fn bench_big_bitv_small(b: &mut BenchHarness) {
1581         let mut r = rng();
1582         let mut bitv = BigBitv::new(~[0]);
1583         b.iter(|| {
1584             bitv.set((r.next_u32() as uint) % uint::BITS, true);
1585             &bitv
1586         })
1587     }
1588
1589     #[bench]
1590     fn bench_big_bitv_big(b: &mut BenchHarness) {
1591         let mut r = rng();
1592         let mut storage = ~[];
1593         storage.grow(BENCH_BITS / uint::BITS, &0u);
1594         let mut bitv = BigBitv::new(storage);
1595         b.iter(|| {
1596             bitv.set((r.next_u32() as uint) % BENCH_BITS, true);
1597             &bitv
1598         })
1599     }
1600
1601     #[bench]
1602     fn bench_bitv_big(b: &mut BenchHarness) {
1603         let mut r = rng();
1604         let mut bitv = Bitv::new(BENCH_BITS, false);
1605         b.iter(|| {
1606             bitv.set((r.next_u32() as uint) % BENCH_BITS, true);
1607             &bitv
1608         })
1609     }
1610
1611     #[bench]
1612     fn bench_bitv_small(b: &mut BenchHarness) {
1613         let mut r = rng();
1614         let mut bitv = Bitv::new(uint::BITS, false);
1615         b.iter(|| {
1616             bitv.set((r.next_u32() as uint) % uint::BITS, true);
1617             &bitv
1618         })
1619     }
1620
1621     #[bench]
1622     fn bench_bitv_set_small(b: &mut BenchHarness) {
1623         let mut r = rng();
1624         let mut bitv = BitvSet::new();
1625         b.iter(|| {
1626             bitv.insert((r.next_u32() as uint) % uint::BITS);
1627             &bitv
1628         })
1629     }
1630
1631     #[bench]
1632     fn bench_bitv_set_big(b: &mut BenchHarness) {
1633         let mut r = rng();
1634         let mut bitv = BitvSet::new();
1635         b.iter(|| {
1636             bitv.insert((r.next_u32() as uint) % BENCH_BITS);
1637             &bitv
1638         })
1639     }
1640
1641     #[bench]
1642     fn bench_bitv_big_union(b: &mut BenchHarness) {
1643         let mut b1 = Bitv::new(BENCH_BITS, false);
1644         let b2 = Bitv::new(BENCH_BITS, false);
1645         b.iter(|| {
1646             b1.union(&b2);
1647         })
1648     }
1649
1650     #[bench]
1651     fn bench_btv_small_iter(b: &mut BenchHarness) {
1652         let bitv = Bitv::new(uint::BITS, false);
1653         b.iter(|| {
1654             let mut _sum = 0;
1655             for pres in bitv.iter() {
1656                 _sum += pres as uint;
1657             }
1658         })
1659     }
1660
1661     #[bench]
1662     fn bench_bitv_big_iter(b: &mut BenchHarness) {
1663         let bitv = Bitv::new(BENCH_BITS, false);
1664         b.iter(|| {
1665             let mut _sum = 0;
1666             for pres in bitv.iter() {
1667                 _sum += pres as uint;
1668             }
1669         })
1670     }
1671
1672     #[bench]
1673     fn bench_bitvset_iter(b: &mut BenchHarness) {
1674         let bitv = BitvSet::from_bitv(from_fn(BENCH_BITS,
1675                                               |idx| {idx % 3 == 0}));
1676         b.iter(|| {
1677             let mut _sum = 0;
1678             for idx in bitv.iter() {
1679                 _sum += idx;
1680             }
1681         })
1682     }
1683 }