bit.rs 87.2 KB
Newer Older
C
Chris Wong 已提交
1
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

T
Tobias Bucher 已提交
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
// FIXME(Gankro): Bitv and BitvSet are very tightly coupled. Ideally (for
// maintenance), they should be in separate files/modules, with BitvSet only
// using Bitv's public API. This will be hard for performance though, because
// `Bitv` will not want to leak its internal representation while its internal
// representation as `u32`s must be assumed for best performance.

// FIXME(tbu-): `Bitv`'s methods shouldn't be `union`, `intersection`, but
// rather `or` and `and`.

// (1) Be careful, most things can overflow here because the amount of bits in
//     memory can overflow `uint`.
// (2) Make sure that the underlying vector has no excess length:
//     E. g. `nbits == 16`, `storage.len() == 2` would be excess length,
//     because the last word isn't used at all. This is important because some
//     methods rely on it (for *CORRECTNESS*).
// (3) Make sure that the unused bits in the last word are zeroed out, again
//     other methods rely on it for *CORRECTNESS*.
// (4) `BitvSet` is tightly coupled with `Bitv`, so any changes you make in
// `Bitv` will need to be reflected in `BitvSet`.
30

J
Jonas Hietala 已提交
31 32
//! Collections implemented with bit vectors.
//!
33
//! # Examples
J
Jonas Hietala 已提交
34 35 36 37 38 39 40 41
//!
//! This is a simple example of the [Sieve of Eratosthenes][sieve]
//! which calculates prime numbers up to a given limit.
//!
//! [sieve]: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
//!
//! ```
//! use std::collections::{BitvSet, Bitv};
42
//! use std::num::Float;
J
Jonas Hietala 已提交
43 44 45 46 47 48
//! use std::iter;
//!
//! let max_prime = 10000;
//!
//! // Store the primes as a BitvSet
//! let primes = {
J
Jonas Hietala 已提交
49 50
//!     // Assume all numbers are prime to begin, and then we
//!     // cross off non-primes progressively
51
//!     let mut bv = Bitv::from_elem(max_prime, true);
J
Jonas Hietala 已提交
52 53 54 55 56
//!
//!     // Neither 0 nor 1 are prime
//!     bv.set(0, false);
//!     bv.set(1, false);
//!
57
//!     for i in iter::range_inclusive(2, (max_prime as f64).sqrt() as uint) {
J
Jonas Hietala 已提交
58
//!         // if i is a prime
J
Jonas Hietala 已提交
59 60
//!         if bv[i] {
//!             // Mark all multiples of i as non-prime (any multiples below i * i
J
Jonas Hietala 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
//!             // will have been marked as non-prime previously)
//!             for j in iter::range_step(i * i, max_prime, i) { bv.set(j, false) }
//!         }
//!     }
//!     BitvSet::from_bitv(bv)
//! };
//!
//! // Simple primality tests below our max bound
//! let print_primes = 20;
//! print!("The primes below {} are: ", print_primes);
//! for x in range(0, print_primes) {
//!     if primes.contains(&x) {
//!         print!("{} ", x);
//!     }
//! }
//! println!("");
//!
//! // We can manipulate the internal Bitv
//! let num_primes = primes.get_ref().iter().filter(|x| *x).count();
//! println!("There are {} primes below {}", num_primes, max_prime);
//! ```

83
use core::prelude::*;
84

85
use core::cmp::Ordering;
86
use core::cmp;
87
use core::default::Default;
88
use core::fmt;
89
use core::hash;
A
Alex Crichton 已提交
90 91
use core::iter::RandomAccessIterator;
use core::iter::{Chain, Enumerate, Repeat, Skip, Take, repeat, Cloned};
92
use core::iter::{self, FromIterator};
93
use core::num::Int;
94
use core::ops::Index;
95
use core::slice;
T
Tobias Bucher 已提交
96
use core::{u8, u32, uint};
A
Alexis Beingessner 已提交
97
use bitv_set; //so meta
98

T
Tobias Bucher 已提交
99
use Vec;
100

A
Alexis Beingessner 已提交
101 102
type Blocks<'a> = Cloned<slice::Iter<'a, u32>>;
type MutBlocks<'a> = slice::IterMut<'a, u32>;
103
type MatchWords<'a> = Chain<Enumerate<Blocks<'a>>, Skip<Take<Enumerate<Repeat<u32>>>>>;
104

105 106 107 108 109 110 111
fn reverse_bits(byte: u8) -> u8 {
    let mut result = 0;
    for i in range(0, u8::BITS) {
        result |= ((byte >> i) & 1) << (u8::BITS - 1 - i);
    }
    result
}
112

113 114
// Take two BitV's, and return iterators of their words, where the shorter one
// has been padded with 0's
115 116 117 118 119 120
fn match_words <'a,'b>(a: &'a Bitv, b: &'b Bitv) -> (MatchWords<'a>, MatchWords<'b>) {
    let a_len = a.storage.len();
    let b_len = b.storage.len();

    // have to uselessly pretend to pad the longer one for type matching
    if a_len < b_len {
121 122
        (a.blocks().enumerate().chain(iter::repeat(0u32).enumerate().take(b_len).skip(a_len)),
         b.blocks().enumerate().chain(iter::repeat(0u32).enumerate().take(0).skip(0)))
123
    } else {
124 125
        (a.blocks().enumerate().chain(iter::repeat(0u32).enumerate().take(0).skip(0)),
         b.blocks().enumerate().chain(iter::repeat(0u32).enumerate().take(a_len).skip(b_len)))
126 127
    }
}
128 129 130 131

static TRUE: bool = true;
static FALSE: bool = false;

P
P1start 已提交
132
/// The bitvector type.
J
Joseph Crail 已提交
133
///
134
/// # Examples
J
Joseph Crail 已提交
135 136
///
/// ```rust
137
/// use collections::Bitv;
J
Joseph Crail 已提交
138
///
139
/// let mut bv = Bitv::from_elem(10, false);
J
Joseph Crail 已提交
140 141 142 143 144 145
///
/// // insert all primes less than 10
/// bv.set(2, true);
/// bv.set(3, true);
/// bv.set(5, true);
/// bv.set(7, true);
A
Alex Crichton 已提交
146
/// println!("{:?}", bv);
A
Aaron Turon 已提交
147
/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
J
Joseph Crail 已提交
148 149 150
///
/// // flip all values in bitvector, producing non-primes less than 10
/// bv.negate();
A
Alex Crichton 已提交
151
/// println!("{:?}", bv);
A
Aaron Turon 已提交
152
/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
J
Joseph Crail 已提交
153 154 155
///
/// // reset bitvector to empty
/// bv.clear();
A
Alex Crichton 已提交
156
/// println!("{:?}", bv);
A
Aaron Turon 已提交
157
/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
J
Joseph Crail 已提交
158
/// ```
A
Alexis Beingessner 已提交
159
#[stable]
160
pub struct Bitv {
161
    /// Internal representation of the bit vector
162
    storage: Vec<u32>,
163
    /// The number of valid bits in the internal representation
164
    nbits: uint
165
}
166

J
Jorge Aparicio 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180
// FIXME(Gankro): NopeNopeNopeNopeNope (wait for IndexGet to be a thing)
impl Index<uint> for Bitv {
    type Output = bool;

    #[inline]
    fn index(&self, i: &uint) -> &bool {
        if self.get(*i).expect("index out of bounds") {
            &TRUE
        } else {
            &FALSE
        }
    }
}

181 182 183 184 185 186 187 188 189 190 191 192 193 194
/// Computes how many blocks are needed to store that many bits
fn blocks_for_bits(bits: uint) -> uint {
    // If we want 17 bits, dividing by 32 will produce 0. So we add 1 to make sure we
    // reserve enough. But if we want exactly a multiple of 32, this will actually allocate
    // one too many. So we need to check if that's the case. We can do that by computing if
    // bitwise AND by `32 - 1` is 0. But LLVM should be able to optimize the semantically
    // superior modulo operator on a power of two to this.
    //
    // Note that we can technically avoid this branch with the expression
    // `(nbits + u32::BITS - 1) / 32::BITS`, but if nbits is almost uint::MAX this will overflow.
    if bits % u32::BITS == 0 {
        bits / u32::BITS
    } else {
        bits / u32::BITS + 1
195 196 197
    }
}

198 199 200 201
/// Computes the bitmask for the final word of the vector
fn mask_for_bits(bits: uint) -> u32 {
    // Note especially that a perfect multiple of u32::BITS should mask all 1s.
    !0u32 >> (u32::BITS - bits % u32::BITS) % u32::BITS
202 203
}

204
impl Bitv {
T
Tobias Bucher 已提交
205 206 207
    /// Applies the given operation to the blocks of self and other, and sets
    /// self to be the result. This relies on the caller not to corrupt the
    /// last word.
208
    #[inline]
209
    fn process<F>(&mut self, other: &Bitv, mut op: F) -> bool where F: FnMut(u32, u32) -> u32 {
T
Tobias Bucher 已提交
210 211 212
        assert_eq!(self.len(), other.len());
        // This could theoretically be a `debug_assert!`.
        assert_eq!(self.storage.len(), other.storage.len());
213
        let mut changed = false;
214
        for (a, b) in self.blocks_mut().zip(other.blocks()) {
215 216
            let w = op(*a, b);
            if *a != w {
217 218
                changed = true;
                *a = w;
219 220
            }
        }
221
        changed
222
    }
223

224 225
    /// Iterator over mutable refs to  the underlying blocks of data.
    fn blocks_mut(&mut self) -> MutBlocks {
T
Tobias Bucher 已提交
226 227
        // (2)
        self.storage.iter_mut()
228 229 230 231
    }

    /// Iterator over the underlying blocks of data
    fn blocks(&self) -> Blocks {
T
Tobias Bucher 已提交
232 233
        // (2)
        self.storage.iter().cloned()
234 235
    }

T
Tobias Bucher 已提交
236 237
    /// An operation might screw up the unused bits in the last block of the
    /// `Bitv`. As per (3), it's assumed to be all 0s. This method fixes it up.
238
    fn fix_last_block(&mut self) {
T
Tobias Bucher 已提交
239
        let extra_bits = self.len() % u32::BITS;
240 241 242 243
        if extra_bits > 0 {
            let mask = (1 << extra_bits) - 1;
            let storage_len = self.storage.len();
            self.storage[storage_len - 1] &= mask;
244 245
        }
    }
246

P
P1start 已提交
247
    /// Creates an empty `Bitv`.
J
Jonas Hietala 已提交
248
    ///
249
    /// # Examples
J
Jonas Hietala 已提交
250 251 252 253 254
    ///
    /// ```
    /// use std::collections::Bitv;
    /// let mut bv = Bitv::new();
    /// ```
A
Alexis Beingessner 已提交
255
    #[stable]
256 257 258 259
    pub fn new() -> Bitv {
        Bitv { storage: Vec::new(), nbits: 0 }
    }

P
P1start 已提交
260
    /// Creates a `Bitv` that holds `nbits` elements, setting each element
261
    /// to `bit`.
J
Jonas Hietala 已提交
262
    ///
263
    /// # Examples
J
Jonas Hietala 已提交
264 265 266 267
    ///
    /// ```
    /// use std::collections::Bitv;
    ///
268
    /// let mut bv = Bitv::from_elem(10u, false);
J
Jonas Hietala 已提交
269 270 271 272 273
    /// assert_eq!(bv.len(), 10u);
    /// for x in bv.iter() {
    ///     assert_eq!(x, false);
    /// }
    /// ```
274 275
    pub fn from_elem(nbits: uint, bit: bool) -> Bitv {
        let nblocks = blocks_for_bits(nbits);
276
        let mut bitv = Bitv {
A
Aaron Turon 已提交
277
            storage: repeat(if bit { !0u32 } else { 0u32 }).take(nblocks).collect(),
278
            nbits: nbits
279
        };
280 281 282 283 284 285 286 287 288 289 290
        bitv.fix_last_block();
        bitv
    }

    /// Constructs a new, empty `Bitv` with the specified capacity.
    ///
    /// The bitvector will be able to hold at least `capacity` bits without
    /// reallocating. If `capacity` is 0, it will not allocate.
    ///
    /// It is important to note that this function does not specify the
    /// *length* of the returned bitvector, but only the *capacity*.
A
Alexis Beingessner 已提交
291
    #[stable]
292 293 294 295
    pub fn with_capacity(nbits: uint) -> Bitv {
        Bitv {
            storage: Vec::with_capacity(blocks_for_bits(nbits)),
            nbits: 0,
296
        }
297
    }
298

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
    /// Transforms a byte-vector into a `Bitv`. Each byte becomes eight bits,
    /// with the most significant bits of each byte coming first. Each
    /// bit becomes `true` if equal to 1 or `false` if equal to 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::Bitv;
    ///
    /// let bv = Bitv::from_bytes(&[0b10100000, 0b00010010]);
    /// assert!(bv.eq_vec(&[true, false, true, false,
    ///                     false, false, false, false,
    ///                     false, false, false, true,
    ///                     false, false, true, false]));
    /// ```
    pub fn from_bytes(bytes: &[u8]) -> Bitv {
T
Tobias Bucher 已提交
315 316 317 318 319
        let len = bytes.len().checked_mul(u8::BITS).expect("capacity overflow");
        let mut bitv = Bitv::with_capacity(len);
        let complete_words = bytes.len() / 4;
        let extra_bytes = bytes.len() % 4;

320 321
        bitv.nbits = len;

T
Tobias Bucher 已提交
322 323
        for i in range(0, complete_words) {
            bitv.storage.push(
324 325 326 327
                ((reverse_bits(bytes[i * 4 + 0]) as u32) << 0) |
                ((reverse_bits(bytes[i * 4 + 1]) as u32) << 8) |
                ((reverse_bits(bytes[i * 4 + 2]) as u32) << 16) |
                ((reverse_bits(bytes[i * 4 + 3]) as u32) << 24)
T
Tobias Bucher 已提交
328 329
            );
        }
330

T
Tobias Bucher 已提交
331 332
        if extra_bytes > 0 {
            let mut last_word = 0u32;
333
            for (i, &byte) in bytes.index(&((complete_words*4)..)).iter().enumerate() {
334
                last_word |= (reverse_bits(byte) as u32) << (i * 8);
T
Tobias Bucher 已提交
335 336
            }
            bitv.storage.push(last_word);
337
        }
338 339

        bitv
340
    }
341

T
Tobias Bucher 已提交
342 343
    /// Creates a `Bitv` of the specified length where the value at each index
    /// is `f(index)`.
J
Jonas Hietala 已提交
344
    ///
345
    /// # Examples
J
Jonas Hietala 已提交
346
    ///
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    /// ```
    /// use std::collections::Bitv;
    ///
    /// let bv = Bitv::from_fn(5, |i| { i % 2 == 0 });
    /// assert!(bv.eq_vec(&[true, false, true, false, true]));
    /// ```
    pub fn from_fn<F>(len: uint, mut f: F) -> Bitv where F: FnMut(uint) -> bool {
        let mut bitv = Bitv::from_elem(len, false);
        for i in range(0u, len) {
            bitv.set(i, f(i));
        }
        bitv
    }

