bit.rs 89.9 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
//!             // 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
J
Jorge Aparicio 已提交
69
//! let print_primes = 20u;
J
Jonas Hietala 已提交
70
//! print!("The primes below {} are: ", print_primes);
71
//! for x in 0..print_primes {
J
Jonas Hietala 已提交
72 73 74 75 76 77 78 79 80 81 82
//!     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, IntoIterator};
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
fn reverse_bits(byte: u8) -> u8 {
    let mut result = 0;
107
    for i in 0..u8::BITS {
108 109 110 111
        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 std::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
/// ```
159
#[unstable(feature = "collections",
160
           reason = "RFC 509")]
161
pub struct Bitv {
162
    /// Internal representation of the bit vector
163
    storage: Vec<u32>,
164
    /// The number of valid bits in the internal representation
165
    nbits: uint
166
}
167

J
Jorge Aparicio 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181
// 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
        }
    }
}

182 183 184 185 186 187 188 189 190 191 192 193 194 195
/// 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
196 197 198
    }
}

199 200 201 202
/// 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
203 204
}

205
impl Bitv {
T
Tobias Bucher 已提交
206 207 208
    /// 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.
209
    #[inline]
210
    fn process<F>(&mut self, other: &Bitv, mut op: F) -> bool where F: FnMut(u32, u32) -> u32 {
T
Tobias Bucher 已提交
211 212 213
        assert_eq!(self.len(), other.len());
        // This could theoretically be a `debug_assert!`.
        assert_eq!(self.storage.len(), other.storage.len());
214
        let mut changed = false;
215
        for (a, b) in self.blocks_mut().zip(other.blocks()) {
216 217
            let w = op(*a, b);
            if *a != w {
218 219
                changed = true;
                *a = w;
220 221
            }
        }
222
        changed
223
    }
224

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

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

T
Tobias Bucher 已提交
237 238
    /// 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.
239
    fn fix_last_block(&mut self) {
T
Tobias Bucher 已提交
240
        let extra_bits = self.len() % u32::BITS;
241 242 243 244
        if extra_bits > 0 {
            let mask = (1 << extra_bits) - 1;
            let storage_len = self.storage.len();
            self.storage[storage_len - 1] &= mask;
245 246
        }
    }
247

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

P
P1start 已提交
261
    /// Creates a `Bitv` that holds `nbits` elements, setting each element
262
    /// to `bit`.
J
Jonas Hietala 已提交
263
    ///
264
    /// # Examples
J
Jonas Hietala 已提交
265 266 267 268
    ///
    /// ```
    /// use std::collections::Bitv;
    ///
269
    /// let mut bv = Bitv::from_elem(10u, false);
J
Jonas Hietala 已提交
270 271 272 273 274
    /// assert_eq!(bv.len(), 10u);
    /// for x in bv.iter() {
    ///     assert_eq!(x, false);
    /// }
    /// ```
275 276
    pub fn from_elem(nbits: uint, bit: bool) -> Bitv {
        let nblocks = blocks_for_bits(nbits);
277
        let mut bitv = Bitv {
A
Aaron Turon 已提交
278
            storage: repeat(if bit { !0u32 } else { 0u32 }).take(nblocks).collect(),
279
            nbits: nbits
280
        };
281 282 283 284 285 286 287 288 289 290 291
        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*.
B
Brian Anderson 已提交
292
    #[stable(feature = "rust1", since = "1.0.0")]
293 294 295 296
    pub fn with_capacity(nbits: uint) -> Bitv {
        Bitv {
            storage: Vec::with_capacity(blocks_for_bits(nbits)),
            nbits: 0,
297
        }
298
    }
299

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    /// 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 已提交
316 317 318 319 320
        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;

321 322
        bitv.nbits = len;

323
        for i in 0..complete_words {
T
Tobias Bucher 已提交
324
            bitv.storage.push(
325 326 327 328
                ((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 已提交
329 330
            );
        }
331

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

        bitv
341
    }
342

T
Tobias Bucher 已提交
343 344
    /// Creates a `Bitv` of the specified length where the value at each index
    /// is `f(index)`.
J
Jonas Hietala 已提交
345
    ///
346
    /// # Examples
J
Jonas Hietala 已提交
347
    ///
348 349 350 351 352 353 354 355
    /// ```
    /// 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);
356
        for i in 0u..len {
357 358 359 360 361 362
            bitv.set(i, f(i));
        }
        bitv
    }

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

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

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

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

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

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

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

J
Jonas Hietala 已提交
555 556
    /// Returns `true` if all bits are 1.
    ///
557
    /// # Examples
J
Jonas Hietala 已提交
558 559
    ///
    /// ```
560
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
561
    ///
562
    /// let mut bv = Bitv::from_elem(5, true);
J
Jonas Hietala 已提交
563 564 565 566 567
    /// assert_eq!(bv.all(), true);
    ///
    /// bv.set(1, false);
    /// assert_eq!(bv.all(), false);
    /// ```
568
    pub fn all(&self) -> bool {
569
        let mut last_word = !0u32;
570 571 572 573 574 575
        // 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
576
        }) && (last_word == mask_for_bits(self.nbits))
577
    }
578

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

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

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

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

        let len = self.nbits/8 +
                  if self.nbits % 8 == 0 { 0 } else { 1 };
663
        (0..len).map(|i|
664 665 666 667 668 669 670 671
            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 已提交
672
        ).collect()
673 674
    }

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

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

721 722 723 724 725 726
    /// 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 已提交
727
    ///
728
    /// # Examples
J
Jonas Hietala 已提交
729 730
    ///
    /// ```
731
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
732
    ///
733
    /// let mut bv = Bitv::from_elem(3, false);
J
Jonas Hietala 已提交
734 735
    /// bv.reserve(10);
    /// assert_eq!(bv.len(), 3);
736 737
    /// assert!(bv.capacity() >= 13);
    /// ```
B
Brian Anderson 已提交
738
    #[stable(feature = "rust1", since = "1.0.0")]
739 740
    pub fn reserve(&mut self, additional: uint) {
        let desired_cap = self.len().checked_add(additional).expect("capacity overflow");
T
Tobias Bucher 已提交
741 742 743
        let storage_len = self.storage.len();
        if desired_cap > self.capacity() {
            self.storage.reserve(blocks_for_bits(desired_cap) - storage_len);
744 745 746
        }
    }

747 748 749 750 751 752 753 754 755 756
    /// 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 已提交
757
    ///
758
    /// # Examples
J
Jonas Hietala 已提交
759 760
    ///
    /// ```
761
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
762
    ///
763
    /// let mut bv = Bitv::from_elem(3, false);
J
Jonas Hietala 已提交
764 765
    /// bv.reserve(10);
    /// assert_eq!(bv.len(), 3);
766
    /// assert!(bv.capacity() >= 13);
J
Jonas Hietala 已提交
767
    /// ```
B
Brian Anderson 已提交
768
    #[stable(feature = "rust1", since = "1.0.0")]
769 770
    pub fn reserve_exact(&mut self, additional: uint) {
        let desired_cap = self.len().checked_add(additional).expect("capacity overflow");
T
Tobias Bucher 已提交
771 772 773
        let storage_len = self.storage.len();
        if desired_cap > self.capacity() {
            self.storage.reserve_exact(blocks_for_bits(desired_cap) - storage_len);
774 775 776
        }
    }

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

P
P1start 已提交
795
    /// Grows the `Bitv` in-place, adding `n` copies of `value` to the `Bitv`.
796
    ///
797 798 799 800
    /// # Panics
    ///
    /// Panics if the new len overflows a `uint`.
    ///
801
    /// # Examples
802
    ///
J
Jonas Hietala 已提交
803
    /// ```
804
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
805
    ///
806
    /// let mut bv = Bitv::from_bytes(&[0b01001011]);
J
Jonas Hietala 已提交
807
    /// bv.grow(2, true);
808 809
    /// assert_eq!(bv.len(), 10);
    /// assert_eq!(bv.to_bytes(), vec!(0b01001011, 0b11000000));
810 811
    /// ```
    pub fn grow(&mut self, n: uint, value: bool) {
812 813 814 815 816 817
        // 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);
818
        let full_value = if value { !0 } else { 0 };
819

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

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

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

843 844
        // Adjust internal bit count
        self.nbits = new_nbits;
845 846

        self.fix_last_block();
847 848
    }

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

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

    /// Return the total number of bits in this vector
    #[inline]
B
Brian Anderson 已提交
903
    #[stable(feature = "rust1", since = "1.0.0")]
904 905 906 907
    pub fn len(&self) -> uint { self.nbits }

    /// Returns true if there are no bits in this vector
    #[inline]
B
Brian Anderson 已提交
908
    #[stable(feature = "rust1", since = "1.0.0")]
