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