    /// Retrieves the value at index `i`, or `None` if the index is out of bounds.
J
Jonas Hietala 已提交
362
    ///
363
    /// # Examples
J
Jonas Hietala 已提交
364 365
    ///
    /// ```
366
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
367
    ///
368 369 370 371
    /// let bv = Bitv::from_bytes(&[0b01100000]);
    /// assert_eq!(bv.get(0), Some(false));
    /// assert_eq!(bv.get(1), Some(true));
    /// assert_eq!(bv.get(100), None);
J
Jonas Hietala 已提交
372 373 374
    ///
    /// // Can also use array indexing
    /// assert_eq!(bv[1], true);
J
Jonas Hietala 已提交
375
    /// ```
376
    #[inline]
A
Alexis Beingessner 已提交
377
    #[stable]
378
    pub fn get(&self, i: uint) -> Option<bool> {
T
Tobias Bucher 已提交
379 380 381
        if i >= self.nbits {
            return None;
        }
382 383
        let w = i / u32::BITS;
        let b = i % u32::BITS;
J
Josh Stone 已提交
384
        self.storage.get(w).map(|&block|
385 386
            (block & (1 << b)) != 0
        )
387
    }
388

389
    /// Sets the value of a bit at an index `i`.
J
Jonas Hietala 已提交
390
    ///
391
    /// # Panics
J
Jonas Hietala 已提交
392
    ///
393
    /// Panics if `i` is out of bounds.
J
Jonas Hietala 已提交
394
    ///
395
    /// # Examples
J
Jonas Hietala 已提交
396 397 398 399
    ///
    /// ```
    /// use std::collections::Bitv;
    ///
400
    /// let mut bv = Bitv::from_elem(5, false);
J
Jonas Hietala 已提交
401
    /// bv.set(3, true);
J
Jonas Hietala 已提交
402
    /// assert_eq!(bv[3], true);
J
Jonas Hietala 已提交
403
    /// ```
404
    #[inline]
405
    #[unstable = "panic semantics are likely to change in the future"]
406
    pub fn set(&mut self, i: uint, x: bool) {
407
        assert!(i < self.nbits);
408 409
        let w = i / u32::BITS;
        let b = i % u32::BITS;
410
        let flag = 1 << b;
411 412 413
        let val = if x { self.storage[w] | flag }
                  else { self.storage[w] & !flag };
        self.storage[w] = val;
414
    }
415

P
P1start 已提交
416
    /// Sets all bits to 1.
J
Jonas Hietala 已提交
417
    ///
418
    /// # Examples
J
Jonas Hietala 已提交
419 420
    ///
    /// ```
421
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
422
    ///
423 424 425
    /// let before = 0b01100000;
    /// let after  = 0b11111111;
    ///
426
    /// let mut bv = Bitv::from_bytes(&[before]);
J
Jonas Hietala 已提交
427
    /// bv.set_all();
428
    /// assert_eq!(bv, Bitv::from_bytes(&[after]));
429
    /// ```
430
    #[inline]
431
    pub fn set_all(&mut self) {
432
        for w in self.storage.iter_mut() { *w = !0u32; }
433
        self.fix_last_block();
434
    }
435

P
P1start 已提交
436
    /// Flips all bits.
J
Jonas Hietala 已提交
437
    ///
438
    /// # Examples
J
Jonas Hietala 已提交
439 440
    ///
    /// ```
441
    /// use std::collections::Bitv;
442 443 444
    ///
    /// let before = 0b01100000;
    /// let after  = 0b10011111;
J
Jonas Hietala 已提交
445
    ///
446
    /// let mut bv = Bitv::from_bytes(&[before]);
J
Jonas Hietala 已提交
447
    /// bv.negate();
448
    /// assert_eq!(bv, Bitv::from_bytes(&[after]));
449
    /// ```
450
    #[inline]
D
Daniel Micay 已提交
451
    pub fn negate(&mut self) {
A
Aaron Turon 已提交
452
        for w in self.storage.iter_mut() { *w = !*w; }
453
        self.fix_last_block();
454
    }
455

P
P1start 已提交
456 457
    /// Calculates the union of two bitvectors. This acts like the bitwise `or`
    /// function.
J
Jonas Hietala 已提交
458
    ///
P
P1start 已提交
459 460
    /// Sets `self` to the union of `self` and `other`. Both bitvectors must be
    /// the same length. Returns `true` if `self` changed.
J
Jonas Hietala 已提交
461
    ///
462
    /// # Panics
J
Jonas Hietala 已提交
463
    ///
464
    /// Panics if the bitvectors are of different lengths.
J
Jonas Hietala 已提交
465
    ///
466
    /// # Examples
J
Jonas Hietala 已提交
467 468
    ///
    /// ```
469
    /// use std::collections::Bitv;
470 471 472 473
    ///
    /// let a   = 0b01100100;
    /// let b   = 0b01011010;
    /// let res = 0b01111110;
J
Jonas Hietala 已提交
474
    ///
475 476
    /// let mut a = Bitv::from_bytes(&[a]);
    /// let b = Bitv::from_bytes(&[b]);
J
Jonas Hietala 已提交
477
    ///
478
    /// assert!(a.union(&b));
479
    /// assert_eq!(a, Bitv::from_bytes(&[res]));
J
Jonas Hietala 已提交
480
    /// ```
481 482 483 484 485
    #[inline]
    pub fn union(&mut self, other: &Bitv) -> bool {
        self.process(other, |w1, w2| w1 | w2)
    }

P
P1start 已提交
486 487
    /// Calculates the intersection of two bitvectors. This acts like the
    /// bitwise `and` function.
J
Jonas Hietala 已提交
488
    ///
P
P1start 已提交
489 490
    /// Sets `self` to the intersection of `self` and `other`. Both bitvectors
    /// must be the same length. Returns `true` if `self` changed.
J
Jonas Hietala 已提交
491
    ///
492
    /// # Panics
J
Jonas Hietala 已提交
493
    ///
494
    /// Panics if the bitvectors are of different lengths.
J
Jonas Hietala 已提交
495
    ///
496
    /// # Examples
J
Jonas Hietala 已提交
497 498
    ///
    /// ```
499
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
500
    ///
501 502 503
    /// let a   = 0b01100100;
    /// let b   = 0b01011010;
    /// let res = 0b01000000;
J
Jonas Hietala 已提交
504
    ///
505 506
    /// let mut a = Bitv::from_bytes(&[a]);
    /// let b = Bitv::from_bytes(&[b]);
507 508
    ///
    /// assert!(a.intersect(&b));
509
    /// assert_eq!(a, Bitv::from_bytes(&[res]));
J
Jonas Hietala 已提交
510
    /// ```
511 512 513 514 515
    #[inline]
    pub fn intersect(&mut self, other: &Bitv) -> bool {
        self.process(other, |w1, w2| w1 & w2)
    }

P
P1start 已提交
516
    /// Calculates the difference between two bitvectors.
J
Jonas Hietala 已提交
517
    ///
P
P1start 已提交
518
    /// Sets each element of `self` to the value of that element minus the
J
Jonas Hietala 已提交
519
    /// element of `other` at the same index. Both bitvectors must be the same
P
P1start 已提交
520
    /// length. Returns `true` if `self` changed.
J
Jonas Hietala 已提交
521
    ///
522
    /// # Panics
J
Jonas Hietala 已提交
523
    ///
524
    /// Panics if the bitvectors are of different length.
J
Jonas Hietala 已提交
525
    ///
526
    /// # Examples
J
Jonas Hietala 已提交
527 528
    ///
    /// ```
529
    /// use std::collections::Bitv;
530 531 532 533 534 535
    ///
    /// let a   = 0b01100100;
    /// let b   = 0b01011010;
    /// let a_b = 0b00100100; // a - b
    /// let b_a = 0b00011010; // b - a
    ///
536 537
    /// let mut bva = Bitv::from_bytes(&[a]);
    /// let bvb = Bitv::from_bytes(&[b]);
J
Jonas Hietala 已提交
538
    ///
539
    /// assert!(bva.difference(&bvb));
540
    /// assert_eq!(bva, Bitv::from_bytes(&[a_b]));
J
Jonas Hietala 已提交
541
    ///
542 543
    /// let bva = Bitv::from_bytes(&[a]);
    /// let mut bvb = Bitv::from_bytes(&[b]);
544 545
    ///
    /// assert!(bvb.difference(&bva));
546
    /// assert_eq!(bvb, Bitv::from_bytes(&[b_a]));
J
Jonas Hietala 已提交
547
    /// ```
548
    #[inline]
549
    pub fn difference(&mut self, other: &Bitv) -> bool {
550
        self.process(other, |w1, w2| w1 & !w2)
551
    }
552

J
Jonas Hietala 已提交
553 554
    /// Returns `true` if all bits are 1.
    ///
555
    /// # Examples
J
Jonas Hietala 已提交
556 557
    ///
    /// ```
558
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
559
    ///
560
    /// let mut bv = Bitv::from_elem(5, true);
J
Jonas Hietala 已提交
561 562 563 564 565
    /// assert_eq!(bv.all(), true);
    ///
    /// bv.set(1, false);
    /// assert_eq!(bv.all(), false);
    /// ```
566
    pub fn all(&self) -> bool {
567
        let mut last_word = !0u32;
568 569 570 571 572 573
        // Check that every block but the last is all-ones...
        self.blocks().all(|elem| {
            let tmp = last_word;
            last_word = elem;
            tmp == !0u32
        // and then check the last one has enough ones
574
        }) && (last_word == mask_for_bits(self.nbits))
575
    }
576

P
P1start 已提交
577
    /// Returns an iterator over the elements of the vector in order.
J
Joseph Crail 已提交
578
    ///
579
    /// # Examples
J
Joseph Crail 已提交
580
    ///
J
Jonas Hietala 已提交
581
    /// ```
582
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
583
    ///
584
    /// let bv = Bitv::from_bytes(&[0b01110100, 0b10010010]);
585
    /// assert_eq!(bv.iter().filter(|x| *x).count(), 7);
J
Joseph Crail 已提交
586
    /// ```
587
    #[inline]
A
Alexis Beingessner 已提交
588 589 590
    #[stable]
    pub fn iter(&self) -> Iter {
        Iter { bitv: self, next_idx: 0, end_idx: self.nbits }
A
Alex Crichton 已提交
591
    }
592

P
P1start 已提交
593
    /// Returns `true` if all bits are 0.
J
Jonas Hietala 已提交
594
    ///
595
    /// # Examples
J
Jonas Hietala 已提交
596 597
    ///
    /// ```
598
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
599
    ///
600
    /// let mut bv = Bitv::from_elem(10, false);
J
Jonas Hietala 已提交
601 602 603 604 605
    /// assert_eq!(bv.none(), true);
    ///
    /// bv.set(3, true);
    /// assert_eq!(bv.none(), false);
    /// ```
606
    pub fn none(&self) -> bool {
607
        self.blocks().all(|w| w == 0)
608
    }
609

P
P1start 已提交
610
    /// Returns `true` if any bit is 1.
J
Jonas Hietala 已提交
611
    ///
612
    /// # Examples
J
Jonas Hietala 已提交
613 614
    ///
    /// ```
615
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
616
    ///
617
    /// let mut bv = Bitv::from_elem(10, false);
J
Jonas Hietala 已提交
618 619 620 621 622
    /// assert_eq!(bv.any(), false);
    ///
    /// bv.set(3, true);
    /// assert_eq!(bv.any(), true);
    /// ```
623 624 625 626 627
    #[inline]
    pub fn any(&self) -> bool {
        !self.none()
    }

P
P1start 已提交
628
    /// Organises the bits into bytes, such that the first bit in the
J
Jonas Hietala 已提交
629
    /// `Bitv` becomes the high-order bit of the first byte. If the
P
P1start 已提交
630
    /// size of the `Bitv` is not a multiple of eight then trailing bits
J
Jonas Hietala 已提交
631
    /// will be filled-in with `false`.
J
Jonas Hietala 已提交
632
    ///
633
    /// # Examples
J
Jonas Hietala 已提交
634 635
    ///
    /// ```
636
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
637
    ///
638
    /// let mut bv = Bitv::from_elem(3, true);
J
Jonas Hietala 已提交
639 640 641 642
    /// bv.set(1, false);
    ///
    /// assert_eq!(bv.to_bytes(), vec!(0b10100000));
    ///
643
    /// let mut bv = Bitv::from_elem(9, false);
J
Jonas Hietala 已提交
644 645 646 647 648
    /// bv.set(2, true);
    /// bv.set(8, true);
    ///
    /// assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000));
    /// ```
649
    pub fn to_bytes(&self) -> Vec<u8> {
T
Tobias Bucher 已提交
650
        fn bit(bitv: &Bitv, byte: uint, bit: uint) -> u8 {
651 652 653 654
            let offset = byte * 8 + bit;
            if offset >= bitv.nbits {
                0
            } else {
655
                (bitv[offset] as u8) << (7 - bit)
656 657 658 659 660
            }
        }

        let len = self.nbits/8 +
                  if self.nbits % 8 == 0 { 0 } else { 1 };
A
Aaron Turon 已提交
661
        range(0, len).map(|i|
662 663 664 665 666 667 668 669
            bit(self, i, 0) |
            bit(self, i, 1) |
            bit(self, i, 2) |
            bit(self, i, 3) |
            bit(self, i, 4) |
            bit(self, i, 5) |
            bit(self, i, 6) |
            bit(self, i, 7)
A
Aaron Turon 已提交
670
        ).collect()
671 672
    }

P
P1start 已提交
673 674 675
    /// Compares a `Bitv` to a slice of `bool`s.
    /// Both the `Bitv` and slice must have the same length.
    ///
676
    /// # Panics
J
Jonas Hietala 已提交
677
    ///
678
    /// Panics if the `Bitv` and slice are of different length.
J
Jonas Hietala 已提交
679
    ///
680
    /// # Examples
J
Jonas Hietala 已提交
681 682
    ///
    /// ```
683
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
684
    ///
685
    /// let bv = Bitv::from_bytes(&[0b10100000]);
J
Jonas Hietala 已提交
686
    ///
N
Nick Cameron 已提交
687 688
    /// assert!(bv.eq_vec(&[true, false, true, false,
    ///                     false, false, false, false]));
J
Jonas Hietala 已提交
689
    /// ```
690
    pub fn eq_vec(&self, v: &[bool]) -> bool {
691
        assert_eq!(self.nbits, v.len());
T
Tobias Bucher 已提交
692
        iter::order::eq(self.iter(), v.iter().cloned())
693
    }
694

P
P1start 已提交
695
    /// Shortens a `Bitv`, dropping excess elements.
696 697 698 699
    ///
    /// If `len` is greater than the vector's current length, this has no
    /// effect.
    ///
700
    /// # Examples
701
    ///
J
Jonas Hietala 已提交
702
    /// ```
703
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
704
    ///
705
    /// let mut bv = Bitv::from_bytes(&[0b01001011]);
J
Jonas Hietala 已提交
706
    /// bv.truncate(2);
N
Nick Cameron 已提交
707
    /// assert!(bv.eq_vec(&[false, true]));
708
    /// ```
A
Alexis Beingessner 已提交
709
    #[stable]
710 711 712
    pub fn truncate(&mut self, len: uint) {
        if len < self.len() {
            self.nbits = len;
T
Tobias Bucher 已提交
713
            // This fixes (2).
714 715
            self.storage.truncate(blocks_for_bits(len));
            self.fix_last_block();
716 717 718
        }
    }

719 720 721 722 723 724
    /// Reserves capacity for at least `additional` more bits to be inserted in the given
    /// `Bitv`. The collection may reserve more space to avoid frequent reallocations.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity overflows `uint`.
J
Jonas Hietala 已提交
725
    ///
726
    /// # Examples
J
Jonas Hietala 已提交
727 728
    ///
    /// ```
729
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
730
    ///
731
    /// let mut bv = Bitv::from_elem(3, false);
J
Jonas Hietala 已提交
732 733
    /// bv.reserve(10);
    /// assert_eq!(bv.len(), 3);
734 735
    /// assert!(bv.capacity() >= 13);
    /// ```
A
Alexis Beingessner 已提交
736
    #[stable]
737 738
    pub fn reserve(&mut self, additional: uint) {
        let desired_cap = self.len().checked_add(additional).expect("capacity overflow");
T
Tobias Bucher 已提交
739 740 741
        let storage_len = self.storage.len();
        if desired_cap > self.capacity() {
            self.storage.reserve(blocks_for_bits(desired_cap) - storage_len);
742 743 744
        }
    }

745 746 747 748 749 750 751 752 753 754
    /// Reserves the minimum capacity for exactly `additional` more bits to be inserted in the
    /// given `Bitv`. Does nothing if the capacity is already sufficient.
    ///
    /// Note that the allocator may give the collection more space than it requests. Therefore
    /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
    /// insertions are expected.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity overflows `uint`.
J
Jonas Hietala 已提交
755
    ///
756
    /// # Examples
J
Jonas Hietala 已提交
757 758
    ///
    /// ```
759
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
760
    ///
761
    /// let mut bv = Bitv::from_elem(3, false);
J
Jonas Hietala 已提交
762 763
    /// bv.reserve(10);
    /// assert_eq!(bv.len(), 3);
764
    /// assert!(bv.capacity() >= 13);
J
Jonas Hietala 已提交
765
    /// ```
A
Alexis Beingessner 已提交
766
    #[stable]
767 768
    pub fn reserve_exact(&mut self, additional: uint) {
        let desired_cap = self.len().checked_add(additional).expect("capacity overflow");
T
Tobias Bucher 已提交
769 770 771
        let storage_len = self.storage.len();
        if desired_cap > self.capacity() {
            self.storage.reserve_exact(blocks_for_bits(desired_cap) - storage_len);
772 773 774
        }
    }

P
P1start 已提交
775
    /// Returns the capacity in bits for this bit vector. Inserting any
776
    /// element less than this amount will not trigger a resizing.
J
Jonas Hietala 已提交
777
    ///
778
    /// # Examples
J
Jonas Hietala 已提交
779 780
    ///
    /// ```
781
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
782 783 784 785 786
    ///
    /// let mut bv = Bitv::new();
    /// bv.reserve(10);
    /// assert!(bv.capacity() >= 10);
    /// ```
787
    #[inline]
A
Alexis Beingessner 已提交
788
    #[stable]
789
    pub fn capacity(&self) -> uint {
790
        self.storage.capacity().checked_mul(u32::BITS).unwrap_or(uint::MAX)
791 792
    }

P
P1start 已提交
793
    /// Grows the `Bitv` in-place, adding `n` copies of `value` to the `Bitv`.
794
    ///
795 796 797 798
    /// # Panics
    ///
    /// Panics if the new len overflows a `uint`.
    ///
799
    /// # Examples
800
    ///
J
Jonas Hietala 已提交
801
    /// ```
802
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
803
    ///
804
    /// let mut bv = Bitv::from_bytes(&[0b01001011]);
J
Jonas Hietala 已提交
805
    /// bv.grow(2, true);
806 807
    /// assert_eq!(bv.len(), 10);
    /// assert_eq!(bv.to_bytes(), vec!(0b01001011, 0b11000000));
808 809
    /// ```
    pub fn grow(&mut self, n: uint, value: bool) {
810 811 812 813 814 815
        // Note: we just bulk set all the bits in the last word in this fn in multiple places
        // which is technically wrong if not all of these bits are to be used. However, at the end
        // of this fn we call `fix_last_block` at the end of this fn, which should fix this.

        let new_nbits = self.nbits.checked_add(n).expect("capacity overflow");
        let new_nblocks = blocks_for_bits(new_nbits);
816
        let full_value = if value { !0 } else { 0 };
817

818
        // Correct the old tail word, setting or clearing formerly unused bits
819
        let old_last_word = blocks_for_bits(self.nbits) - 1;
820
        if self.nbits % u32::BITS > 0 {
821
            let mask = mask_for_bits(self.nbits);
822
            if value {
823
                self.storage[old_last_word] |= !mask;
824
            } else {
T
Tobias Bucher 已提交
825
                // Extra bits are already zero by invariant.
826 827
            }
        }
828

829
        // Fill in words after the old tail word
830
        let stop_idx = cmp::min(self.storage.len(), new_nblocks);
831
        for idx in range(old_last_word + 1, stop_idx) {
832
            self.storage[idx] = full_value;
833
        }
834

835
        // Allocate new words, if needed
836 837
        if new_nblocks > self.storage.len() {
            let to_add = new_nblocks - self.storage.len();
A
Aaron Turon 已提交
838
            self.storage.extend(repeat(full_value).take(to_add));
839
        }
840

841 842
        // Adjust internal bit count
        self.nbits = new_nbits;
843 844

        self.fix_last_block();
845 846
    }

847
    /// Removes the last bit from the Bitv, and returns it. Returns None if the Bitv is empty.
848
    ///
849
    /// # Examples
850
    ///
J
Jonas Hietala 已提交
851
    /// ```
852
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
853
    ///
854 855 856
    /// let mut bv = Bitv::from_bytes(&[0b01001001]);
    /// assert_eq!(bv.pop(), Some(true));
    /// assert_eq!(bv.pop(), Some(false));
857
    /// assert_eq!(bv.len(), 6);
858
    /// ```
A
Alexis Beingessner 已提交
859
    #[stable]
860 861 862 863
    pub fn pop(&mut self) -> Option<bool> {
        if self.is_empty() {
            None
        } else {
J
Josh Stone 已提交
864 865
            let i = self.nbits - 1;
            let ret = self[i];
T
Tobias Bucher 已提交
866
            // (3)
J
Josh Stone 已提交
867 868
            self.set(i, false);
            self.nbits = i;
T
Tobias Bucher 已提交
869 870 871 872
            if self.nbits % u32::BITS == 0 {
                // (2)
                self.storage.pop();
            }
873
            Some(ret)
874 875 876
        }
    }

P
P1start 已提交
877
    /// Pushes a `bool` onto the end.
878
    ///
879
    /// # Examples
880
    ///
J
Jonas Hietala 已提交
881
    /// ```
882
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
883
    ///
884
    /// let mut bv = Bitv::new();
J
Jonas Hietala 已提交
885 886
    /// bv.push(true);
    /// bv.push(false);
N
Nick Cameron 已提交
887
    /// assert!(bv.eq_vec(&[true, false]));
888
    /// ```
A
Alexis Beingessner 已提交
889
    #[stable]
890
    pub fn push(&mut self, elem: bool) {
T
Tobias Bucher 已提交
891
        if self.nbits % u32::BITS == 0 {
892 893
            self.storage.push(0);
        }
T
Tobias Bucher 已提交
894 895
        let insert_pos = self.nbits;
        self.nbits = self.nbits.checked_add(1).expect("Capacity overflow");
896 897
        self.set(insert_pos, elem);
    }
898 899 900