909 910 911 912
    pub fn is_empty(&self) -> bool { self.len() == 0 }

    /// Clears all bits in this vector.
    #[inline]
B
Brian Anderson 已提交
913
    #[stable(feature = "rust1", since = "1.0.0")]
914
    pub fn clear(&mut self) {
915
        for w in &mut self.storage { *w = 0u32; }
916
    }
917
}
918

B
Brian Anderson 已提交
919
#[stable(feature = "rust1", since = "1.0.0")]
920 921
impl Default for Bitv {
    #[inline]
922
    fn default() -> Bitv { Bitv::new() }
923 924
}

B
Brian Anderson 已提交
925
#[stable(feature = "rust1", since = "1.0.0")]
926
impl FromIterator<bool> for Bitv {
J
Jorge Aparicio 已提交
927
    fn from_iter<I:Iterator<Item=bool>>(iterator: I) -> Bitv {
928
        let mut ret = Bitv::new();
929 930 931 932 933
        ret.extend(iterator);
        ret
    }
}

B
Brian Anderson 已提交
934
#[stable(feature = "rust1", since = "1.0.0")]
G
gamazeps 已提交
935
impl Extend<bool> for Bitv {
936
    #[inline]
J
Jorge Aparicio 已提交
937
    fn extend<I: Iterator<Item=bool>>(&mut self, mut iterator: I) {
938
        let (min, _) = iterator.size_hint();
939
        self.reserve(min);
940 941 942 943 944 945
        for element in iterator {
            self.push(element)
        }
    }
}

B
Brian Anderson 已提交
946
#[stable(feature = "rust1", since = "1.0.0")]
947 948 949 950 951 952 953 954 955
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;
956
        self.storage.clone_from(&source.storage);
957 958 959
    }
}

B
Brian Anderson 已提交
960
#[stable(feature = "rust1", since = "1.0.0")]
N
nham 已提交
961 962 963 964 965 966 967
impl PartialOrd for Bitv {
    #[inline]
    fn partial_cmp(&self, other: &Bitv) -> Option<Ordering> {
        iter::order::partial_cmp(self.iter(), other.iter())
    }
}

B
Brian Anderson 已提交
968
#[stable(feature = "rust1", since = "1.0.0")]
969 970 971 972 973 974 975
impl Ord for Bitv {
    #[inline]
    fn cmp(&self, other: &Bitv) -> Ordering {
        iter::order::cmp(self.iter(), other.iter())
    }
}

B
Brian Anderson 已提交
976
#[stable(feature = "rust1", since = "1.0.0")]
977
impl fmt::Debug for Bitv {
S
Steven Fackler 已提交
978
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
979
        for bit in self {
T
Tobias Bucher 已提交
980
            try!(write!(fmt, "{}", if bit { 1u32 } else { 0u32 }));
S
Steven Fackler 已提交
981 982 983 984 985
        }
        Ok(())
    }
}

B
Brian Anderson 已提交
986
#[stable(feature = "rust1", since = "1.0.0")]
987
impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for Bitv {
988 989
    fn hash(&self, state: &mut S) {
        self.nbits.hash(state);
990
        for elem in self.blocks() {
991
            elem.hash(state);
992 993 994 995
        }
    }
}

B
Brian Anderson 已提交
996
#[stable(feature = "rust1", since = "1.0.0")]
997 998 999
impl cmp::PartialEq for Bitv {
    #[inline]
    fn eq(&self, other: &Bitv) -> bool {
1000 1001 1002
        if self.nbits != other.nbits {
            return false;
        }
1003
        self.blocks().zip(other.blocks()).all(|(w1, w2)| w1 == w2)
1004 1005 1006
    }
}

B
Brian Anderson 已提交
1007
#[stable(feature = "rust1", since = "1.0.0")]
1008 1009
impl cmp::Eq for Bitv {}

1010
/// An iterator for `Bitv`.
B
Brian Anderson 已提交
1011
#[stable(feature = "rust1", since = "1.0.0")]
1012
#[derive(Clone)]
A
Alexis Beingessner 已提交
1013
pub struct Iter<'a> {
1014 1015 1016
    bitv: &'a Bitv,
    next_idx: uint,
    end_idx: uint,
1017 1018
}

B
Brian Anderson 已提交
1019
#[stable(feature = "rust1", since = "1.0.0")]
J
Jorge Aparicio 已提交
1020 1021 1022
impl<'a> Iterator for Iter<'a> {
    type Item = bool;

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

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

B
Brian Anderson 已提交
1040
#[stable(feature = "rust1", since = "1.0.0")]
J
Jorge Aparicio 已提交
1041
impl<'a> DoubleEndedIterator for Iter<'a> {
1042 1043 1044 1045
    #[inline]
    fn next_back(&mut self) -> Option<bool> {
        if self.next_idx != self.end_idx {
            self.end_idx -= 1;
1046
            Some(self.bitv[self.end_idx])
1047 1048 1049 1050 1051 1052
        } else {
            None
        }
    }
}

B
Brian Anderson 已提交
1053
#[stable(feature = "rust1", since = "1.0.0")]
J
Jorge Aparicio 已提交
1054
impl<'a> ExactSizeIterator for Iter<'a> {}
1055

B
Brian Anderson 已提交
1056
#[stable(feature = "rust1", since = "1.0.0")]
J
Jorge Aparicio 已提交
1057
impl<'a> RandomAccessIterator for Iter<'a> {
1058 1059 1060 1061 1062 1063
    #[inline]
    fn indexable(&self) -> uint {
        self.end_idx - self.next_idx
    }

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

1073 1074 1075 1076 1077 1078 1079 1080
impl<'a> IntoIterator for &'a Bitv {
    type Iter = Iter<'a>;

    fn into_iter(self) -> Iter<'a> {
        self.iter()
    }
}

1081
/// An implementation of a set using a bit vector as an underlying
J
Jonas Hietala 已提交
1082
/// representation for holding unsigned numerical elements.
1083 1084 1085
///
/// 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
1086
/// as a `uint`.
J
Jonas Hietala 已提交
1087
///
1088
/// # Examples
J
Jonas Hietala 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
///
/// ```
/// 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`
1106
/// let other = BitvSet::from_bitv(Bitv::from_bytes(&[0b11010000]));
J
Jonas Hietala 已提交
1107 1108 1109 1110 1111 1112 1113 1114 1115
///
/// s.union_with(&other);
///
/// // Print 0, 1, 3 in some order
/// for x in s.iter() {
///     println!("{}", x);
/// }
///
/// // Can convert back to a `Bitv`
1116
/// let bv: Bitv = s.into_bitv();
1117
/// assert!(bv[3]);
J
Jonas Hietala 已提交
1118
/// ```
1119
#[derive(Clone)]
1120
#[unstable(feature = "collections",
1121
           reason = "RFC 509")]
1122 1123 1124
pub struct BitvSet {
    bitv: Bitv,
}
1125

B
Brian Anderson 已提交
1126
#[stable(feature = "rust1", since = "1.0.0")]
1127 1128 1129 1130 1131
impl Default for BitvSet {
    #[inline]
    fn default() -> BitvSet { BitvSet::new() }
}

B
Brian Anderson 已提交
1132
#[stable(feature = "rust1", since = "1.0.0")]
1133
impl FromIterator<uint> for BitvSet {
J
Jorge Aparicio 已提交
1134
    fn from_iter<I:Iterator<Item=uint>>(iterator: I) -> BitvSet {
1135 1136 1137 1138 1139 1140
        let mut ret = BitvSet::new();
        ret.extend(iterator);
        ret
    }
}

B
Brian Anderson 已提交
1141
#[stable(feature = "rust1", since = "1.0.0")]
1142
impl Extend<uint> for BitvSet {
1143
    #[inline]
J
Jorge Aparicio 已提交
1144
    fn extend<I: Iterator<Item=uint>>(&mut self, mut iterator: I) {
1145 1146 1147
        for i in iterator {
            self.insert(i);
        }
1148 1149 1150
    }
}

B
Brian Anderson 已提交
1151
#[stable(feature = "rust1", since = "1.0.0")]
1152 1153 1154
impl PartialOrd for BitvSet {
    #[inline]
    fn partial_cmp(&self, other: &BitvSet) -> Option<Ordering> {
1155
        let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1156 1157 1158 1159
        iter::order::partial_cmp(a_iter, b_iter)
    }
}

B
Brian Anderson 已提交
1160
#[stable(feature = "rust1", since = "1.0.0")]
1161 1162 1163
impl Ord for BitvSet {
    #[inline]
    fn cmp(&self, other: &BitvSet) -> Ordering {
1164
        let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1165 1166 1167 1168
        iter::order::cmp(a_iter, b_iter)
    }
}