    /// Return the total number of bits in this vector
    #[inline]
A
Alexis Beingessner 已提交
901
    #[stable]
902 903 904 905
    pub fn len(&self) -> uint { self.nbits }

    /// Returns true if there are no bits in this vector
    #[inline]
A
Alexis Beingessner 已提交
906
    #[stable]
907 908 909 910
    pub fn is_empty(&self) -> bool { self.len() == 0 }

    /// Clears all bits in this vector.
    #[inline]
A
Alexis Beingessner 已提交
911
    #[stable]
912 913 914
    pub fn clear(&mut self) {
        for w in self.storage.iter_mut() { *w = 0u32; }
    }
915
}
916

917
#[stable]
918 919
impl Default for Bitv {
    #[inline]
920
    fn default() -> Bitv { Bitv::new() }
921 922
}

A
Alexis Beingessner 已提交
923
#[stable]
924
impl FromIterator<bool> for Bitv {
J
Jorge Aparicio 已提交
925
    fn from_iter<I:Iterator<Item=bool>>(iterator: I) -> Bitv {
926
        let mut ret = Bitv::new();
927 928 929 930 931
        ret.extend(iterator);
        ret
    }
}

A
Alexis Beingessner 已提交
932
#[stable]
G
gamazeps 已提交
933
impl Extend<bool> for Bitv {
934
    #[inline]
J
Jorge Aparicio 已提交
935
    fn extend<I: Iterator<Item=bool>>(&mut self, mut iterator: I) {
936
        let (min, _) = iterator.size_hint();
937
        self.reserve(min);
938 939 940 941 942 943
        for element in iterator {
            self.push(element)
        }
    }
}

A
Aaron Turon 已提交
944
#[stable]
945 946 947 948 949 950 951 952 953
impl Clone for Bitv {
    #[inline]
    fn clone(&self) -> Bitv {
        Bitv { storage: self.storage.clone(), nbits: self.nbits }
    }

    #[inline]
    fn clone_from(&mut self, source: &Bitv) {
        self.nbits = source.nbits;
954
        self.storage.clone_from(&source.storage);
955 956 957
    }
}

A
Aaron Turon 已提交
958
#[stable]
N
nham 已提交
959 960 961 962 963 964 965
impl PartialOrd for Bitv {
    #[inline]
    fn partial_cmp(&self, other: &Bitv) -> Option<Ordering> {
        iter::order::partial_cmp(self.iter(), other.iter())
    }
}

A
Aaron Turon 已提交
966
#[stable]
967 968 969 970 971 972 973
impl Ord for Bitv {
    #[inline]
    fn cmp(&self, other: &Bitv) -> Ordering {
        iter::order::cmp(self.iter(), other.iter())
    }
}

A
Alexis Beingessner 已提交
974
#[stable]
S
Steven Fackler 已提交
975 976 977
impl fmt::Show for Bitv {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        for bit in self.iter() {
T
Tobias Bucher 已提交
978
            try!(write!(fmt, "{}", if bit { 1u32 } else { 0u32 }));
S
Steven Fackler 已提交
979 980 981 982 983
        }
        Ok(())
    }
}

A
Alexis Beingessner 已提交
984
#[stable]
985 986 987
impl<S: hash::Writer> hash::Hash<S> for Bitv {
    fn hash(&self, state: &mut S) {
        self.nbits.hash(state);
988
        for elem in self.blocks() {
989
            elem.hash(state);
990 991 992 993
        }
    }
}

A
Aaron Turon 已提交
994
#[stable]
995 996 997
impl cmp::PartialEq for Bitv {
    #[inline]
    fn eq(&self, other: &Bitv) -> bool {
998 999 1000
        if self.nbits != other.nbits {
            return false;
        }
1001
        self.blocks().zip(other.blocks()).all(|(w1, w2)| w1 == w2)
1002 1003 1004
    }
}

A
Aaron Turon 已提交
1005
#[stable]
1006 1007
impl cmp::Eq for Bitv {}

1008
/// An iterator for `Bitv`.
A
Alexis Beingessner 已提交
1009
#[stable]
1010
#[derive(Clone)]
A
Alexis Beingessner 已提交
1011
pub struct Iter<'a> {
1012 1013 1014
    bitv: &'a Bitv,
    next_idx: uint,
    end_idx: uint,
1015 1016
}

A
Alexis Beingessner 已提交
1017
#[stable]
J
Jorge Aparicio 已提交
1018 1019 1020
impl<'a> Iterator for Iter<'a> {
    type Item = bool;

S
Steven Fackler 已提交
1021
    #[inline]
1022
    fn next(&mut self) -> Option<bool> {
1023
        if self.next_idx != self.end_idx {
1024 1025
            let idx = self.next_idx;
            self.next_idx += 1;
1026
            Some(self.bitv[idx])
1027 1028 1029 1030 1031 1032
        } else {
            None
        }
    }

    fn size_hint(&self) -> (uint, Option<uint>) {
1033
        let rem = self.end_idx - self.next_idx;
1034 1035 1036 1037
        (rem, Some(rem))
    }
}

A
Alexis Beingessner 已提交
1038
#[stable]
J
Jorge Aparicio 已提交
1039
impl<'a> DoubleEndedIterator for Iter<'a> {
1040 1041 1042 1043
    #[inline]
    fn next_back(&mut self) -> Option<bool> {
        if self.next_idx != self.end_idx {
            self.end_idx -= 1;
1044
            Some(self.bitv[self.end_idx])
1045 1046 1047 1048 1049 1050
        } else {
            None
        }
    }
}

A
Alexis Beingessner 已提交
1051
#[stable]
J
Jorge Aparicio 已提交
1052
impl<'a> ExactSizeIterator for Iter<'a> {}
1053

A
Alexis Beingessner 已提交
1054
#[stable]
J
Jorge Aparicio 已提交
1055
impl<'a> RandomAccessIterator for Iter<'a> {
1056 1057 1058 1059 1060 1061
    #[inline]
    fn indexable(&self) -> uint {
        self.end_idx - self.next_idx
    }

    #[inline]
1062
    fn idx(&mut self, index: uint) -> Option<bool> {
1063 1064 1065
        if index >= self.indexable() {
            None
        } else {
1066
            Some(self.bitv[index])
1067 1068 1069 1070
        }
    }
}

1071
/// An implementation of a set using a bit vector as an underlying
J
Jonas Hietala 已提交
1072
/// representation for holding unsigned numerical elements.
1073 1074 1075
///
/// It should also be noted that the amount of storage necessary for holding a
/// set of objects is proportional to the maximum of the objects when viewed
1076
/// as a `uint`.
J
Jonas Hietala 已提交
1077
///
1078
/// # Examples
J
Jonas Hietala 已提交
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
///
/// ```
/// use std::collections::{BitvSet, Bitv};
///
/// // It's a regular set
/// let mut s = BitvSet::new();
/// s.insert(0);
/// s.insert(3);
/// s.insert(7);
///
/// s.remove(&7);
///
/// if !s.contains(&7) {
///     println!("There is no 7");
/// }
///
/// // Can initialize from a `Bitv`
1096
/// let other = BitvSet::from_bitv(Bitv::from_bytes(&[0b11010000]));
J
Jonas Hietala 已提交
1097 1098 1099 1100 1101 1102 1103 1104 1105
///
/// s.union_with(&other);
///
/// // Print 0, 1, 3 in some order
/// for x in s.iter() {
///     println!("{}", x);
/// }
///
/// // Can convert back to a `Bitv`
1106
/// let bv: Bitv = s.into_bitv();
1107
/// assert!(bv[3]);
J
Jonas Hietala 已提交
1108
/// ```
1109
#[derive(Clone)]
A
Alexis Beingessner 已提交
1110
#[stable]
1111 1112 1113
pub struct BitvSet {
    bitv: Bitv,
}
1114

A
Alexis Beingessner 已提交
1115
#[stable]
1116 1117 1118 1119 1120
impl Default for BitvSet {
    #[inline]
    fn default() -> BitvSet { BitvSet::new() }
}

A
Alexis Beingessner 已提交
1121
#[stable]
1122
impl FromIterator<uint> for BitvSet {
J
Jorge Aparicio 已提交
1123
    fn from_iter<I:Iterator<Item=uint>>(iterator: I) -> BitvSet {
1124 1125 1126 1127 1128 1129
        let mut ret = BitvSet::new();
        ret.extend(iterator);
        ret
    }
}

A
Alexis Beingessner 已提交
1130
#[stable]
1131
impl Extend<uint> for BitvSet {
1132
    #[inline]
J
Jorge Aparicio 已提交
1133
    fn extend<I: Iterator<Item=uint>>(&mut self, mut iterator: I) {
1134 1135 1136
        for i in iterator {
            self.insert(i);
        }
1137 1138 1139
    }
}

A
Aaron Turon 已提交
1140
#[stable]
1141 1142 1143
impl PartialOrd for BitvSet {
    #[inline]
    fn partial_cmp(&self, other: &BitvSet) -> Option<Ordering> {
1144
        let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1145 1146 1147 1148
        iter::order::partial_cmp(a_iter, b_iter)
    }
}

A
Aaron Turon 已提交
1149
#[stable]
1150 1151 1152
impl Ord for BitvSet {
    #[inline]
    fn cmp(&self, other: &BitvSet) -> Ordering {
1153
        let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1154 1155 1156 1157
        iter::order::cmp(a_iter, b_iter)
    }
}

A
Aaron Turon 已提交
1158
#[stable]
1159 1160 1161
impl cmp::PartialEq for BitvSet {
    #[inline]
    fn eq(&self, other: &BitvSet) -> bool {
1162
        let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1163 1164 1165 1166
        iter::order::eq(a_iter, b_iter)
    }
}

A
Aaron Turon 已提交
1167
#[stable]
1168 1169
impl cmp::Eq for BitvSet {}

1170
impl BitvSet {
1171
    /// Creates a new empty `BitvSet`.
J
Jonas Hietala 已提交
1172
    ///
1173
    /// # Examples
J
Jonas Hietala 已提交
1174 1175 1176
    ///
    /// ```
    /// use std::collections::BitvSet;
1177
    ///
J
Jonas Hietala 已提交
1178 1179
    /// let mut s = BitvSet::new();
    /// ```
1180
    #[inline]
A
Alexis Beingessner 已提交
1181
    #[stable]
1182
    pub fn new() -> BitvSet {
1183
        BitvSet { bitv: Bitv::new() }
1184 1185
    }

1186
    /// Creates a new `BitvSet` with initially no contents, able to
J
Jonas Hietala 已提交
1187 1188
    /// hold `nbits` elements without resizing.
    ///
1189
    /// # Examples
J
Jonas Hietala 已提交
1190 1191 1192
    ///
    /// ```
    /// use std::collections::BitvSet;
1193
    ///
J
Jonas Hietala 已提交
1194 1195 1196
    /// let mut s = BitvSet::with_capacity(100);
    /// assert!(s.capacity() >= 100);
    /// ```
1197
    #[inline]
A
Alexis Beingessner 已提交
1198
    #[stable]
1199
    pub fn with_capacity(nbits: uint) -> BitvSet {
1200
        let bitv = Bitv::from_elem(nbits, false);
1201
        BitvSet::from_bitv(bitv)
1202
    }
E
Eric Holk 已提交
1203

1204
    /// Creates a new `BitvSet` from the given bit vector.
J
Jonas Hietala 已提交
1205
    ///
1206
    /// # Examples
J
Jonas Hietala 已提交
1207 1208
    ///
    /// ```
1209
    /// use std::collections::{Bitv, BitvSet};
J
Jonas Hietala 已提交
1210
    ///
1211
    /// let bv = Bitv::from_bytes(&[0b01100000]);
J
Jonas Hietala 已提交
1212 1213 1214 1215 1216 1217 1218
    /// let s = BitvSet::from_bitv(bv);
    ///
    /// // Print 1, 2 in arbitrary order
    /// for x in s.iter() {
    ///     println!("{}", x);
    /// }
    /// ```
1219
    #[inline]
1220 1221
    pub fn from_bitv(bitv: Bitv) -> BitvSet {
        BitvSet { bitv: bitv }
1222 1223 1224 1225
    }