B
Brian Anderson 已提交
1169
#[stable(feature = "rust1", since = "1.0.0")]
1170 1171 1172
impl cmp::PartialEq for BitvSet {
    #[inline]
    fn eq(&self, other: &BitvSet) -> bool {
1173
        let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1174 1175 1176 1177
        iter::order::eq(a_iter, b_iter)
    }
}

B
Brian Anderson 已提交
1178
#[stable(feature = "rust1", since = "1.0.0")]
1179 1180
impl cmp::Eq for BitvSet {}

1181
impl BitvSet {
1182
    /// Creates a new empty `BitvSet`.
J
Jonas Hietala 已提交
1183
    ///
1184
    /// # Examples
J
Jonas Hietala 已提交
1185 1186 1187
    ///
    /// ```
    /// use std::collections::BitvSet;
1188
    ///
J
Jonas Hietala 已提交
1189 1190
    /// let mut s = BitvSet::new();
    /// ```
1191
    #[inline]
B
Brian Anderson 已提交
1192
    #[stable(feature = "rust1", since = "1.0.0")]
1193
    pub fn new() -> BitvSet {
1194
        BitvSet { bitv: Bitv::new() }
1195 1196
    }

1197
    /// Creates a new `BitvSet` with initially no contents, able to
J
Jonas Hietala 已提交
1198 1199
    /// hold `nbits` elements without resizing.
    ///
1200
    /// # Examples
J
Jonas Hietala 已提交
1201 1202 1203
    ///
    /// ```
    /// use std::collections::BitvSet;
1204
    ///
J
Jonas Hietala 已提交
1205 1206 1207
    /// let mut s = BitvSet::with_capacity(100);
    /// assert!(s.capacity() >= 100);
    /// ```
1208
    #[inline]
B
Brian Anderson 已提交
1209
    #[stable(feature = "rust1", since = "1.0.0")]
1210
    pub fn with_capacity(nbits: uint) -> BitvSet {
1211
        let bitv = Bitv::from_elem(nbits, false);
1212
        BitvSet::from_bitv(bitv)
1213
    }
E
Eric Holk 已提交
1214

1215
    /// Creates a new `BitvSet` from the given bit vector.
J
Jonas Hietala 已提交
1216
    ///
1217
    /// # Examples
J
Jonas Hietala 已提交
1218 1219
    ///
    /// ```
1220
    /// use std::collections::{Bitv, BitvSet};
J
Jonas Hietala 已提交
1221
    ///
1222
    /// let bv = Bitv::from_bytes(&[0b01100000]);
J
Jonas Hietala 已提交
1223 1224 1225 1226 1227 1228 1229
    /// let s = BitvSet::from_bitv(bv);
    ///
    /// // Print 1, 2 in arbitrary order
    /// for x in s.iter() {
    ///     println!("{}", x);
    /// }
    /// ```
1230
    #[inline]
1231 1232
    pub fn from_bitv(bitv: Bitv) -> BitvSet {
        BitvSet { bitv: bitv }
1233 1234 1235 1236
    }

    /// Returns the capacity in bits for this bit vector. Inserting any
    /// element less than this amount will not trigger a resizing.
J
Jonas Hietala 已提交
1237
    ///
1238
    /// # Examples
J
Jonas Hietala 已提交
1239 1240 1241 1242 1243 1244 1245
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::with_capacity(100);
    /// assert!(s.capacity() >= 100);
    /// ```
1246
    #[inline]
B
Brian Anderson 已提交
1247
    #[stable(feature = "rust1", since = "1.0.0")]
1248
    pub fn capacity(&self) -> uint {
1249 1250 1251
        self.bitv.capacity()
    }

1252 1253 1254
    /// 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`.
1255
    ///
1256
    /// The collection may reserve more space to avoid frequent reallocations.
1257 1258 1259 1260 1261 1262 1263 1264
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::new();
1265 1266
    /// s.reserve_len(10);
    /// assert!(s.capacity() >= 10);
1267
    /// ```
B
Brian Anderson 已提交
1268
    #[stable(feature = "rust1", since = "1.0.0")]
1269 1270 1271 1272
    pub fn reserve_len(&mut self, len: uint) {
        let cur_len = self.bitv.len();
        if len >= cur_len {
            self.bitv.reserve(len - cur_len);
1273
        }
1274 1275
    }

1276 1277 1278
    /// 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`.
1279 1280
    ///
    /// Note that the allocator may give the collection more space than it requests. Therefore
1281
    /// capacity can not be relied upon to be precisely minimal. Prefer `reserve_len` if future
1282 1283
    /// insertions are expected.
    ///
J
Jonas Hietala 已提交
1284
    ///
1285
    /// # Examples
J
Jonas Hietala 已提交
1286 1287 1288 1289 1290
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::new();
1291
    /// s.reserve_len_exact(10);
J
Jonas Hietala 已提交
1292 1293
    /// assert!(s.capacity() >= 10);
    /// ```
B
Brian Anderson 已提交
1294
    #[stable(feature = "rust1", since = "1.0.0")]
1295 1296 1297 1298
    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);
1299
        }
1300
    }
1301

1302

P
P1start 已提交
1303
    /// Consumes this set to return the underlying bit vector.
J
Jonas Hietala 已提交
1304
    ///
1305
    /// # Examples
J
Jonas Hietala 已提交
1306 1307 1308 1309 1310 1311 1312 1313
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::new();
    /// s.insert(0);
    /// s.insert(3);
    ///
1314
    /// let bv = s.into_bitv();
1315 1316
    /// assert!(bv[0]);
    /// assert!(bv[3]);
J
Jonas Hietala 已提交
1317
    /// ```
1318
    #[inline]
1319
    pub fn into_bitv(self) -> Bitv {
1320
        self.bitv
1321 1322
    }

P
P1start 已提交
1323
    /// Returns a reference to the underlying bit vector.
J
Jonas Hietala 已提交
1324
    ///
1325
    /// # Examples
J
Jonas Hietala 已提交
1326 1327 1328 1329 1330 1331 1332 1333
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::new();
    /// s.insert(0);
    ///
    /// let bv = s.get_ref();
J
Jonas Hietala 已提交
1334
    /// assert_eq!(bv[0], true);
J
Jonas Hietala 已提交
1335
    /// ```
1336
    #[inline]
A
Alexis Beingessner 已提交
1337
    pub fn get_ref(&self) -> &Bitv {
1338
        &self.bitv
1339 1340
    }

1341
    #[inline]
1342
    fn other_op<F>(&mut self, other: &BitvSet, mut f: F) where F: FnMut(u32, u32) -> u32 {
1343
        // Unwrap Bitvs
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
        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);
        }
1354 1355

        // virtually pad other with 0's for equal lengths
1356 1357 1358 1359
        let mut other_words = {
            let (_, result) = match_words(self_bitv, other_bitv);
            result
        };
1360 1361 1362

        // Apply values found in other
        for (i, w) in other_words {
1363
            let old = self_bitv.storage[i];
1364
            let new = f(old, w);
1365
            self_bitv.storage[i] = new;
1366
        }
1367 1368
    }

P
P1start 已提交
1369
    /// Truncates the underlying vector to the least length required.
J
Jonas Hietala 已提交
1370
    ///
1371
    /// # Examples
J
Jonas Hietala 已提交
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
    ///
    /// ```
    /// 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());
    /// ```
1387
    #[inline]
B
Brian Anderson 已提交
1388
    #[stable(feature = "rust1", since = "1.0.0")]
1389
    pub fn shrink_to_fit(&mut self) {
1390
        let bitv = &mut self.bitv;
1391 1392 1393 1394 1395 1396
        // 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);
1397
        bitv.storage.truncate(trunc_len);
1398
        bitv.nbits = trunc_len * u32::BITS;
1399 1400
    }

1401
    /// Iterator over each u32 stored in the `BitvSet`.
J
Jonas Hietala 已提交
1402
    ///
1403
    /// # Examples
J
Jonas Hietala 已提交
1404 1405
    ///
    /// ```
1406
    /// use std::collections::{Bitv, BitvSet};
J
Jonas Hietala 已提交
1407
    ///
1408
    /// let s = BitvSet::from_bitv(Bitv::from_bytes(&[0b01001010]));
J
Jonas Hietala 已提交
1409 1410 1411 1412 1413 1414
    ///
    /// // Print 1, 4, 6 in arbitrary order
    /// for x in s.iter() {
    ///     println!("{}", x);
    /// }
    /// ```
1415
    #[inline]
B
Brian Anderson 已提交
1416
    #[stable(feature = "rust1", since = "1.0.0")]
A
Alexis Beingessner 已提交
1417 1418
    pub fn iter(&self) -> bitv_set::Iter {
        SetIter {set: self, next_idx: 0u}
1419
    }
1420

1421
    /// Iterator over each u32 stored in `self` union `other`.
J
Jonas Hietala 已提交
1422 1423
    /// See [union_with](#method.union_with) for an efficient in-place version.
    ///