    /// Returns the capacity in bits for this bit vector. Inserting any
    /// element less than this amount will not trigger a resizing.
J
Jonas Hietala 已提交
1226
    ///
1227
    /// # Examples
J
Jonas Hietala 已提交
1228 1229 1230 1231 1232 1233 1234
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::with_capacity(100);
    /// assert!(s.capacity() >= 100);
    /// ```
1235
    #[inline]
A
Alexis Beingessner 已提交
1236
    #[stable]
1237
    pub fn capacity(&self) -> uint {
1238 1239 1240
        self.bitv.capacity()
    }

1241 1242 1243
    /// Reserves capacity for the given `BitvSet` to contain `len` distinct elements. In the case
    /// of `BitvSet` this means reallocations will not occur as long as all inserted elements
    /// are less than `len`.
1244
    ///
1245
    /// The collection may reserve more space to avoid frequent reallocations.
1246 1247 1248 1249 1250 1251 1252 1253
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::new();
1254 1255
    /// s.reserve_len(10);
    /// assert!(s.capacity() >= 10);
1256
    /// ```
A
Alexis Beingessner 已提交
1257
    #[stable]
1258 1259 1260 1261
    pub fn reserve_len(&mut self, len: uint) {
        let cur_len = self.bitv.len();
        if len >= cur_len {
            self.bitv.reserve(len - cur_len);
1262
        }
1263 1264
    }

1265 1266 1267
    /// Reserves the minimum capacity for the given `BitvSet` to contain `len` distinct elements.
    /// In the case of `BitvSet` this means reallocations will not occur as long as all inserted
    /// elements are less than `len`.
1268 1269
    ///
    /// Note that the allocator may give the collection more space than it requests. Therefore
1270
    /// capacity can not be relied upon to be precisely minimal. Prefer `reserve_len` if future
1271 1272
    /// insertions are expected.
    ///
J
Jonas Hietala 已提交
1273
    ///
1274
    /// # Examples
J
Jonas Hietala 已提交
1275 1276 1277 1278 1279
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::new();
1280
    /// s.reserve_len_exact(10);
J
Jonas Hietala 已提交
1281 1282
    /// assert!(s.capacity() >= 10);
    /// ```
A
Alexis Beingessner 已提交
1283
    #[stable]
1284 1285 1286 1287
    pub fn reserve_len_exact(&mut self, len: uint) {
        let cur_len = self.bitv.len();
        if len >= cur_len {
            self.bitv.reserve_exact(len - cur_len);
1288
        }
1289
    }
1290

1291

P
P1start 已提交
1292
    /// Consumes this set to return the underlying bit vector.
J
Jonas Hietala 已提交
1293
    ///
1294
    /// # Examples
J
Jonas Hietala 已提交
1295 1296 1297 1298 1299 1300 1301 1302
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::new();
    /// s.insert(0);
    /// s.insert(3);
    ///
1303
    /// let bv = s.into_bitv();
1304 1305
    /// assert!(bv[0]);
    /// assert!(bv[3]);
J
Jonas Hietala 已提交
1306
    /// ```
1307
    #[inline]
1308
    pub fn into_bitv(self) -> Bitv {
1309
        self.bitv
1310 1311
    }

P
P1start 已提交
1312
    /// Returns a reference to the underlying bit vector.
J
Jonas Hietala 已提交
1313
    ///
1314
    /// # Examples
J
Jonas Hietala 已提交
1315 1316 1317 1318 1319 1320 1321 1322
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::new();
    /// s.insert(0);
    ///
    /// let bv = s.get_ref();
J
Jonas Hietala 已提交
1323
    /// assert_eq!(bv[0], true);
J
Jonas Hietala 已提交
1324
    /// ```
1325
    #[inline]
A
Alexis Beingessner 已提交
1326
    pub fn get_ref(&self) -> &Bitv {
1327
        &self.bitv
1328 1329
    }

1330
    #[inline]
1331
    fn other_op<F>(&mut self, other: &BitvSet, mut f: F) where F: FnMut(u32, u32) -> u32 {
1332
        // Unwrap Bitvs
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
        let self_bitv = &mut self.bitv;
        let other_bitv = &other.bitv;

        let self_len = self_bitv.len();
        let other_len = other_bitv.len();

        // Expand the vector if necessary
        if self_len < other_len {
            self_bitv.grow(other_len - self_len, false);
        }
1343 1344

        // virtually pad other with 0's for equal lengths
1345 1346 1347 1348
        let mut other_words = {
            let (_, result) = match_words(self_bitv, other_bitv);
            result
        };
1349 1350 1351

        // Apply values found in other
        for (i, w) in other_words {
1352
            let old = self_bitv.storage[i];
1353
            let new = f(old, w);
1354
            self_bitv.storage[i] = new;
1355
        }
1356 1357
    }

P
P1start 已提交
1358
    /// Truncates the underlying vector to the least length required.
J
Jonas Hietala 已提交
1359
    ///
1360
    /// # Examples
J
Jonas Hietala 已提交
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::new();
    /// s.insert(32183231);
    /// s.remove(&32183231);
    ///
    /// // Internal storage will probably be bigger than necessary
    /// println!("old capacity: {}", s.capacity());
    ///
    /// // Now should be smaller
    /// s.shrink_to_fit();
    /// println!("new capacity: {}", s.capacity());
    /// ```
1376
    #[inline]
A
Alexis Beingessner 已提交
1377
    #[stable]
1378
    pub fn shrink_to_fit(&mut self) {
1379
        let bitv = &mut self.bitv;
1380 1381 1382 1383 1384 1385
        // Obtain original length
        let old_len = bitv.storage.len();
        // Obtain coarse trailing zero length
        let n = bitv.storage.iter().rev().take_while(|&&n| n == 0).count();
        // Truncate
        let trunc_len = cmp::max(old_len - n, 1);
1386
        bitv.storage.truncate(trunc_len);
1387
        bitv.nbits = trunc_len * u32::BITS;
1388 1389
    }

1390
    /// Iterator over each u32 stored in the `BitvSet`.
J
Jonas Hietala 已提交
1391
    ///
1392
    /// # Examples
J
Jonas Hietala 已提交
1393 1394
    ///
    /// ```
1395
    /// use std::collections::{Bitv, BitvSet};
J
Jonas Hietala 已提交
1396
    ///
1397
    /// let s = BitvSet::from_bitv(Bitv::from_bytes(&[0b01001010]));
J
Jonas Hietala 已提交
1398 1399 1400 1401 1402 1403
    ///
    /// // Print 1, 4, 6 in arbitrary order
    /// for x in s.iter() {
    ///     println!("{}", x);
    /// }
    /// ```
1404
    #[inline]
A
Alexis Beingessner 已提交
1405 1406 1407
    #[stable]
    pub fn iter(&self) -> bitv_set::Iter {
        SetIter {set: self, next_idx: 0u}
1408
    }
1409

1410
    /// Iterator over each u32 stored in `self` union `other`.
J
Jonas Hietala 已提交
1411 1412
    /// See [union_with](#method.union_with) for an efficient in-place version.
    ///
1413
    /// # Examples
J
Jonas Hietala 已提交
1414 1415
    ///
    /// ```
1416
    /// use std::collections::{Bitv, BitvSet};
J
Jonas Hietala 已提交
1417
    ///
1418 1419
    /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
    /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
J
Jonas Hietala 已提交
1420 1421 1422 1423 1424 1425
    ///
    /// // Print 0, 1, 2, 4 in arbitrary order
    /// for x in a.union(&b) {
    ///     println!("{}", x);
    /// }
    /// ```
1426
    #[inline]
A
Alexis Beingessner 已提交
1427 1428
    #[stable]
    pub fn union<'a>(&'a self, other: &'a BitvSet) -> Union<'a> {
1429 1430
        fn or(w1: u32, w2: u32) -> u32 { w1 | w2 }

A
Alexis Beingessner 已提交
1431
        Union(TwoBitPositions {
1432 1433
            set: self,
            other: other,
1434
            merge: or,
1435 1436
            current_word: 0u32,
            next_idx: 0u
A
Alexis Beingessner 已提交
1437
        })
1438 1439
    }

1440 1441
    /// Iterator over each uint stored in `self` intersect `other`.
    /// See [intersect_with](#method.intersect_with) for an efficient in-place version.
J
Jonas Hietala 已提交
1442
    ///
1443
    /// # Examples
J
Jonas Hietala 已提交
1444 1445
    ///
    /// ```
1446
    /// use std::collections::{Bitv, BitvSet};
J
Jonas Hietala 已提交
1447
    ///
1448 1449
    /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
    /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
J
Jonas Hietala 已提交
1450
    ///
1451 1452
    /// // Print 2
    /// for x in a.intersection(&b) {
J
Jonas Hietala 已提交
1453 1454 1455
    ///     println!("{}", x);
    /// }
    /// ```
1456
    #[inline]
A
Alexis Beingessner 已提交
1457 1458
    #[stable]
    pub fn intersection<'a>(&'a self, other: &'a BitvSet) -> Intersection<'a> {
1459
        fn bitand(w1: u32, w2: u32) -> u32 { w1 & w2 }
1460
        let min = cmp::min(self.bitv.len(), other.bitv.len());
A
Alexis Beingessner 已提交
1461
        Intersection(TwoBitPositions {
1462 1463
            set: self,
            other: other,
1464
            merge: bitand,
1465
            current_word: 0u32,
1466
            next_idx: 0
A
Alexis Beingessner 已提交
1467
        }.take(min))
1468 1469
    }

1470 1471
    /// Iterator over each uint stored in the `self` setminus `other`.
    /// See [difference_with](#method.difference_with) for an efficient in-place version.
J
Jonas Hietala 已提交
1472
    ///
1473
    /// # Examples
J
Jonas Hietala 已提交
1474 1475
    ///
    /// ```
1476
    /// use std::collections::{BitvSet, Bitv};
J
Jonas Hietala 已提交
1477
    ///
1478 1479
    /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
    /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
J
Jonas Hietala 已提交
1480
    ///
1481
    /// // Print 1, 4 in arbitrary order
1482 1483 1484 1485 1486 1487 1488 1489
    /// for x in a.difference(&b) {
    ///     println!("{}", x);
    /// }
    ///
    /// // Note that difference is not symmetric,
    /// // and `b - a` means something else.
    /// // This prints 0
    /// for x in b.difference(&a) {
J
Jonas Hietala 已提交
1490 1491 1492
    ///     println!("{}", x);
    /// }
    /// ```
1493
    #[inline]
A
Alexis Beingessner 已提交
1494 1495
    #[stable]
    pub fn difference<'a>(&'a self, other: &'a BitvSet) -> Difference<'a> {
1496 1497
        fn diff(w1: u32, w2: u32) -> u32 { w1 & !w2 }

A
Alexis Beingessner 已提交
1498
        Difference(TwoBitPositions {
1499 1500
            set: self,
            other: other,
1501
            merge: diff,
1502
            current_word: 0u32,
1503
            next_idx: 0
A
Alexis Beingessner 已提交
1504
        })
1505 1506
    }

1507
    /// Iterator over each u32 stored in the symmetric difference of `self` and `other`.
1508 1509
    /// See [symmetric_difference_with](#method.symmetric_difference_with) for
    /// an efficient in-place version.
J
Jonas Hietala 已提交
1510
    ///
1511
    /// # Examples
J
Jonas Hietala 已提交
1512 1513
    ///
    /// ```
1514
    /// use std::collections::{BitvSet, Bitv};
J
Jonas Hietala 已提交
1515
    ///
1516 1517
    /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
    /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
J
Jonas Hietala 已提交
1518
    ///
1519 1520
    /// // Print 0, 1, 4 in arbitrary order
    /// for x in a.symmetric_difference(&b) {
J
Jonas Hietala 已提交
1521 1522 1523
    ///     println!("{}", x);
    /// }
    /// ```
1524
    #[inline]
A
Alexis Beingessner 已提交
1525 1526
    #[stable]
    pub fn symmetric_difference<'a>(&'a self, other: &'a BitvSet) -> SymmetricDifference<'a> {
1527 1528
        fn bitxor(w1: u32, w2: u32) -> u32 { w1 ^ w2 }

A
Alexis Beingessner 已提交
1529
        SymmetricDifference(TwoBitPositions {
1530 1531
            set: self,
            other: other,
1532
            merge: bitxor,
1533
            current_word: 0u32,
1534
            next_idx: 0
A
Alexis Beingessner 已提交
1535
        })
1536 1537
    }

P
P1start 已提交
1538
    /// Unions in-place with the specified other bit vector.
J
Jonas Hietala 已提交
1539
    ///
1540
    /// # Examples
J
Jonas Hietala 已提交
1541 1542
    ///
    /// ```
1543
    /// use std::collections::{BitvSet, Bitv};
J
Jonas Hietala 已提交
1544
    ///
1545 1546 1547 1548
    /// let a   = 0b01101000;
    /// let b   = 0b10100000;
    /// let res = 0b11101000;
    ///
1549 1550 1551
    /// let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
    /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
    /// let res = BitvSet::from_bitv(Bitv::from_bytes(&[res]));
J
Jonas Hietala 已提交
1552 1553
    ///
    /// a.union_with(&b);
1554
    /// assert_eq!(a, res);
J
Jonas Hietala 已提交
1555
    /// ```
1556 1557 1558 1559 1560
    #[inline]
    pub fn union_with(&mut self, other: &BitvSet) {
        self.other_op(other, |w1, w2| w1 | w2);
    }

P
P1start 已提交
1561
    /// Intersects in-place with the specified other bit vector.
J
Jonas Hietala 已提交
1562
    ///
1563
    /// # Examples
J
Jonas Hietala 已提交
1564 1565
    ///
    /// ```
1566
    /// use std::collections::{BitvSet, Bitv};
J
Jonas Hietala 已提交
1567
    ///
1568 1569 1570 1571
    /// let a   = 0b01101000;
    /// let b   = 0b10100000;
    /// let res = 0b00100000;
    ///
1572 1573 1574
    /// let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
    /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
    /// let res = BitvSet::from_bitv(Bitv::from_bytes(&[res]));
J
Jonas Hietala 已提交
1575 1576
    ///
    /// a.intersect_with(&b);
1577
    /// assert_eq!(a, res);
J
Jonas Hietala 已提交
1578
    /// ```
1579 1580 1581 1582 1583
    #[inline]
    pub fn intersect_with(&mut self, other: &BitvSet) {
        self.other_op(other, |w1, w2| w1 & w2);
    }

P
P1start 已提交
1584 1585
    /// Makes this bit vector the difference with the specified other bit vector
    /// in-place.
J
Jonas Hietala 已提交
1586
    ///
1587
    /// # Examples
J
Jonas Hietala 已提交
1588 1589
    ///
    /// ```
1590
    /// use std::collections::{BitvSet, Bitv};
J
Jonas Hietala 已提交
1591
    ///
1592 1593 1594 1595 1596
    /// let a   = 0b01101000;
    /// let b   = 0b10100000;
    /// let a_b = 0b01001000; // a - b
    /// let b_a = 0b10000000; // b - a
    ///
1597 1598 1599 1600
    /// let mut bva = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
    /// let bvb = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
    /// let bva_b = BitvSet::from_bitv(Bitv::from_bytes(&[a_b]));
    /// let bvb_a = BitvSet::from_bitv(Bitv::from_bytes(&[b_a]));
1601 1602
    ///
    /// bva.difference_with(&bvb);
1603
    /// assert_eq!(bva, bva_b);
J
Jonas Hietala 已提交
1604
    ///
1605 1606
    /// let bva = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
    /// let mut bvb = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
1607 1608
    ///
    /// bvb.difference_with(&bva);
1609
    /// assert_eq!(bvb, bvb_a);
J
Jonas Hietala 已提交
1610
    /// ```
1611 1612 1613 1614 1615
    #[inline]
    pub fn difference_with(&mut self, other: &BitvSet) {
        self.other_op(other, |w1, w2| w1 & !w2);
    }

P
P1start 已提交
1616 1617
    /// Makes this bit vector the symmetric difference with the specified other
    /// bit vector in-place.
J
Jonas Hietala 已提交
1618
    ///
1619
    /// # Examples
J
Jonas Hietala 已提交
1620 1621
    ///
    /// ```
1622
    /// use std::collections::{BitvSet, Bitv};
J
Jonas Hietala 已提交
1623
    ///
1624 1625 1626 1627
    /// let a   = 0b01101000;
    /// let b   = 0b10100000;
    /// let res = 0b11001000;
    ///
1628 1629 1630
    /// let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
    /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
    /// let res = BitvSet::from_bitv(Bitv::from_bytes(&[res]));
J
Jonas Hietala 已提交
1631 1632
    ///
    /// a.symmetric_difference_with(&b);
1633
    /// assert_eq!(a, res);
J
Jonas Hietala 已提交
1634
    /// ```
1635 1636 1637 1638
    #[inline]
    pub fn symmetric_difference_with(&mut self, other: &BitvSet) {
        self.other_op(other, |w1, w2| w1 ^ w2);
    }
S
Steven Fackler 已提交
1639

1640 1641
    /// Return the number of set bits in this set.
    #[inline]
A
Alexis Beingessner 已提交
1642
    #[stable]
1643
    pub fn len(&self) -> uint  {
1644
        self.bitv.blocks().fold(0, |acc, n| acc + n.count_ones())
1645 1646
    }

1647
    /// Returns whether there are no bits set in this set
1648
    #[inline]
A
Alexis Beingessner 已提交
1649
    #[stable]
1650
    pub fn is_empty(&self) -> bool {
1651
        self.bitv.none()
1652
    }
1653

1654
    /// Clears all bits in this set
1655
    #[inline]
A
Alexis Beingessner 已提交
1656
    #[stable]
1657
    pub fn clear(&mut self) {
1658
        self.bitv.clear();
1659 1660
    }

1661
    /// Returns `true` if this set contains the specified integer.
1662
    #[inline]
A
Alexis Beingessner 已提交
1663
    #[stable]
1664
    pub fn contains(&self, value: &uint) -> bool {
1665 1666
        let bitv = &self.bitv;
        *value < bitv.nbits && bitv[*value]
1667 1668
    }

1669 1670
    /// Returns `true` if the set has no elements in common with `other`.
    /// This is equivalent to checking for an empty intersection.
1671
    #[inline]
A
Alexis Beingessner 已提交
1672
    #[stable]
1673
    pub fn is_disjoint(&self, other: &BitvSet) -> bool {
1674
        self.intersection(other).next().is_none()
1675 1676
    }

1677
    /// Returns `true` if the set is a subset of another.
1678
    #[inline]
A
Alexis Beingessner 已提交
1679
    #[stable]
1680
    pub fn is_subset(&self, other: &BitvSet) -> bool {
1681 1682 1683
        let self_bitv = &self.bitv;
        let other_bitv = &other.bitv;
        let other_blocks = blocks_for_bits(other_bitv.len());
1684 1685

        // Check that `self` intersect `other` is self
1686 1687 1688
        self_bitv.blocks().zip(other_bitv.blocks()).all(|(w1, w2)| w1 & w2 == w1) &&
        // Make sure if `self` has any more blocks than `other`, they're all 0
        self_bitv.blocks().skip(other_blocks).all(|w| w == 0)
1689 1690
    }

1691
    /// Returns `true` if the set is a superset of another.
1692
    #[inline]
A
Alexis Beingessner 已提交
1693
    #[stable]
1694
    pub fn is_superset(&self, other: &BitvSet) -> bool {
1695 1696 1697
        other.is_subset(self)
    }

1698 1699
    /// Adds a value to the set. Returns `true` if the value was not already
    /// present in the set.
A
Alexis Beingessner 已提交
1700
    #[stable]
1701
    pub fn insert(&mut self, value: uint) -> bool {
1702 1703 1704
        if self.contains(&value) {
            return false;
        }
1705 1706

        // Ensure we have enough space to hold the new element
1707 1708 1709
        let len = self.bitv.len();
        if value >= len {
            self.bitv.grow(value - len + 1, false)
1710
        }
1711

1712
        self.bitv.set(value, true);
1713 1714 1715
        return true;
    }

1716 1717
    /// Removes a value from the set. Returns `true` if the value was
    /// present in the set.
A
Alexis Beingessner 已提交
1718
    #[stable]
1719
    pub fn remove(&mut self, value: &uint) -> bool {
1720 1721 1722
        if !self.contains(value) {
            return false;
        }
1723 1724 1725

        self.bitv.set(*value, false);

1726 1727 1728 1729
        return true;
    }
}

1730 1731
impl fmt::Show for BitvSet {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1732
        try!(write!(fmt, "BitvSet {{"));
1733 1734 1735 1736 1737
        let mut first = true;
        for n in self.iter() {
            if !first {
                try!(write!(fmt, ", "));
            }
1738
            try!(write!(fmt, "{:?}", n));
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
            first = false;
        }
        write!(fmt, "}}")
    }
}

impl<S: hash::Writer> hash::Hash<S> for BitvSet {
    fn hash(&self, state: &mut S) {
        for pos in self.iter() {
            pos.hash(state);
        }
    }
}

1753
/// An iterator for `BitvSet`.
1754
#[derive(Clone)]
A
Alexis Beingessner 已提交
1755 1756
#[stable]
pub struct SetIter<'a> {
1757 1758
    set: &'a BitvSet,
    next_idx: uint
1759 1760
}

J
Joseph Crail 已提交
1761
/// An iterator combining two `BitvSet` iterators.
1762
#[derive(Clone)]
A
Alexis Beingessner 已提交
1763
struct TwoBitPositions<'a> {
1764 1765
    set: &'a BitvSet,
    other: &'a BitvSet,
1766
    merge: fn(u32, u32) -> u32,
1767
    current_word: u32,
1768 1769 1770
    next_idx: uint
}

A
Alexis Beingessner 已提交
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
#[stable]
pub struct Union<'a>(TwoBitPositions<'a>);
#[stable]
pub struct Intersection<'a>(Take<TwoBitPositions<'a>>);
#[stable]
pub struct Difference<'a>(TwoBitPositions<'a>);
#[stable]
pub struct SymmetricDifference<'a>(TwoBitPositions<'a>);

#[stable]
J
Jorge Aparicio 已提交
1781 1782 1783
impl<'a> Iterator for SetIter<'a> {
    type Item = uint;

1784
    fn next(&mut self) -> Option<uint> {
1785
        while self.next_idx < self.set.bitv.len() {
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
            let idx = self.next_idx;
            self.next_idx += 1;

            if self.set.contains(&idx) {
                return Some(idx);
            }
        }

        return None;
    }

1797
    #[inline]
1798
    fn size_hint(&self) -> (uint, Option<uint>) {
1799
        (0, Some(self.set.bitv.len() - self.next_idx))
1800 1801 1802
    }
}

A
Alexis Beingessner 已提交
1803
#[stable]
J
Jorge Aparicio 已提交
1804 1805 1806
impl<'a> Iterator for TwoBitPositions<'a> {
    type Item = uint;

1807
    fn next(&mut self) -> Option<uint> {
1808 1809
        while self.next_idx < self.set.bitv.len() ||
              self.next_idx < self.other.bitv.len() {
1810
            let bit_idx = self.next_idx % u32::BITS;
1811
            if bit_idx == 0 {
1812 1813
                let s_bitv = &self.set.bitv;
                let o_bitv = &self.other.bitv;
1814 1815
                // Merging the two words is a bit of an awkward dance since
                // one Bitv might be longer than the other
1816
                let word_idx = self.next_idx / u32::BITS;
1817
                let w1 = if word_idx < s_bitv.storage.len() {
1818
                             s_bitv.storage[word_idx]
1819 1820
                         } else { 0 };
                let w2 = if word_idx < o_bitv.storage.len() {
1821
                             o_bitv.storage[word_idx]
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
                         } else { 0 };
                self.current_word = (self.merge)(w1, w2);
            }

            self.next_idx += 1;
            if self.current_word & (1 << bit_idx) != 0 {
                return Some(self.next_idx - 1);
            }
        }
        return None;
    }

1834
    #[inline]
1835
    fn size_hint(&self) -> (uint, Option<uint>) {
1836
        let cap = cmp::max(self.set.bitv.len(), self.other.bitv.len());
1837 1838 1839 1840
        (0, Some(cap - self.next_idx))
    }
}