1424
    /// # Examples
J
Jonas Hietala 已提交
1425 1426
    ///
    /// ```
1427
    /// use std::collections::{Bitv, BitvSet};
J
Jonas Hietala 已提交
1428
    ///
1429 1430
    /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
    /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
J
Jonas Hietala 已提交
1431 1432 1433 1434 1435 1436
    ///
    /// // Print 0, 1, 2, 4 in arbitrary order
    /// for x in a.union(&b) {
    ///     println!("{}", x);
    /// }
    /// ```
1437
    #[inline]
B
Brian Anderson 已提交
1438
    #[stable(feature = "rust1", since = "1.0.0")]
A
Alexis Beingessner 已提交
1439
    pub fn union<'a>(&'a self, other: &'a BitvSet) -> Union<'a> {
1440 1441
        fn or(w1: u32, w2: u32) -> u32 { w1 | w2 }

A
Alexis Beingessner 已提交
1442
        Union(TwoBitPositions {
1443 1444
            set: self,
            other: other,
1445
            merge: or,
1446 1447
            current_word: 0u32,
            next_idx: 0u
A
Alexis Beingessner 已提交
1448
        })
1449 1450
    }

1451 1452
    /// Iterator over each uint stored in `self` intersect `other`.
    /// See [intersect_with](#method.intersect_with) for an efficient in-place version.
J
Jonas Hietala 已提交
1453
    ///
1454
    /// # Examples
J
Jonas Hietala 已提交
1455 1456
    ///
    /// ```
1457
    /// use std::collections::{Bitv, BitvSet};
J
Jonas Hietala 已提交
1458
    ///
1459 1460
    /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
    /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
J
Jonas Hietala 已提交
1461
    ///
1462 1463
    /// // Print 2
    /// for x in a.intersection(&b) {
J
Jonas Hietala 已提交
1464 1465 1466
    ///     println!("{}", x);
    /// }
    /// ```
1467
    #[inline]
B
Brian Anderson 已提交
1468
    #[stable(feature = "rust1", since = "1.0.0")]
A
Alexis Beingessner 已提交
1469
    pub fn intersection<'a>(&'a self, other: &'a BitvSet) -> Intersection<'a> {
1470
        fn bitand(w1: u32, w2: u32) -> u32 { w1 & w2 }
1471
        let min = cmp::min(self.bitv.len(), other.bitv.len());
A
Alexis Beingessner 已提交
1472
        Intersection(TwoBitPositions {
1473 1474
            set: self,
            other: other,
1475
            merge: bitand,
1476
            current_word: 0u32,
1477
            next_idx: 0
A
Alexis Beingessner 已提交
1478
        }.take(min))
1479 1480
    }

1481 1482
    /// 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 已提交
1483
    ///
1484
    /// # Examples
J
Jonas Hietala 已提交
1485 1486
    ///
    /// ```
1487
    /// use std::collections::{BitvSet, Bitv};
J
Jonas Hietala 已提交
1488
    ///
1489 1490
    /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
    /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
J
Jonas Hietala 已提交
1491
    ///
1492
    /// // Print 1, 4 in arbitrary order
1493 1494 1495 1496 1497 1498 1499 1500
    /// 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 已提交
1501 1502 1503
    ///     println!("{}", x);
    /// }
    /// ```
1504
    #[inline]
B
Brian Anderson 已提交
1505
    #[stable(feature = "rust1", since = "1.0.0")]
A
Alexis Beingessner 已提交
1506
    pub fn difference<'a>(&'a self, other: &'a BitvSet) -> Difference<'a> {
1507 1508
        fn diff(w1: u32, w2: u32) -> u32 { w1 & !w2 }

A
Alexis Beingessner 已提交
1509
        Difference(TwoBitPositions {
1510 1511
            set: self,
            other: other,
1512
            merge: diff,
1513
            current_word: 0u32,
1514
            next_idx: 0
A
Alexis Beingessner 已提交
1515
        })
1516 1517
    }

1518
    /// Iterator over each u32 stored in the symmetric difference of `self` and `other`.
1519 1520
    /// See [symmetric_difference_with](#method.symmetric_difference_with) for
    /// an efficient in-place version.
J
Jonas Hietala 已提交
1521
    ///
1522
    /// # Examples
J
Jonas Hietala 已提交
1523 1524
    ///
    /// ```
1525
    /// use std::collections::{BitvSet, Bitv};
J
Jonas Hietala 已提交
1526
    ///
1527 1528
    /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
    /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
J
Jonas Hietala 已提交
1529
    ///
1530 1531
    /// // Print 0, 1, 4 in arbitrary order
    /// for x in a.symmetric_difference(&b) {
J
Jonas Hietala 已提交
1532 1533 1534
    ///     println!("{}", x);
    /// }
    /// ```
1535
    #[inline]
B
Brian Anderson 已提交
1536
    #[stable(feature = "rust1", since = "1.0.0")]
A
Alexis Beingessner 已提交
1537
    pub fn symmetric_difference<'a>(&'a self, other: &'a BitvSet) -> SymmetricDifference<'a> {
1538 1539
        fn bitxor(w1: u32, w2: u32) -> u32 { w1 ^ w2 }

A
Alexis Beingessner 已提交
1540
        SymmetricDifference(TwoBitPositions {
1541 1542
            set: self,
            other: other,
1543
            merge: bitxor,
1544
            current_word: 0u32,
1545
            next_idx: 0
A
Alexis Beingessner 已提交
1546
        })
1547 1548
    }

P
P1start 已提交
1549
    /// Unions in-place with the specified other bit vector.
J
Jonas Hietala 已提交
1550
    ///
1551
    /// # Examples
J
Jonas Hietala 已提交
1552 1553
    ///
    /// ```
1554
    /// use std::collections::{BitvSet, Bitv};
J
Jonas Hietala 已提交
1555
    ///
1556 1557 1558 1559
    /// let a   = 0b01101000;
    /// let b   = 0b10100000;
    /// let res = 0b11101000;
    ///
1560 1561 1562
    /// 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 已提交
1563 1564
    ///
    /// a.union_with(&b);
1565
    /// assert_eq!(a, res);
J
Jonas Hietala 已提交
1566
    /// ```
1567 1568 1569 1570 1571
    #[inline]
    pub fn union_with(&mut self, other: &BitvSet) {
        self.other_op(other, |w1, w2| w1 | w2);
    }

P
P1start 已提交
1572
    /// Intersects in-place with the specified other bit vector.
J
Jonas Hietala 已提交
1573
    ///
1574
    /// # Examples
J
Jonas Hietala 已提交
1575 1576
    ///
    /// ```
1577
    /// use std::collections::{BitvSet, Bitv};
J
Jonas Hietala 已提交
1578
    ///
1579 1580 1581 1582
    /// let a   = 0b01101000;
    /// let b   = 0b10100000;
    /// let res = 0b00100000;
    ///
1583 1584 1585
    /// 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 已提交
1586 1587
    ///
    /// a.intersect_with(&b);
1588
    /// assert_eq!(a, res);
J
Jonas Hietala 已提交
1589
    /// ```
1590 1591 1592 1593 1594
    #[inline]
    pub fn intersect_with(&mut self, other: &BitvSet) {
        self.other_op(other, |w1, w2| w1 & w2);
    }

P
P1start 已提交
1595 1596
    /// Makes this bit vector the difference with the specified other bit vector
    /// in-place.
J
Jonas Hietala 已提交
1597
    ///
1598
    /// # Examples
J
Jonas Hietala 已提交
1599 1600
    ///
    /// ```
1601
    /// use std::collections::{BitvSet, Bitv};
J
Jonas Hietala 已提交
1602
    ///
1603 1604 1605 1606 1607
    /// let a   = 0b01101000;
    /// let b   = 0b10100000;
    /// let a_b = 0b01001000; // a - b
    /// let b_a = 0b10000000; // b - a
    ///
1608 1609 1610 1611
    /// 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]));
1612 1613
    ///
    /// bva.difference_with(&bvb);
1614
    /// assert_eq!(bva, bva_b);
J
Jonas Hietala 已提交
1615
    ///
1616 1617
    /// let bva = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
    /// let mut bvb = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
1618 1619
    ///
    /// bvb.difference_with(&bva);
1620
    /// assert_eq!(bvb, bvb_a);
J
Jonas Hietala 已提交
1621
    /// ```
1622 1623 1624 1625 1626
    #[inline]
    pub fn difference_with(&mut self, other: &BitvSet) {
        self.other_op(other, |w1, w2| w1 & !w2);
    }

P
P1start 已提交
1627 1628
    /// Makes this bit vector the symmetric difference with the specified other
    /// bit vector in-place.
J
Jonas Hietala 已提交
1629
    ///
1630
    /// # Examples
J
Jonas Hietala 已提交
1631 1632
    ///
    /// ```