A
Alexis Beingessner 已提交
1841
#[stable]
J
Jorge Aparicio 已提交
1842 1843 1844
impl<'a> Iterator for Union<'a> {
    type Item = uint;

A
Alexis Beingessner 已提交
1845 1846 1847 1848 1849
    #[inline] fn next(&mut self) -> Option<uint> { self.0.next() }
    #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.0.size_hint() }
}

#[stable]
J
Jorge Aparicio 已提交
1850 1851 1852
impl<'a> Iterator for Intersection<'a> {
    type Item = uint;

A
Alexis Beingessner 已提交
1853 1854 1855
    #[inline] fn next(&mut self) -> Option<uint> { self.0.next() }
    #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.0.size_hint() }
}
1856

A
Alexis Beingessner 已提交
1857
#[stable]
J
Jorge Aparicio 已提交
1858 1859 1860
impl<'a> Iterator for Difference<'a> {
    type Item = uint;

A
Alexis Beingessner 已提交
1861 1862 1863
    #[inline] fn next(&mut self) -> Option<uint> { self.0.next() }
    #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.0.size_hint() }
}
1864

A
Alexis Beingessner 已提交
1865
#[stable]
J
Jorge Aparicio 已提交
1866 1867 1868
impl<'a> Iterator for SymmetricDifference<'a> {
    type Item = uint;

A
Alexis Beingessner 已提交
1869 1870 1871
    #[inline] fn next(&mut self) -> Option<uint> { self.0.next() }
    #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.0.size_hint() }
}
1872 1873


1874 1875
#[cfg(test)]
mod tests {
1876 1877
    use prelude::*;
    use core::u32;
1878

A
Alex Crichton 已提交
1879
    use super::Bitv;
1880

1881
    #[test]
1882
    fn test_to_str() {
1883
        let zerolen = Bitv::new();
A
Alex Crichton 已提交
1884
        assert_eq!(format!("{:?}", zerolen), "");
1885

1886
        let eightbits = Bitv::from_elem(8u, false);
A
Alex Crichton 已提交
1887
        assert_eq!(format!("{:?}", eightbits), "00000000")
1888 1889
    }

1890
    #[test]
1891
    fn test_0_elements() {
1892
        let act = Bitv::new();
A
Alex Crichton 已提交
1893
        let exp = Vec::new();
1894
        assert!(act.eq_vec(exp.as_slice()));
1895
        assert!(act.none() && act.all());
1896 1897 1898
    }

    #[test]
1899
    fn test_1_element() {
1900
        let mut act = Bitv::from_elem(1u, false);
N
Nick Cameron 已提交
1901
        assert!(act.eq_vec(&[false]));
1902
        assert!(act.none() && !act.all());
1903
        act = Bitv::from_elem(1u, true);
N
Nick Cameron 已提交
1904
        assert!(act.eq_vec(&[true]));
1905
        assert!(!act.none() && act.all());
1906 1907
    }

1908
    #[test]
1909
    fn test_2_elements() {
1910
        let mut b = Bitv::from_elem(2, false);
1911 1912
        b.set(0, true);
        b.set(1, false);
A
Alex Crichton 已提交
1913
        assert_eq!(format!("{:?}", b), "10");
1914
        assert!(!b.none() && !b.all());
1915 1916
    }

1917
    #[test]
1918
    fn test_10_elements() {
1919
        let mut act;
1920 1921
        // all 0

1922
        act = Bitv::from_elem(10u, false);
1923
        assert!((act.eq_vec(
N
Nick Cameron 已提交
1924
                    &[false, false, false, false, false, false, false, false, false, false])));
1925
        assert!(act.none() && !act.all());
1926 1927
        // all 1

1928
        act = Bitv::from_elem(10u, true);
N
Nick Cameron 已提交
1929
        assert!((act.eq_vec(&[true, true, true, true, true, true, true, true, true, true])));
1930
        assert!(!act.none() && act.all());
1931 1932
        // mixed

1933
        act = Bitv::from_elem(10u, false);
1934 1935 1936 1937 1938
        act.set(0u, true);
        act.set(1u, true);
        act.set(2u, true);
        act.set(3u, true);
        act.set(4u, true);
N
Nick Cameron 已提交
1939
        assert!((act.eq_vec(&[true, true, true, true, true, false, false, false, false, false])));
1940
        assert!(!act.none() && !act.all());
1941 1942
        // mixed

1943
        act = Bitv::from_elem(10u, false);
1944 1945 1946 1947 1948
        act.set(5u, true);
        act.set(6u, true);
        act.set(7u, true);
        act.set(8u, true);
        act.set(9u, true);
N
Nick Cameron 已提交
1949
        assert!((act.eq_vec(&[false, false, false, false, false, true, true, true, true, true])));
1950
        assert!(!act.none() && !act.all());
1951 1952
        // mixed

1953
        act = Bitv::from_elem(10u, false);
1954 1955 1956 1957
        act.set(0u, true);
        act.set(3u, true);
        act.set(6u, true);
        act.set(9u, true);
N
Nick Cameron 已提交
1958
        assert!((act.eq_vec(&[true, false, false, true, false, false, true, false, false, true])));
1959
        assert!(!act.none() && !act.all());
1960 1961 1962
    }

    #[test]
1963
    fn test_31_elements() {
1964
        let mut act;
1965 1966
        // all 0

1967
        act = Bitv::from_elem(31u, false);
P
Patrick Walton 已提交
1968
        assert!(act.eq_vec(
N
Nick Cameron 已提交
1969 1970 1971
                &[false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, false, false, false, false]));
1972
        assert!(act.none() && !act.all());
1973 1974
        // all 1

1975
        act = Bitv::from_elem(31u, true);
P
Patrick Walton 已提交
1976
        assert!(act.eq_vec(
N
Nick Cameron 已提交
1977 1978 1979
                &[true, true, true, true, true, true, true, true, true, true, true, true, true,
                  true, true, true, true, true, true, true, true, true, true, true, true, true,
                  true, true, true, true, true]));
1980
        assert!(!act.none() && act.all());
1981 1982
        // mixed

1983
        act = Bitv::from_elem(31u, false);
1984 1985 1986 1987 1988 1989 1990 1991
        act.set(0u, true);
        act.set(1u, true);
        act.set(2u, true);
        act.set(3u, true);
        act.set(4u, true);
        act.set(5u, true);
        act.set(6u, true);
        act.set(7u, true);
P
Patrick Walton 已提交
1992
        assert!(act.eq_vec(
N
Nick Cameron 已提交
1993 1994 1995
                &[true, true, true, true, true, true, true, true, false, false, false, false, false,
                  false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, false, false]));
1996
        assert!(!act.none() && !act.all());
1997 1998
        // mixed

1999
        act = Bitv::from_elem(31u, false);
2000 2001 2002 2003 2004 2005 2006 2007
        act.set(16u, true);
        act.set(17u, true);
        act.set(18u, true);
        act.set(19u, true);
        act.set(20u, true);
        act.set(21u, true);
        act.set(22u, true);
        act.set(23u, true);
P
Patrick Walton 已提交
2008
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2009 2010 2011
                &[false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, true, true, true, true, true, true, true, true,
                  false, false, false, false, false, false, false]));
2012
        assert!(!act.none() && !act.all());
2013 2014
        // mixed

2015
        act = Bitv::from_elem(31u, false);
2016 2017 2018 2019 2020 2021 2022
        act.set(24u, true);
        act.set(25u, true);
        act.set(26u, true);
        act.set(27u, true);
        act.set(28u, true);
        act.set(29u, true);
        act.set(30u, true);
P
Patrick Walton 已提交
2023
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2024 2025 2026
                &[false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, false, false, false, false, false, false,
                  false, false, true, true, true, true, true, true, true]));
2027
        assert!(!act.none() && !act.all());
2028 2029
        // mixed

2030
        act = Bitv::from_elem(31u, false);
2031 2032 2033
        act.set(3u, true);
        act.set(17u, true);
        act.set(30u, true);
P
Patrick Walton 已提交
2034
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2035 2036 2037
                &[false, false, false, true, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, true, false, false, false, false, false, false,
                  false, false, false, false, false, false, true]));
2038
        assert!(!act.none() && !act.all());
2039 2040 2041
    }

    #[test]
2042
    fn test_32_elements() {
2043
        let mut act;
2044 2045
        // all 0

2046
        act = Bitv::from_elem(32u, false);
P
Patrick Walton 已提交
2047
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2048 2049 2050
                &[false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, false, false, false, false, false]));
2051
        assert!(act.none() && !act.all());
2052 2053
        // all 1

2054
        act = Bitv::from_elem(32u, true);
P
Patrick Walton 已提交
2055
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2056 2057 2058
                &[true, true, true, true, true, true, true, true, true, true, true, true, true,
                  true, true, true, true, true, true, true, true, true, true, true, true, true,
                  true, true, true, true, true, true]));
2059
        assert!(!act.none() && act.all());
2060 2061
        // mixed

2062
        act = Bitv::from_elem(32u, false);
2063 2064 2065 2066 2067 2068 2069 2070
        act.set(0u, true);
        act.set(1u, true);
        act.set(2u, true);
        act.set(3u, true);
        act.set(4u, true);
        act.set(5u, true);
        act.set(6u, true);
        act.set(7u, true);
P
Patrick Walton 已提交
2071
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2072 2073 2074
                &[true, true, true, true, true, true, true, true, false, false, false, false, false,
                  false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, false, false, false]));
2075
        assert!(!act.none() && !act.all());
2076 2077
        // mixed

2078
        act = Bitv::from_elem(32u, false);
2079 2080 2081 2082 2083 2084 2085 2086
        act.set(16u, true);
        act.set(17u, true);
        act.set(18u, true);
        act.set(19u, true);
        act.set(20u, true);
        act.set(21u, true);
        act.set(22u, true);
        act.set(23u, true);
P
Patrick Walton 已提交
2087
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2088 2089 2090
                &[false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, true, true, true, true, true, true, true, true,
                  false, false, false, false, false, false, false, false]));
2091
        assert!(!act.none() && !act.all());
2092 2093
        // mixed

2094
        act = Bitv::from_elem(32u, false);
2095 2096 2097 2098 2099 2100 2101 2102
        act.set(24u, true);
        act.set(25u, true);
        act.set(26u, true);
        act.set(27u, true);
        act.set(28u, true);
        act.set(29u, true);
        act.set(30u, true);
        act.set(31u, true);
P
Patrick Walton 已提交
2103
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2104 2105 2106
                &[false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, false, false, false, false, false, false,
                  false, false, true, true, true, true, true, true, true, true]));
2107
        assert!(!act.none() && !act.all());
2108 2109
        // mixed

2110
        act = Bitv::from_elem(32u, false);
2111 2112 2113 2114
        act.set(3u, true);
        act.set(17u, true);
        act.set(30u, true);
        act.set(31u, true);
P
Patrick Walton 已提交
2115
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2116 2117 2118
                &[false, false, false, true, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, true, false, false, false, false, false, false,
                  false, false, false, false, false, false, true, true]));
2119
        assert!(!act.none() && !act.all());
2120 2121 2122
    }

    #[test]
2123
    fn test_33_elements() {
2124
        let mut act;
2125 2126
        // all 0

2127
        act = Bitv::from_elem(33u, false);
P
Patrick Walton 已提交
2128
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2129 2130 2131
                &[false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, false, false, false, false, false, false]));
2132
        assert!(act.none() && !act.all());
2133 2134
        // all 1

2135
        act = Bitv::from_elem(33u, true);
P
Patrick Walton 已提交
2136
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2137 2138 2139
                &[true, true, true, true, true, true, true, true, true, true, true, true, true,
                  true, true, true, true, true, true, true, true, true, true, true, true, true,
                  true, true, true, true, true, true, true]));
2140
        assert!(!act.none() && act.all());
2141 2142
        // mixed

2143
        act = Bitv::from_elem(33u, false);
2144 2145 2146 2147 2148 2149 2150 2151
        act.set(0u, true);
        act.set(1u, true);
        act.set(2u, true);
        act.set(3u, true);
        act.set(4u, true);
        act.set(5u, true);
        act.set(6u, true);
        act.set(7u, true);
P
Patrick Walton 已提交
2152
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2153 2154 2155
                &[true, true, true, true, true, true, true, true, false, false, false, false, false,
                  false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, false, false, false, false]));
2156
        assert!(!act.none() && !act.all());
2157 2158
        // mixed

2159
        act = Bitv::from_elem(33u, false);
2160 2161 2162 2163 2164 2165 2166 2167
        act.set(16u, true);
        act.set(17u, true);
        act.set(18u, true);
        act.set(19u, true);
        act.set(20u, true);
        act.set(21u, true);
        act.set(22u, true);
        act.set(23u, true);
P
Patrick Walton 已提交
2168
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2169 2170 2171
                &[false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, true, true, true, true, true, true, true, true,
                  false, false, false, false, false, false, false, false, false]));
2172
        assert!(!act.none() && !act.all());
2173 2174
        // mixed

2175
        act = Bitv::from_elem(33u, false);
2176 2177 2178 2179 2180 2181 2182 2183
        act.set(24u, true);
        act.set(25u, true);
        act.set(26u, true);
        act.set(27u, true);
        act.set(28u, true);
        act.set(29u, true);
        act.set(30u, true);
        act.set(31u, true);
P
Patrick Walton 已提交
2184
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2185 2186 2187
                &[false, false, false, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, false, false, false, false, false, false,
                  false, false, true, true, true, true, true, true, true, true, false]));
2188
        assert!(!act.none() && !act.all());
2189 2190
        // mixed

2191
        act = Bitv::from_elem(33u, false);
2192 2193 2194 2195 2196
        act.set(3u, true);
        act.set(17u, true);
        act.set(30u, true);
        act.set(31u, true);
        act.set(32u, true);
P
Patrick Walton 已提交
2197
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2198 2199 2200
                &[false, false, false, true, false, false, false, false, false, false, false, false,
                  false, false, false, false, false, true, false, false, false, false, false, false,
                  false, false, false, false, false, false, true, true, true]));
2201
        assert!(!act.none() && !act.all());
2202 2203
    }

G
Graydon Hoare 已提交
2204
    #[test]
2205
    fn test_equal_differing_sizes() {
2206 2207
        let v0 = Bitv::from_elem(10u, false);
        let v1 = Bitv::from_elem(11u, false);
2208
        assert!(v0 != v1);
G
Graydon Hoare 已提交
2209 2210 2211
    }

    #[test]