1633
    /// use std::collections::{BitvSet, Bitv};
J
Jonas Hietala 已提交
1634
    ///
1635 1636 1637 1638
    /// let a   = 0b01101000;
    /// let b   = 0b10100000;
    /// let res = 0b11001000;
    ///
1639 1640 1641
    /// 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 已提交
1642 1643
    ///
    /// a.symmetric_difference_with(&b);
1644
    /// assert_eq!(a, res);
J
Jonas Hietala 已提交
1645
    /// ```
1646 1647 1648 1649
    #[inline]
    pub fn symmetric_difference_with(&mut self, other: &BitvSet) {
        self.other_op(other, |w1, w2| w1 ^ w2);
    }
S
Steven Fackler 已提交
1650

1651 1652
    /// Return the number of set bits in this set.
    #[inline]
B
Brian Anderson 已提交
1653
    #[stable(feature = "rust1", since = "1.0.0")]
1654
    pub fn len(&self) -> uint  {
1655
        self.bitv.blocks().fold(0, |acc, n| acc + n.count_ones())
1656 1657
    }

1658
    /// Returns whether there are no bits set in this set
1659
    #[inline]
B
Brian Anderson 已提交
1660
    #[stable(feature = "rust1", since = "1.0.0")]
1661
    pub fn is_empty(&self) -> bool {
1662
        self.bitv.none()
1663
    }
1664

1665
    /// Clears all bits in this set
1666
    #[inline]
B
Brian Anderson 已提交
1667
    #[stable(feature = "rust1", since = "1.0.0")]
1668
    pub fn clear(&mut self) {
1669
        self.bitv.clear();
1670 1671
    }

1672
    /// Returns `true` if this set contains the specified integer.
1673
    #[inline]
B
Brian Anderson 已提交
1674
    #[stable(feature = "rust1", since = "1.0.0")]
1675
    pub fn contains(&self, value: &uint) -> bool {
1676 1677
        let bitv = &self.bitv;
        *value < bitv.nbits && bitv[*value]
1678 1679
    }

1680 1681
    /// Returns `true` if the set has no elements in common with `other`.
    /// This is equivalent to checking for an empty intersection.
1682
    #[inline]
B
Brian Anderson 已提交
1683
    #[stable(feature = "rust1", since = "1.0.0")]
1684
    pub fn is_disjoint(&self, other: &BitvSet) -> bool {
1685
        self.intersection(other).next().is_none()
1686 1687
    }

1688
    /// Returns `true` if the set is a subset of another.
1689
    #[inline]
B
Brian Anderson 已提交
1690
    #[stable(feature = "rust1", since = "1.0.0")]
1691
    pub fn is_subset(&self, other: &BitvSet) -> bool {
1692 1693 1694
        let self_bitv = &self.bitv;
        let other_bitv = &other.bitv;
        let other_blocks = blocks_for_bits(other_bitv.len());
1695 1696

        // Check that `self` intersect `other` is self
1697 1698 1699
        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)
1700 1701
    }

1702
    /// Returns `true` if the set is a superset of another.
1703
    #[inline]
B
Brian Anderson 已提交
1704
    #[stable(feature = "rust1", since = "1.0.0")]
1705
    pub fn is_superset(&self, other: &BitvSet) -> bool {
1706 1707 1708
        other.is_subset(self)
    }

1709 1710
    /// Adds a value to the set. Returns `true` if the value was not already
    /// present in the set.
B
Brian Anderson 已提交
1711
    #[stable(feature = "rust1", since = "1.0.0")]
1712
    pub fn insert(&mut self, value: uint) -> bool {
1713 1714 1715
        if self.contains(&value) {
            return false;
        }
1716 1717

        // Ensure we have enough space to hold the new element
1718 1719 1720
        let len = self.bitv.len();
        if value >= len {
            self.bitv.grow(value - len + 1, false)
1721
        }
1722

1723
        self.bitv.set(value, true);
1724 1725 1726
        return true;
    }

1727 1728
    /// Removes a value from the set. Returns `true` if the value was
    /// present in the set.
B
Brian Anderson 已提交
1729
    #[stable(feature = "rust1", since = "1.0.0")]
1730
    pub fn remove(&mut self, value: &uint) -> bool {
1731 1732 1733
        if !self.contains(value) {
            return false;
        }
1734 1735 1736

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

1737 1738 1739 1740
        return true;
    }
}

1741
#[stable(feature = "rust1", since = "1.0.0")]
1742
impl fmt::Debug for BitvSet {
1743
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1744
        try!(write!(fmt, "BitvSet {{"));
1745
        let mut first = true;
1746
        for n in self {
1747 1748 1749
            if !first {
                try!(write!(fmt, ", "));
            }
1750
            try!(write!(fmt, "{:?}", n));
1751 1752 1753 1754 1755 1756
            first = false;
        }
        write!(fmt, "}}")
    }
}

1757
impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for BitvSet {
1758
    fn hash(&self, state: &mut S) {
1759
        for pos in self {
1760 1761 1762 1763 1764
            pos.hash(state);
        }
    }
}

1765
/// An iterator for `BitvSet`.
1766
#[derive(Clone)]
B
Brian Anderson 已提交
1767
#[stable(feature = "rust1", since = "1.0.0")]
A
Alexis Beingessner 已提交
1768
pub struct SetIter<'a> {
1769 1770
    set: &'a BitvSet,
    next_idx: uint
1771 1772
}

J
Joseph Crail 已提交
1773
/// An iterator combining two `BitvSet` iterators.
1774
#[derive(Clone)]
A
Alexis Beingessner 已提交
1775
struct TwoBitPositions<'a> {
1776 1777
    set: &'a BitvSet,
    other: &'a BitvSet,
1778
    merge: fn(u32, u32) -> u32,
1779
    current_word: u32,
1780 1781 1782
    next_idx: uint
}

B
Brian Anderson 已提交
1783
#[stable(feature = "rust1", since = "1.0.0")]
A
Alexis Beingessner 已提交
1784
pub struct Union<'a>(TwoBitPositions<'a>);
B
Brian Anderson 已提交
1785
#[stable(feature = "rust1", since = "1.0.0")]
A
Alexis Beingessner 已提交
1786
pub struct Intersection<'a>(Take<TwoBitPositions<'a>>);
B
Brian Anderson 已提交
1787
#[stable(feature = "rust1", since = "1.0.0")]
A
Alexis Beingessner 已提交
1788
pub struct Difference<'a>(TwoBitPositions<'a>);
B
Brian Anderson 已提交
1789
#[stable(feature = "rust1", since = "1.0.0")]
A
Alexis Beingessner 已提交
1790 1791
pub struct SymmetricDifference<'a>(TwoBitPositions<'a>);