2212
    fn test_equal_greatly_differing_sizes() {
2213 2214
        let v0 = Bitv::from_elem(10u, false);
        let v1 = Bitv::from_elem(110u, false);
2215
        assert!(v0 != v1);
G
Graydon Hoare 已提交
2216
    }
2217 2218

    #[test]
2219
    fn test_equal_sneaky_small() {
2220
        let mut a = Bitv::from_elem(1, false);
2221 2222
        a.set(0, true);

2223
        let mut b = Bitv::from_elem(1, true);
2224 2225
        b.set(0, true);

2226
        assert_eq!(a, b);
2227 2228 2229
    }

    #[test]
2230
    fn test_equal_sneaky_big() {
2231
        let mut a = Bitv::from_elem(100, false);
D
Daniel Micay 已提交
2232
        for i in range(0u, 100) {
2233 2234 2235
            a.set(i, true);
        }

2236
        let mut b = Bitv::from_elem(100, true);
D
Daniel Micay 已提交
2237
        for i in range(0u, 100) {
2238 2239 2240
            b.set(i, true);
        }

2241
        assert_eq!(a, b);
2242 2243
    }

2244
    #[test]
2245
    fn test_from_bytes() {
2246
        let bitv = Bitv::from_bytes(&[0b10110110, 0b00000000, 0b11111111]);
2247
        let str = concat!("10110110", "00000000", "11111111");
A
Alex Crichton 已提交
2248
        assert_eq!(format!("{:?}", bitv), str);
2249 2250 2251
    }

    #[test]
2252
    fn test_to_bytes() {
2253
        let mut bv = Bitv::from_elem(3, true);
2254
        bv.set(1, false);
2255
        assert_eq!(bv.to_bytes(), vec!(0b10100000));
2256

2257
        let mut bv = Bitv::from_elem(9, false);
2258 2259
        bv.set(2, true);
        bv.set(8, true);
2260
        assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000));
2261 2262 2263
    }

    #[test]
2264
    fn test_from_bools() {
2265 2266
        let bools = vec![true, false, true, true];
        let bitv: Bitv = bools.iter().map(|n| *n).collect();
A
Alex Crichton 已提交
2267
        assert_eq!(format!("{:?}", bitv), "1011");
2268 2269 2270
    }

    #[test]
2271
    fn test_to_bools() {
2272
        let bools = vec!(false, false, true, false, false, true, true, false);
2273
        assert_eq!(Bitv::from_bytes(&[0b00100110]).iter().collect::<Vec<bool>>(), bools);
2274
    }
2275

S
Steven Fackler 已提交
2276 2277
    #[test]
    fn test_bitv_iterator() {
2278
        let bools = vec![true, false, true, true];
2279
        let bitv: Bitv = bools.iter().map(|n| *n).collect();
S
Steven Fackler 已提交
2280

2281
        assert_eq!(bitv.iter().collect::<Vec<bool>>(), bools);
2282

A
Alex Crichton 已提交
2283
        let long = range(0, 10000).map(|i| i % 2 == 0).collect::<Vec<_>>();
2284 2285
        let bitv: Bitv = long.iter().map(|n| *n).collect();
        assert_eq!(bitv.iter().collect::<Vec<bool>>(), long)
S
Steven Fackler 已提交
2286 2287
    }

2288
    #[test]
2289
    fn test_small_difference() {
2290 2291
        let mut b1 = Bitv::from_elem(3, false);
        let mut b2 = Bitv::from_elem(3, false);
2292 2293 2294 2295
        b1.set(0, true);
        b1.set(1, true);
        b2.set(1, true);
        b2.set(2, true);
P
Patrick Walton 已提交
2296
        assert!(b1.difference(&b2));
2297 2298 2299
        assert!(b1[0]);
        assert!(!b1[1]);
        assert!(!b1[2]);
2300 2301 2302
    }

    #[test]
2303
    fn test_big_difference() {
2304 2305
        let mut b1 = Bitv::from_elem(100, false);
        let mut b2 = Bitv::from_elem(100, false);
2306 2307 2308 2309
        b1.set(0, true);
        b1.set(40, true);
        b2.set(40, true);
        b2.set(80, true);
P
Patrick Walton 已提交
2310
        assert!(b1.difference(&b2));
2311 2312 2313
        assert!(b1[0]);
        assert!(!b1[40]);
        assert!(!b1[80]);
2314
    }
2315 2316

    #[test]
2317
    fn test_small_clear() {
2318
        let mut b = Bitv::from_elem(14, true);
2319
        assert!(!b.none() && b.all());
2320
        b.clear();
2321
        assert!(b.none() && !b.all());
2322 2323 2324
    }

    #[test]
2325
    fn test_big_clear() {
2326
        let mut b = Bitv::from_elem(140, true);
2327
        assert!(!b.none() && b.all());
2328
        b.clear();
2329
        assert!(b.none() && !b.all());
2330 2331
    }

2332
    #[test]
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
    fn test_bitv_lt() {
        let mut a = Bitv::from_elem(5u, false);
        let mut b = Bitv::from_elem(5u, false);

        assert!(!(a < b) && !(b < a));
        b.set(2, true);
        assert!(a < b);
        a.set(3, true);
        assert!(a < b);
        a.set(2, true);
        assert!(!(a < b) && b < a);
        b.set(0, true);
        assert!(a < b);
2346 2347
    }

2348
    #[test]
2349 2350 2351
    fn test_ord() {
        let mut a = Bitv::from_elem(5u, false);
        let mut b = Bitv::from_elem(5u, false);
2352

2353 2354 2355 2356 2357 2358 2359 2360
        assert!(a <= b && a >= b);
        a.set(1, true);
        assert!(a > b && a >= b);
        assert!(b < a && b <= a);
        b.set(1, true);
        b.set(2, true);
        assert!(b > a && b >= a);
        assert!(a < b && a <= b);
2361 2362 2363
    }


2364 2365 2366 2367 2368 2369
    #[test]
    fn test_small_bitv_tests() {
        let v = Bitv::from_bytes(&[0]);
        assert!(!v.all());
        assert!(!v.any());
        assert!(v.none());
2370

2371 2372 2373 2374
        let v = Bitv::from_bytes(&[0b00010100]);
        assert!(!v.all());
        assert!(v.any());
        assert!(!v.none());
2375

2376 2377 2378 2379
        let v = Bitv::from_bytes(&[0xFF]);
        assert!(v.all());
        assert!(v.any());
        assert!(!v.none());
2380 2381 2382
    }

    #[test]
2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505
    fn test_big_bitv_tests() {
        let v = Bitv::from_bytes(&[ // 88 bits
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0]);
        assert!(!v.all());
        assert!(!v.any());
        assert!(v.none());

        let v = Bitv::from_bytes(&[ // 88 bits
            0, 0, 0b00010100, 0,
            0, 0, 0, 0b00110100,
            0, 0, 0]);
        assert!(!v.all());
        assert!(v.any());
        assert!(!v.none());

        let v = Bitv::from_bytes(&[ // 88 bits
            0xFF, 0xFF, 0xFF, 0xFF,
            0xFF, 0xFF, 0xFF, 0xFF,
            0xFF, 0xFF, 0xFF]);
        assert!(v.all());
        assert!(v.any());
        assert!(!v.none());
    }

    #[test]
    fn test_bitv_push_pop() {
        let mut s = Bitv::from_elem(5 * u32::BITS - 2, false);
        assert_eq!(s.len(), 5 * u32::BITS - 2);
        assert_eq!(s[5 * u32::BITS - 3], false);
        s.push(true);
        s.push(true);
        assert_eq!(s[5 * u32::BITS - 2], true);
        assert_eq!(s[5 * u32::BITS - 1], true);
        // Here the internal vector will need to be extended
        s.push(false);
        assert_eq!(s[5 * u32::BITS], false);
        s.push(false);
        assert_eq!(s[5 * u32::BITS + 1], false);
        assert_eq!(s.len(), 5 * u32::BITS + 2);
        // Pop it all off
        assert_eq!(s.pop(), Some(false));
        assert_eq!(s.pop(), Some(false));
        assert_eq!(s.pop(), Some(true));
        assert_eq!(s.pop(), Some(true));
        assert_eq!(s.len(), 5 * u32::BITS - 2);
    }

    #[test]
    fn test_bitv_truncate() {
        let mut s = Bitv::from_elem(5 * u32::BITS, true);

        assert_eq!(s, Bitv::from_elem(5 * u32::BITS, true));
        assert_eq!(s.len(), 5 * u32::BITS);
        s.truncate(4 * u32::BITS);
        assert_eq!(s, Bitv::from_elem(4 * u32::BITS, true));
        assert_eq!(s.len(), 4 * u32::BITS);
        // Truncating to a size > s.len() should be a noop
        s.truncate(5 * u32::BITS);
        assert_eq!(s, Bitv::from_elem(4 * u32::BITS, true));
        assert_eq!(s.len(), 4 * u32::BITS);
        s.truncate(3 * u32::BITS - 10);
        assert_eq!(s, Bitv::from_elem(3 * u32::BITS - 10, true));
        assert_eq!(s.len(), 3 * u32::BITS - 10);
        s.truncate(0);
        assert_eq!(s, Bitv::from_elem(0, true));
        assert_eq!(s.len(), 0);
    }

    #[test]
    fn test_bitv_reserve() {
        let mut s = Bitv::from_elem(5 * u32::BITS, true);
        // Check capacity
        assert!(s.capacity() >= 5 * u32::BITS);
        s.reserve(2 * u32::BITS);
        assert!(s.capacity() >= 7 * u32::BITS);
        s.reserve(7 * u32::BITS);
        assert!(s.capacity() >= 12 * u32::BITS);
        s.reserve_exact(7 * u32::BITS);
        assert!(s.capacity() >= 12 * u32::BITS);
        s.reserve(7 * u32::BITS + 1);
        assert!(s.capacity() >= 12 * u32::BITS + 1);
        // Check that length hasn't changed
        assert_eq!(s.len(), 5 * u32::BITS);
        s.push(true);
        s.push(false);
        s.push(true);
        assert_eq!(s[5 * u32::BITS - 1], true);
        assert_eq!(s[5 * u32::BITS - 0], true);
        assert_eq!(s[5 * u32::BITS + 1], false);
        assert_eq!(s[5 * u32::BITS + 2], true);
    }

    #[test]
    fn test_bitv_grow() {
        let mut bitv = Bitv::from_bytes(&[0b10110110, 0b00000000, 0b10101010]);
        bitv.grow(32, true);
        assert_eq!(bitv, Bitv::from_bytes(&[0b10110110, 0b00000000, 0b10101010,
                                     0xFF, 0xFF, 0xFF, 0xFF]));
        bitv.grow(64, false);
        assert_eq!(bitv, Bitv::from_bytes(&[0b10110110, 0b00000000, 0b10101010,
                                     0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0]));
        bitv.grow(16, true);
        assert_eq!(bitv, Bitv::from_bytes(&[0b10110110, 0b00000000, 0b10101010,
                                     0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]));
    }

    #[test]
    fn test_bitv_extend() {
        let mut bitv = Bitv::from_bytes(&[0b10110110, 0b00000000, 0b11111111]);
        let ext = Bitv::from_bytes(&[0b01001001, 0b10010010, 0b10111101]);
        bitv.extend(ext.iter());
        assert_eq!(bitv, Bitv::from_bytes(&[0b10110110, 0b00000000, 0b11111111,
                                     0b01001001, 0b10010010, 0b10111101]));
    }
}




#[cfg(test)]
mod bitv_bench {
2506
    use std::prelude::v1::*;
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612
    use std::rand;
    use std::rand::Rng;
    use std::u32;
    use test::{Bencher, black_box};

    use super::Bitv;

    static BENCH_BITS : uint = 1 << 14;

    fn rng() -> rand::IsaacRng {
        let seed: &[_] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
        rand::SeedableRng::from_seed(seed)
    }

    #[bench]
    fn bench_uint_small(b: &mut Bencher) {
        let mut r = rng();
        let mut bitv = 0 as uint;
        b.iter(|| {
            for _ in range(0u, 100) {
                bitv |= 1 << ((r.next_u32() as uint) % u32::BITS);
            }
            black_box(&bitv)
        });
    }

    #[bench]
    fn bench_bitv_set_big_fixed(b: &mut Bencher) {
        let mut r = rng();
        let mut bitv = Bitv::from_elem(BENCH_BITS, false);
        b.iter(|| {
            for _ in range(0u, 100) {
                bitv.set((r.next_u32() as uint) % BENCH_BITS, true);
            }
            black_box(&bitv)
        });
    }

    #[bench]
    fn bench_bitv_set_big_variable(b: &mut Bencher) {
        let mut r = rng();
        let mut bitv = Bitv::from_elem(BENCH_BITS, false);
        b.iter(|| {
            for _ in range(0u, 100) {
                bitv.set((r.next_u32() as uint) % BENCH_BITS, r.gen());
            }
            black_box(&bitv);
        });
    }

    #[bench]
    fn bench_bitv_set_small(b: &mut Bencher) {
        let mut r = rng();
        let mut bitv = Bitv::from_elem(u32::BITS, false);
        b.iter(|| {
            for _ in range(0u, 100) {
                bitv.set((r.next_u32() as uint) % u32::BITS, true);
            }
            black_box(&bitv);
        });
    }

    #[bench]
    fn bench_bitv_big_union(b: &mut Bencher) {
        let mut b1 = Bitv::from_elem(BENCH_BITS, false);
        let b2 = Bitv::from_elem(BENCH_BITS, false);
        b.iter(|| {
            b1.union(&b2)
        })
    }

    #[bench]
    fn bench_bitv_small_iter(b: &mut Bencher) {
        let bitv = Bitv::from_elem(u32::BITS, false);
        b.iter(|| {
            let mut sum = 0u;
            for _ in range(0u, 10) {
                for pres in bitv.iter() {
                    sum += pres as uint;
                }
            }
            sum
        })
    }

    #[bench]
    fn bench_bitv_big_iter(b: &mut Bencher) {
        let bitv = Bitv::from_elem(BENCH_BITS, false);
        b.iter(|| {
            let mut sum = 0u;
            for pres in bitv.iter() {
                sum += pres as uint;
            }
            sum
        })
    }
}







#[cfg(test)]
mod bitv_set_test {
2613
    use prelude::*;
2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624
    use std::iter::range_step;

    use super::{Bitv, BitvSet};

    #[test]
    fn test_bitv_set_show() {
        let mut s = BitvSet::new();
        s.insert(1);
        s.insert(10);
        s.insert(50);
        s.insert(2);
A
Alex Crichton 已提交
2625
        assert_eq!("BitvSet {1u, 2u, 10u, 50u}", format!("{:?}", s));
2626 2627 2628
    }

    #[test]
2629 2630 2631
    fn test_bitv_set_from_uints() {
        let uints = vec![0, 2, 2, 3];
        let a: BitvSet = uints.into_iter().collect();
2632 2633 2634 2635 2636 2637 2638 2639 2640
        let mut b = BitvSet::new();
        b.insert(0);
        b.insert(2);
        b.insert(3);
        assert_eq!(a, b);
    }