B
Brian Anderson 已提交
1792
#[stable(feature = "rust1", since = "1.0.0")]
J
Jorge Aparicio 已提交
1793 1794 1795
impl<'a> Iterator for SetIter<'a> {
    type Item = uint;

1796
    fn next(&mut self) -> Option<uint> {
1797
        while self.next_idx < self.set.bitv.len() {
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
            let idx = self.next_idx;
            self.next_idx += 1;

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

        return None;
    }

1809
    #[inline]
1810
    fn size_hint(&self) -> (uint, Option<uint>) {
1811
        (0, Some(self.set.bitv.len() - self.next_idx))
1812 1813 1814
    }
}

B
Brian Anderson 已提交
1815
#[stable(feature = "rust1", since = "1.0.0")]
J
Jorge Aparicio 已提交
1816 1817 1818
impl<'a> Iterator for TwoBitPositions<'a> {
    type Item = uint;

1819
    fn next(&mut self) -> Option<uint> {
1820 1821
        while self.next_idx < self.set.bitv.len() ||
              self.next_idx < self.other.bitv.len() {
1822
            let bit_idx = self.next_idx % u32::BITS;
1823
            if bit_idx == 0 {
1824 1825
                let s_bitv = &self.set.bitv;
                let o_bitv = &self.other.bitv;
1826 1827
                // Merging the two words is a bit of an awkward dance since
                // one Bitv might be longer than the other
1828
                let word_idx = self.next_idx / u32::BITS;
1829
                let w1 = if word_idx < s_bitv.storage.len() {
1830
                             s_bitv.storage[word_idx]
1831 1832
                         } else { 0 };
                let w2 = if word_idx < o_bitv.storage.len() {
1833
                             o_bitv.storage[word_idx]
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
                         } 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;
    }

1846
    #[inline]
1847
    fn size_hint(&self) -> (uint, Option<uint>) {
1848
        let cap = cmp::max(self.set.bitv.len(), self.other.bitv.len());
1849 1850 1851 1852
        (0, Some(cap - self.next_idx))
    }
}

B
Brian Anderson 已提交
1853
#[stable(feature = "rust1", since = "1.0.0")]
J
Jorge Aparicio 已提交
1854 1855 1856
impl<'a> Iterator for Union<'a> {
    type Item = uint;

A
Alexis Beingessner 已提交
1857 1858 1859 1860
    #[inline] fn next(&mut self) -> Option<uint> { self.0.next() }
    #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.0.size_hint() }
}

B
Brian Anderson 已提交
1861
#[stable(feature = "rust1", since = "1.0.0")]
J
Jorge Aparicio 已提交
1862 1863 1864
impl<'a> Iterator for Intersection<'a> {
    type Item = uint;

A
Alexis Beingessner 已提交
1865 1866 1867
    #[inline] fn next(&mut self) -> Option<uint> { self.0.next() }
    #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.0.size_hint() }
}
1868

B
Brian Anderson 已提交
1869
#[stable(feature = "rust1", since = "1.0.0")]
J
Jorge Aparicio 已提交
1870 1871 1872
impl<'a> Iterator for Difference<'a> {
    type Item = uint;

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

B
Brian Anderson 已提交
1877
#[stable(feature = "rust1", since = "1.0.0")]
J
Jorge Aparicio 已提交
1878 1879 1880
impl<'a> Iterator for SymmetricDifference<'a> {
    type Item = uint;

A
Alexis Beingessner 已提交
1881 1882 1883
    #[inline] fn next(&mut self) -> Option<uint> { self.0.next() }
    #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.0.size_hint() }
}
1884

1885 1886 1887 1888 1889 1890 1891
impl<'a> IntoIterator for &'a BitvSet {
    type Iter = SetIter<'a>;

    fn into_iter(self) -> SetIter<'a> {
        self.iter()
    }
}
1892

1893 1894
#[cfg(test)]
mod tests {
1895 1896
    use prelude::*;
    use core::u32;
1897

A
Alex Crichton 已提交
1898
    use super::Bitv;
1899

1900
    #[test]
1901
    fn test_to_str() {
1902
        let zerolen = Bitv::new();
A
Alex Crichton 已提交
1903
        assert_eq!(format!("{:?}", zerolen), "");
1904

1905
        let eightbits = Bitv::from_elem(8u, false);
A
Alex Crichton 已提交
1906
        assert_eq!(format!("{:?}", eightbits), "00000000")
1907 1908
    }

1909
    #[test]
1910
    fn test_0_elements() {
1911
        let act = Bitv::new();
A
Alex Crichton 已提交
1912
        let exp = Vec::new();
1913
        assert!(act.eq_vec(exp.as_slice()));
1914
        assert!(act.none() && act.all());
1915 1916 1917
    }

    #[test]
1918
    fn test_1_element() {
1919
        let mut act = Bitv::from_elem(1u, false);
N
Nick Cameron 已提交
1920
        assert!(act.eq_vec(&[false]));
1921
        assert!(act.none() && !act.all());
1922
        act = Bitv::from_elem(1u, true);
N
Nick Cameron 已提交
1923
        assert!(act.eq_vec(&[true]));
1924
        assert!(!act.none() && act.all());
1925 1926
    }

1927
    #[test]
1928
    fn test_2_elements() {
1929
        let mut b = Bitv::from_elem(2, false);
1930 1931
        b.set(0, true);
        b.set(1, false);
A
Alex Crichton 已提交
1932
        assert_eq!(format!("{:?}", b), "10");
1933
        assert!(!b.none() && !b.all());
1934 1935
    }

1936
    #[test]
1937
    fn test_10_elements() {
1938
        let mut act;
1939 1940
        // all 0

1941
        act = Bitv::from_elem(10u, false);
1942
        assert!((act.eq_vec(
N
Nick Cameron 已提交
1943
                    &[false, false, false, false, false, false, false, false, false, false])));
1944
        assert!(act.none() && !act.all());
1945 1946
        // all 1

1947
        act = Bitv::from_elem(10u, true);
N
Nick Cameron 已提交
1948
        assert!((act.eq_vec(&[true, true, true, true, true, true, true, true, true, true])));
1949
        assert!(!act.none() && act.all());
1950 1951
        // mixed

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

1962
        act = Bitv::from_elem(10u, false);
1963 1964 1965 1966 1967
        act.set(5u, true);
        act.set(6u, true);
        act.set(7u, true);
        act.set(8u, true);
        act.set(9u, true);
N
Nick Cameron 已提交
1968
        assert!((act.eq_vec(&[false, false, false, false, false, true, true, true, true, true])));
1969
        assert!(!act.none() && !act.all());
1970 1971
        // mixed

1972
        act = Bitv::from_elem(10u, false);
1973 1974 1975 1976
        act.set(0u, true);
        act.set(3u, true);
        act.set(6u, true);
        act.set(9u, true);
N
Nick Cameron 已提交
1977
        assert!((act.eq_vec(&[true, false, false, true, false, false, true, false, false, true])));
1978
        assert!(!act.none() && !act.all());
1979 1980 1981
    }

    #[test]
1982
    fn test_31_elements() {
1983
        let mut act;
1984 1985
        // all 0

1986
        act = Bitv::from_elem(31u, false);
P
Patrick Walton 已提交
1987
        assert!(act.eq_vec(
N
Nick Cameron 已提交
1988 1989 1990
                &[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]));
1991
        assert!(act.none() && !act.all());
1992 1993
        // all 1

1994
        act = Bitv::from_elem(31u, true);
P
Patrick Walton 已提交
1995
        assert!(act.eq_vec(
N
Nick Cameron 已提交
1996 1997 1998
                &[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]));
1999
        assert!(!act.none() && act.all());
2000 2001
        // mixed

2002
        act = Bitv::from_elem(31u, false);
2003 2004 2005 2006 2007 2008 2009 2010
        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 已提交
2011
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2012 2013 2014
                &[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]));
2015
        assert!(!act.none() && !act.all());
2016 2017
        // mixed

2018
        act = Bitv::from_elem(31u, false);
2019 2020 2021 2022 2023 2024 2025 2026
        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 已提交
2027
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2028 2029 2030
                &[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]));
2031
        assert!(!act.none() && !act.all());
2032 2033
        // mixed

2034
        act = Bitv::from_elem(31u, false);
2035 2036 2037 2038 2039 2040 2041
        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 已提交
2042
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2043 2044 2045
                &[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]));
2046
        assert!(!act.none() && !act.all());
2047 2048
        // mixed

2049
        act = Bitv::from_elem(31u, false);
2050 2051 2052
        act.set(3u, true);
        act.set(17u, true);
        act.set(30u, true);
P
Patrick Walton 已提交
2053
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2054 2055 2056
                &[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]));
2057
        assert!(!act.none() && !act.all());
2058 2059 2060
    }

    #[test]
2061
    fn test_32_elements() {
2062
        let mut act;
2063 2064
        // all 0

2065
        act = Bitv::from_elem(32u, false);
P
Patrick Walton 已提交
2066
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2067 2068 2069
                &[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]));
2070
        assert!(act.none() && !act.all());
2071 2072
        // all 1

2073
        act = Bitv::from_elem(32u, true);
P
Patrick Walton 已提交
2074
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2075 2076 2077
                &[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]));
2078
        assert!(!act.none() && act.all());
2079 2080
        // mixed

2081
        act = Bitv::from_elem(32u, false);
2082 2083 2084 2085 2086 2087 2088 2089
        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 已提交
2090
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2091 2092 2093
                &[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]));
2094
        assert!(!act.none() && !act.all());
2095 2096
        // mixed

2097
        act = Bitv::from_elem(32u, false);
2098 2099 2100 2101 2102 2103 2104 2105
        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 已提交
2106
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2107 2108 2109
                &[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]));
2110
        assert!(!act.none() && !act.all());
2111 2112
        // mixed

2113
        act = Bitv::from_elem(32u, false);
2114 2115 2116 2117 2118 2119 2120 2121
        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 已提交
2122
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2123 2124 2125
                &[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]));
2126
        assert!(!act.none() && !act.all());
2127 2128
        // mixed

2129
        act = Bitv::from_elem(32u, false);
2130 2131 2132 2133
        act.set(3u, true);
        act.set(17u, true);
        act.set(30u, true);
        act.set(31u, true);
P
Patrick Walton 已提交
2134
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2135 2136 2137
                &[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]));
2138
        assert!(!act.none() && !act.all());
2139 2140 2141
    }

    #[test]
2142
    fn test_33_elements() {
2143
        let mut act;
2144 2145
        // all 0

2146
        act = Bitv::from_elem(33u, false);
P
Patrick Walton 已提交
2147
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2148 2149 2150
                &[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]));
2151
        assert!(act.none() && !act.all());
2152 2153
        // all 1

2154
        act = Bitv::from_elem(33u, true);
P
Patrick Walton 已提交
2155
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2156 2157 2158
                &[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]));