    #[test]
    fn test_bitv_set_iterator() {
2641 2642
        let uints = vec![0, 2, 2, 3];
        let bitv: BitvSet = uints.into_iter().collect();
2643 2644

        let idxs: Vec<uint> = bitv.iter().collect();
2645
        assert_eq!(idxs, vec![0, 2, 3]);
2646

2647
        let long: BitvSet = range(0u, 10000).filter(|&n| n % 2 == 0).collect();
2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
        let real = range_step(0, 10000, 2).collect::<Vec<uint>>();

        let idxs: Vec<uint> = long.iter().collect();
        assert_eq!(idxs, real);
    }

    #[test]
    fn test_bitv_set_frombitv_init() {
        let bools = [true, false];
        let lengths = [10, 64, 100];
        for &b in bools.iter() {
            for &l in lengths.iter() {
                let bitset = BitvSet::from_bitv(Bitv::from_elem(l, b));
2661 2662 2663
                assert_eq!(bitset.contains(&1u), b);
                assert_eq!(bitset.contains(&(l-1u)), b);
                assert!(!bitset.contains(&l));
2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
            }
        }
    }

    #[test]
    fn test_bitv_masking() {
        let b = Bitv::from_elem(140, true);
        let mut bs = BitvSet::from_bitv(b);
        assert!(bs.contains(&139));
        assert!(!bs.contains(&140));
        assert!(bs.insert(150));
        assert!(!bs.contains(&140));
        assert!(!bs.contains(&149));
        assert!(bs.contains(&150));
        assert!(!bs.contains(&151));
    }

    #[test]
    fn test_bitv_set_basic() {
        let mut b = BitvSet::new();
        assert!(b.insert(3));
        assert!(!b.insert(3));
        assert!(b.contains(&3));
        assert!(b.insert(4));
        assert!(!b.insert(4));
        assert!(b.contains(&3));
        assert!(b.insert(400));
        assert!(!b.insert(400));
        assert!(b.contains(&400));
        assert_eq!(b.len(), 3);
    }

    #[test]
    fn test_bitv_set_intersection() {
        let mut a = BitvSet::new();
        let mut b = BitvSet::new();

        assert!(a.insert(11));
P
Patrick Walton 已提交
2702 2703 2704 2705 2706
        assert!(a.insert(1));
        assert!(a.insert(3));
        assert!(a.insert(77));
        assert!(a.insert(103));
        assert!(a.insert(5));
2707

P
Patrick Walton 已提交
2708 2709 2710 2711 2712
        assert!(b.insert(2));
        assert!(b.insert(11));
        assert!(b.insert(77));
        assert!(b.insert(5));
        assert!(b.insert(3));
2713 2714

        let expected = [3, 5, 11, 77];
2715
        let actual = a.intersection(&b).collect::<Vec<uint>>();
2716
        assert_eq!(actual, expected);
2717 2718 2719 2720 2721 2722 2723
    }

    #[test]
    fn test_bitv_set_difference() {
        let mut a = BitvSet::new();
        let mut b = BitvSet::new();

P
Patrick Walton 已提交
2724 2725 2726 2727 2728
        assert!(a.insert(1));
        assert!(a.insert(3));
        assert!(a.insert(5));
        assert!(a.insert(200));
        assert!(a.insert(500));
2729

P
Patrick Walton 已提交
2730 2731
        assert!(b.insert(3));
        assert!(b.insert(200));
2732 2733

        let expected = [1, 5, 500];
2734
        let actual = a.difference(&b).collect::<Vec<uint>>();
2735
        assert_eq!(actual, expected);
2736 2737 2738 2739 2740 2741 2742
    }

    #[test]
    fn test_bitv_set_symmetric_difference() {
        let mut a = BitvSet::new();
        let mut b = BitvSet::new();

P
Patrick Walton 已提交
2743 2744 2745 2746 2747
        assert!(a.insert(1));
        assert!(a.insert(3));
        assert!(a.insert(5));
        assert!(a.insert(9));
        assert!(a.insert(11));
2748

P
Patrick Walton 已提交
2749 2750 2751 2752
        assert!(b.insert(3));
        assert!(b.insert(9));
        assert!(b.insert(14));
        assert!(b.insert(220));
2753 2754

        let expected = [1, 5, 11, 14, 220];
2755
        let actual = a.symmetric_difference(&b).collect::<Vec<uint>>();
2756
        assert_eq!(actual, expected);
2757 2758 2759
    }

    #[test]
2760
    fn test_bitv_set_union() {
2761 2762
        let mut a = BitvSet::new();
        let mut b = BitvSet::new();
P
Patrick Walton 已提交
2763 2764 2765 2766 2767 2768 2769 2770
        assert!(a.insert(1));
        assert!(a.insert(3));
        assert!(a.insert(5));
        assert!(a.insert(9));
        assert!(a.insert(11));
        assert!(a.insert(160));
        assert!(a.insert(19));
        assert!(a.insert(24));
2771
        assert!(a.insert(200));
P
Patrick Walton 已提交
2772 2773 2774 2775 2776 2777

        assert!(b.insert(1));
        assert!(b.insert(5));
        assert!(b.insert(9));
        assert!(b.insert(13));
        assert!(b.insert(19));
2778

2779
        let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160, 200];
2780
        let actual = a.union(&b).collect::<Vec<uint>>();
2781
        assert_eq!(actual, expected);
2782 2783
    }

2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809
    #[test]
    fn test_bitv_set_subset() {
        let mut set1 = BitvSet::new();
        let mut set2 = BitvSet::new();

        assert!(set1.is_subset(&set2)); //  {}  {}
        set2.insert(100);
        assert!(set1.is_subset(&set2)); //  {}  { 1 }
        set2.insert(200);
        assert!(set1.is_subset(&set2)); //  {}  { 1, 2 }
        set1.insert(200);
        assert!(set1.is_subset(&set2)); //  { 2 }  { 1, 2 }
        set1.insert(300);
        assert!(!set1.is_subset(&set2)); // { 2, 3 }  { 1, 2 }
        set2.insert(300);
        assert!(set1.is_subset(&set2)); // { 2, 3 }  { 1, 2, 3 }
        set2.insert(400);
        assert!(set1.is_subset(&set2)); // { 2, 3 }  { 1, 2, 3, 4 }
        set2.remove(&100);
        assert!(set1.is_subset(&set2)); // { 2, 3 }  { 2, 3, 4 }
        set2.remove(&300);
        assert!(!set1.is_subset(&set2)); // { 2, 3 }  { 2, 4 }
        set1.remove(&300);
        assert!(set1.is_subset(&set2)); // { 2 }  { 2, 4 }
    }

2810 2811
    #[test]
    fn test_bitv_set_is_disjoint() {
2812 2813
        let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
        let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01000000]));
2814
        let c = BitvSet::new();
2815
        let d = BitvSet::from_bitv(Bitv::from_bytes(&[0b00110000]));
2816 2817 2818 2819

        assert!(!a.is_disjoint(&d));
        assert!(!d.is_disjoint(&a));

2820 2821 2822 2823 2824 2825
        assert!(a.is_disjoint(&b));
        assert!(a.is_disjoint(&c));
        assert!(b.is_disjoint(&a));
        assert!(b.is_disjoint(&c));
        assert!(c.is_disjoint(&a));
        assert!(c.is_disjoint(&b));
2826 2827
    }

2828 2829 2830 2831 2832 2833 2834
    #[test]
    fn test_bitv_set_union_with() {
        //a should grow to include larger elements
        let mut a = BitvSet::new();
        a.insert(0);
        let mut b = BitvSet::new();
        b.insert(5);
2835
        let expected = BitvSet::from_bitv(Bitv::from_bytes(&[0b10000100]));
2836 2837 2838 2839
        a.union_with(&b);
        assert_eq!(a, expected);

        // Standard
2840 2841
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
        let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01100010]));
2842 2843 2844 2845 2846 2847 2848
        let c = a.clone();
        a.union_with(&b);
        b.union_with(&c);
        assert_eq!(a.len(), 4);
        assert_eq!(b.len(), 4);
    }

2849 2850 2851
    #[test]
    fn test_bitv_set_intersect_with() {
        // Explicitly 0'ed bits
2852 2853
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
        let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
2854 2855 2856 2857 2858 2859 2860
        let c = a.clone();
        a.intersect_with(&b);
        b.intersect_with(&c);
        assert!(a.is_empty());
        assert!(b.is_empty());

        // Uninitialized bits should behave like 0's
2861
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2862 2863 2864 2865 2866 2867 2868 2869
        let mut b = BitvSet::new();
        let c = a.clone();
        a.intersect_with(&b);
        b.intersect_with(&c);
        assert!(a.is_empty());
        assert!(b.is_empty());

        // Standard
2870 2871
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
        let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01100010]));
2872 2873 2874 2875 2876 2877 2878
        let c = a.clone();
        a.intersect_with(&b);
        b.intersect_with(&c);
        assert_eq!(a.len(), 2);
        assert_eq!(b.len(), 2);
    }

2879 2880 2881
    #[test]
    fn test_bitv_set_difference_with() {
        // Explicitly 0'ed bits
2882 2883
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
        let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2884 2885 2886 2887 2888
        a.difference_with(&b);
        assert!(a.is_empty());

        // Uninitialized bits should behave like 0's
        let mut a = BitvSet::new();
2889
        let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b11111111]));
2890 2891 2892 2893
        a.difference_with(&b);
        assert!(a.is_empty());

        // Standard
2894 2895
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
        let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01100010]));
2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911
        let c = a.clone();
        a.difference_with(&b);
        b.difference_with(&c);
        assert_eq!(a.len(), 1);
        assert_eq!(b.len(), 1);
    }

    #[test]
    fn test_bitv_set_symmetric_difference_with() {
        //a should grow to include larger elements
        let mut a = BitvSet::new();
        a.insert(0);
        a.insert(1);
        let mut b = BitvSet::new();
        b.insert(1);
        b.insert(5);
2912
        let expected = BitvSet::from_bitv(Bitv::from_bytes(&[0b10000100]));
2913 2914 2915
        a.symmetric_difference_with(&b);
        assert_eq!(a, expected);

2916
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2917 2918 2919 2920 2921 2922
        let b = BitvSet::new();
        let c = a.clone();
        a.symmetric_difference_with(&b);
        assert_eq!(a, c);

        // Standard
2923 2924
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b11100010]));
        let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101010]));
2925 2926 2927 2928 2929 2930 2931
        let c = a.clone();
        a.symmetric_difference_with(&b);
        b.symmetric_difference_with(&c);
        assert_eq!(a.len(), 2);
        assert_eq!(b.len(), 2);
    }

2932 2933
    #[test]
    fn test_bitv_set_eq() {
2934 2935
        let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
        let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947
        let c = BitvSet::new();

        assert!(a == a);
        assert!(a != b);
        assert!(a != c);
        assert!(b == b);
        assert!(b == c);
        assert!(c == c);
    }

    #[test]
    fn test_bitv_set_cmp() {
2948 2949
        let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
        let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
2950 2951 2952 2953 2954 2955 2956 2957 2958 2959
        let c = BitvSet::new();

        assert_eq!(a.cmp(&b), Greater);
        assert_eq!(a.cmp(&c), Greater);
        assert_eq!(b.cmp(&a), Less);
        assert_eq!(b.cmp(&c), Equal);
        assert_eq!(c.cmp(&a), Less);
        assert_eq!(c.cmp(&b), Equal);
    }

2960
    #[test]
2961
    fn test_bitv_remove() {
2962 2963
        let mut a = BitvSet::new();

P
Patrick Walton 已提交
2964 2965
        assert!(a.insert(1));
        assert!(a.remove(&1));
2966

P
Patrick Walton 已提交
2967 2968
        assert!(a.insert(100));
        assert!(a.remove(&100));
2969

P
Patrick Walton 已提交
2970 2971
        assert!(a.insert(1000));
        assert!(a.remove(&1000));
2972
        a.shrink_to_fit();
N
nham 已提交
2973 2974
    }

S
Steven Fackler 已提交
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984
    #[test]
    fn test_bitv_clone() {
        let mut a = BitvSet::new();

        assert!(a.insert(1));
        assert!(a.insert(100));
        assert!(a.insert(1000));

        let mut b = a.clone();

2985
        assert!(a == b);
S
Steven Fackler 已提交
2986 2987 2988 2989 2990 2991 2992

        assert!(b.remove(&1));
        assert!(a.contains(&1));

        assert!(a.remove(&1000));
        assert!(b.contains(&1000));
    }
2993
}
S
Steven Fackler 已提交
2994

2995 2996


2997 2998


2999 3000
#[cfg(test)]
mod bitv_set_bench {
3001
    use std::prelude::v1::*;
3002 3003 3004 3005
    use std::rand;
    use std::rand::Rng;
    use std::u32;
    use test::{Bencher, black_box};
3006

3007
    use super::{Bitv, BitvSet};
3008

3009
    static BENCH_BITS : uint = 1 << 14;
S
Steven Fackler 已提交
3010

3011
    fn rng() -> rand::IsaacRng {
3012
        let seed: &[_] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
3013
        rand::SeedableRng::from_seed(seed)
3014 3015 3016
    }

    #[bench]
3017
    fn bench_bitvset_small(b: &mut Bencher) {
P
Patrick Walton 已提交
3018
        let mut r = rng();
3019
        let mut bitv = BitvSet::new();
3020
        b.iter(|| {
3021
            for _ in range(0u, 100) {
3022
                bitv.insert((r.next_u32() as uint) % u32::BITS);
3023
            }
3024 3025
            black_box(&bitv);
        });
3026 3027 3028
    }

    #[bench]
3029
    fn bench_bitvset_big(b: &mut Bencher) {
P
Patrick Walton 已提交
3030
        let mut r = rng();
3031
        let mut bitv = BitvSet::new();
3032
        b.iter(|| {
3033 3034 3035
            for _ in range(0u, 100) {
                bitv.insert((r.next_u32() as uint) % BENCH_BITS);
            }
3036 3037
            black_box(&bitv);
        });
3038 3039
    }

S
Steven Fackler 已提交
3040
    #[bench]
3041
    fn bench_bitvset_iter(b: &mut Bencher) {
3042
        let bitv = BitvSet::from_bitv(Bitv::from_fn(BENCH_BITS,
S
Steven Fackler 已提交
3043
                                              |idx| {idx % 3 == 0}));
3044
        b.iter(|| {
3045
            let mut sum = 0u;
D
Daniel Micay 已提交
3046
            for idx in bitv.iter() {
3047
                sum += idx as uint;
S
Steven Fackler 已提交
3048
            }
3049
            sum
3050
        })
S
Steven Fackler 已提交
3051
    }
3052
}