2159
        assert!(!act.none() && act.all());
2160 2161
        // mixed

2162
        act = Bitv::from_elem(33u, false);
2163 2164 2165 2166 2167 2168 2169 2170
        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 已提交
2171
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2172 2173 2174
                &[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]));
2175
        assert!(!act.none() && !act.all());
2176 2177
        // mixed

2178
        act = Bitv::from_elem(33u, false);
2179 2180 2181 2182 2183 2184 2185 2186
        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 已提交
2187
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2188 2189 2190
                &[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]));
2191
        assert!(!act.none() && !act.all());
2192 2193
        // mixed

2194
        act = Bitv::from_elem(33u, false);
2195 2196 2197 2198 2199 2200 2201 2202
        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 已提交
2203
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2204 2205 2206
                &[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]));
2207
        assert!(!act.none() && !act.all());
2208 2209
        // mixed

2210
        act = Bitv::from_elem(33u, false);
2211 2212 2213 2214 2215
        act.set(3u, true);
        act.set(17u, true);
        act.set(30u, true);
        act.set(31u, true);
        act.set(32u, true);
P
Patrick Walton 已提交
2216
        assert!(act.eq_vec(
N
Nick Cameron 已提交
2217 2218 2219
                &[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]));
2220
        assert!(!act.none() && !act.all());
2221 2222
    }

G
Graydon Hoare 已提交
2223
    #[test]
2224
    fn test_equal_differing_sizes() {
2225 2226
        let v0 = Bitv::from_elem(10u, false);
        let v1 = Bitv::from_elem(11u, false);
2227
        assert!(v0 != v1);
G
Graydon Hoare 已提交
2228 2229 2230
    }

    #[test]
2231
    fn test_equal_greatly_differing_sizes() {
2232 2233
        let v0 = Bitv::from_elem(10u, false);
        let v1 = Bitv::from_elem(110u, false);
2234
        assert!(v0 != v1);
G
Graydon Hoare 已提交
2235
    }
2236 2237

    #[test]
2238
    fn test_equal_sneaky_small() {
2239
        let mut a = Bitv::from_elem(1, false);
2240 2241
        a.set(0, true);

2242
        let mut b = Bitv::from_elem(1, true);
2243 2244
        b.set(0, true);

2245
        assert_eq!(a, b);
2246 2247 2248
    }

    #[test]
2249
    fn test_equal_sneaky_big() {
2250
        let mut a = Bitv::from_elem(100, false);
2251
        for i in 0u..100 {
2252 2253 2254
            a.set(i, true);
        }

2255
        let mut b = Bitv::from_elem(100, true);
2256
        for i in 0u..100 {
2257 2258 2259
            b.set(i, true);
        }

2260
        assert_eq!(a, b);
2261 2262
    }

2263
    #[test]
2264
    fn test_from_bytes() {
2265
        let bitv = Bitv::from_bytes(&[0b10110110, 0b00000000, 0b11111111]);
2266
        let str = concat!("10110110", "00000000", "11111111");
A
Alex Crichton 已提交
2267
        assert_eq!(format!("{:?}", bitv), str);
2268 2269 2270
    }

    #[test]
2271
    fn test_to_bytes() {
2272
        let mut bv = Bitv::from_elem(3, true);
2273
        bv.set(1, false);
2274
        assert_eq!(bv.to_bytes(), vec!(0b10100000));
2275

2276
        let mut bv = Bitv::from_elem(9, false);
2277 2278
        bv.set(2, true);
        bv.set(8, true);
2279
        assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000));
2280 2281 2282
    }

    #[test]
2283
    fn test_from_bools() {
2284 2285
        let bools = vec![true, false, true, true];
        let bitv: Bitv = bools.iter().map(|n| *n).collect();
A
Alex Crichton 已提交
2286
        assert_eq!(format!("{:?}", bitv), "1011");
2287 2288 2289
    }

    #[test]
2290
    fn test_to_bools() {
2291
        let bools = vec!(false, false, true, false, false, true, true, false);
2292
        assert_eq!(Bitv::from_bytes(&[0b00100110]).iter().collect::<Vec<bool>>(), bools);
2293
    }
2294

S
Steven Fackler 已提交
2295 2296
    #[test]
    fn test_bitv_iterator() {
2297
        let bools = vec![true, false, true, true];
2298
        let bitv: Bitv = bools.iter().map(|n| *n).collect();
S
Steven Fackler 已提交
2299

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

J
Jorge Aparicio 已提交
2302
        let long = (0i32..10000).map(|i| i % 2 == 0).collect::<Vec<_>>();
2303 2304
        let bitv: Bitv = long.iter().map(|n| *n).collect();
        assert_eq!(bitv.iter().collect::<Vec<bool>>(), long)
S
Steven Fackler 已提交
2305 2306
    }

2307
    #[test]
2308
    fn test_small_difference() {
2309 2310
        let mut b1 = Bitv::from_elem(3, false);
        let mut b2 = Bitv::from_elem(3, false);
2311 2312 2313 2314
        b1.set(0, true);
        b1.set(1, true);
        b2.set(1, true);
        b2.set(2, true);
P
Patrick Walton 已提交
2315
        assert!(b1.difference(&b2));
2316 2317 2318
        assert!(b1[0]);
        assert!(!b1[1]);
        assert!(!b1[2]);
2319 2320 2321
    }

    #[test]
2322
    fn test_big_difference() {
2323 2324
        let mut b1 = Bitv::from_elem(100, false);
        let mut b2 = Bitv::from_elem(100, false);
2325 2326 2327 2328
        b1.set(0, true);
        b1.set(40, true);
        b2.set(40, true);
        b2.set(80, true);
P
Patrick Walton 已提交
2329
        assert!(b1.difference(&b2));
2330 2331 2332
        assert!(b1[0]);
        assert!(!b1[40]);
        assert!(!b1[80]);
2333
    }
2334 2335

    #[test]
2336
    fn test_small_clear() {
2337
        let mut b = Bitv::from_elem(14, true);
2338
        assert!(!b.none() && b.all());
2339
        b.clear();
2340
        assert!(b.none() && !b.all());
2341 2342 2343
    }

    #[test]
2344
    fn test_big_clear() {
2345
        let mut b = Bitv::from_elem(140, true);
2346
        assert!(!b.none() && b.all());
2347
        b.clear();
2348
        assert!(b.none() && !b.all());
2349 2350
    }

2351
    #[test]
2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
    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);
2365 2366
    }

2367
    #[test]
2368 2369 2370
    fn test_ord() {
        let mut a = Bitv::from_elem(5u, false);
        let mut b = Bitv::from_elem(5u, false);
2371

2372 2373 2374 2375 2376 2377 2378 2379
        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);
2380 2381 2382
    }


2383 2384 2385 2386 2387 2388
    #[test]
    fn test_small_bitv_tests() {
        let v = Bitv::from_bytes(&[0]);
        assert!(!v.all());
        assert!(!v.any());
        assert!(v.none());
2389

2390 2391 2392 2393
        let v = Bitv::from_bytes(&[0b00010100]);
        assert!(!v.all());
        assert!(v.any());
        assert!(!v.none());
2394

2395 2396 2397 2398
        let v = Bitv::from_bytes(&[0xFF]);
        assert!(v.all());
        assert!(v.any());
        assert!(!v.none());
2399 2400 2401
    }

    #[test]
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 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524
    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 {
2525
    use std::prelude::v1::*;
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544
    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(|| {
2545
            for _ in 0u..100 {
2546 2547
                bitv |= 1 << ((r.next_u32() as uint) % u32::BITS);
            }
T
Travis Watkins 已提交
2548
            black_box(&bitv);
2549 2550 2551 2552 2553 2554 2555 2556
        });
    }

    #[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(|| {
2557
            for _ in 0u..100 {
2558 2559
                bitv.set((r.next_u32() as uint) % BENCH_BITS, true);
            }
T
Travis Watkins 已提交
2560
            black_box(&bitv);
2561 2562 2563 2564 2565 2566 2567 2568
        });
    }

    #[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(|| {
2569
            for _ in 0u..100 {
2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
                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(|| {
2581
            for _ in 0u..100 {
2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601
                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;
2602
            for _ in 0u..10 {
2603
                for pres in &bitv {
2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
                    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;
2616
            for pres in &bitv {
2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631
                sum += pres as uint;
            }
            sum
        })
    }
}







#[cfg(test)]
mod bitv_set_test {
2632
    use prelude::*;
2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643
    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);
2644
        assert_eq!("BitvSet {1, 2, 10, 50}", format!("{:?}", s));
2645 2646 2647
    }

    #[test]
2648 2649 2650
    fn test_bitv_set_from_uints() {
        let uints = vec![0, 2, 2, 3];
        let a: BitvSet = uints.into_iter().collect();
2651 2652 2653 2654 2655 2656 2657 2658 2659
        let mut b = BitvSet::new();
        b.insert(0);
        b.insert(2);
        b.insert(3);
        assert_eq!(a, b);
    }

    #[test]
    fn test_bitv_set_iterator() {
2660 2661
        let uints = vec![0, 2, 2, 3];
        let bitv: BitvSet = uints.into_iter().collect();
2662 2663

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

2666
        let long: BitvSet = (0u..10000).filter(|&n| n % 2 == 0).collect();
2667 2668 2669 2670 2671 2672 2673 2674 2675 2676
        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];
2677 2678
        for &b in &bools {
            for &l in &lengths {
2679
                let bitset = BitvSet::from_bitv(Bitv::from_elem(l, b));
2680 2681 2682
                assert_eq!(bitset.contains(&1u), b);
                assert_eq!(bitset.contains(&(l-1u)), b);
                assert!(!bitset.contains(&l));
2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
            }
        }
    }

    #[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 已提交
2721 2722 2723 2724 2725
        assert!(a.insert(1));
        assert!(a.insert(3));
        assert!(a.insert(77));
        assert!(a.insert(103));
        assert!(a.insert(5));
2726

P
Patrick Walton 已提交
2727 2728 2729 2730 2731
        assert!(b.insert(2));
        assert!(b.insert(11));
        assert!(b.insert(77));
        assert!(b.insert(5));
        assert!(b.insert(3));
2732 2733

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

    #[test]
    fn test_bitv_set_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(200));
        assert!(a.insert(500));
2748

P
Patrick Walton 已提交
2749 2750
        assert!(b.insert(3));
        assert!(b.insert(200));
2751 2752

        let expected = [1, 5, 500];
2753
        let actual = a.difference(&b).collect::<Vec<uint>>();
2754
        assert_eq!(actual, expected);
2755 2756 2757 2758 2759 2760 2761
    }

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

P
Patrick Walton 已提交
2762 2763 2764 2765 2766
        assert!(a.insert(1));
        assert!(a.insert(3));
        assert!(a.insert(5));
        assert!(a.insert(9));
        assert!(a.insert(11));
2767

P
Patrick Walton 已提交
2768 2769 2770 2771
        assert!(b.insert(3));
        assert!(b.insert(9));
        assert!(b.insert(14));
        assert!(b.insert(220));
2772 2773

        let expected = [1, 5, 11, 14, 220];
2774
        let actual = a.symmetric_difference(&b).collect::<Vec<uint>>();
2775
        assert_eq!(actual, expected);
2776 2777 2778
    }

    #[test]
2779
    fn test_bitv_set_union() {
2780 2781
        let mut a = BitvSet::new();
        let mut b = BitvSet::new();
P
Patrick Walton 已提交
2782 2783 2784 2785 2786 2787 2788 2789
        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));
2790
        assert!(a.insert(200));
P
Patrick Walton 已提交
2791 2792 2793 2794 2795 2796

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

2798
        let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160, 200];
2799
        let actual = a.union(&b).collect::<Vec<uint>>();
2800
        assert_eq!(actual, expected);
2801 2802
    }

2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828
    #[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 }
    }

2829 2830
    #[test]
    fn test_bitv_set_is_disjoint() {
2831 2832
        let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
        let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01000000]));
2833
        let c = BitvSet::new();
2834
        let d = BitvSet::from_bitv(Bitv::from_bytes(&[0b00110000]));
2835 2836 2837 2838

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

2839 2840 2841 2842 2843 2844
        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));
2845 2846
    }

2847 2848 2849 2850 2851 2852 2853
    #[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);
2854
        let expected = BitvSet::from_bitv(Bitv::from_bytes(&[0b10000100]));
2855 2856 2857 2858
        a.union_with(&b);
        assert_eq!(a, expected);

        // Standard
2859 2860
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
        let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01100010]));
2861 2862 2863 2864 2865 2866 2867
        let c = a.clone();
        a.union_with(&b);
        b.union_with(&c);
        assert_eq!(a.len(), 4);
        assert_eq!(b.len(), 4);
    }

2868 2869 2870
    #[test]
    fn test_bitv_set_intersect_with() {
        // Explicitly 0'ed bits
2871 2872
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
        let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
2873 2874 2875 2876 2877 2878 2879
        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
2880
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2881 2882 2883 2884 2885 2886 2887 2888
        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
2889 2890
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
        let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01100010]));
2891 2892 2893 2894 2895 2896 2897
        let c = a.clone();
        a.intersect_with(&b);
        b.intersect_with(&c);
        assert_eq!(a.len(), 2);
        assert_eq!(b.len(), 2);
    }

2898 2899 2900
    #[test]
    fn test_bitv_set_difference_with() {
        // Explicitly 0'ed bits
2901 2902
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
        let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2903 2904 2905 2906 2907
        a.difference_with(&b);
        assert!(a.is_empty());

        // Uninitialized bits should behave like 0's
        let mut a = BitvSet::new();
2908
        let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b11111111]));
2909 2910 2911 2912
        a.difference_with(&b);
        assert!(a.is_empty());

        // Standard
2913 2914
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
        let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01100010]));
2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930
        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);
2931
        let expected = BitvSet::from_bitv(Bitv::from_bytes(&[0b10000100]));
2932 2933 2934
        a.symmetric_difference_with(&b);
        assert_eq!(a, expected);

2935
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2936 2937 2938 2939 2940 2941
        let b = BitvSet::new();
        let c = a.clone();
        a.symmetric_difference_with(&b);
        assert_eq!(a, c);

        // Standard
2942 2943
        let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b11100010]));
        let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101010]));
2944 2945 2946 2947 2948 2949 2950
        let c = a.clone();
        a.symmetric_difference_with(&b);
        b.symmetric_difference_with(&c);
        assert_eq!(a.len(), 2);
        assert_eq!(b.len(), 2);
    }

2951 2952
    #[test]
    fn test_bitv_set_eq() {
2953 2954
        let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
        let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966
        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() {
2967 2968
        let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
        let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
2969 2970 2971 2972 2973 2974 2975 2976 2977 2978
        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);
    }

2979
    #[test]
2980
    fn test_bitv_remove() {
2981 2982
        let mut a = BitvSet::new();

P
Patrick Walton 已提交
2983 2984
        assert!(a.insert(1));
        assert!(a.remove(&1));
2985

P
Patrick Walton 已提交
2986 2987
        assert!(a.insert(100));
        assert!(a.remove(&100));
2988

P
Patrick Walton 已提交
2989 2990
        assert!(a.insert(1000));
        assert!(a.remove(&1000));
2991
        a.shrink_to_fit();
N
nham 已提交
2992 2993
    }

S
Steven Fackler 已提交
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003
    #[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();

3004
        assert!(a == b);
S
Steven Fackler 已提交
3005 3006 3007 3008 3009 3010 3011

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

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

3014 3015


3016 3017


3018 3019
#[cfg(test)]
mod bitv_set_bench {
3020
    use std::prelude::v1::*;
3021 3022 3023 3024
    use std::rand;
    use std::rand::Rng;
    use std::u32;
    use test::{Bencher, black_box};
3025

3026
    use super::{Bitv, BitvSet};
3027

3028
    static BENCH_BITS : uint = 1 << 14;
S
Steven Fackler 已提交
3029

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

    #[bench]
3036
    fn bench_bitvset_small(b: &mut Bencher) {
P
Patrick Walton 已提交
3037
        let mut r = rng();
3038
        let mut bitv = BitvSet::new();
3039
        b.iter(|| {
3040
            for _ in 0u..100 {
3041
                bitv.insert((r.next_u32() as uint) % u32::BITS);
3042
            }
3043 3044
            black_box(&bitv);
        });
3045 3046 3047
    }

    #[bench]
3048
    fn bench_bitvset_big(b: &mut Bencher) {
P
Patrick Walton 已提交
3049
        let mut r = rng();
3050
        let mut bitv = BitvSet::new();
3051
        b.iter(|| {
3052
            for _ in 0u..100 {
3053 3054
                bitv.insert((r.next_u32() as uint) % BENCH_BITS);
            }
3055 3056
            black_box(&bitv);
        });
3057 3058
    }

S
Steven Fackler 已提交
3059
    #[bench]
3060
    fn bench_bitvset_iter(b: &mut Bencher) {
3061
        let bitv = BitvSet::from_bitv(Bitv::from_fn(BENCH_BITS,
S
Steven Fackler 已提交
3062
                                              |idx| {idx % 3 == 0}));
3063
        b.iter(|| {
3064
            let mut sum = 0u;
3065
            for idx in &bitv {
3066
                sum += idx as uint;
S
Steven Fackler 已提交
3067
            }
3068
            sum
3069
        })
S
Steven Fackler 已提交
3070
    }
3071
}