bit.rs 81.3 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.

11 12 13
// 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.

J
Jonas Hietala 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
//! Collections implemented with bit vectors.
//!
//! # Example
//!
//! 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};
//! use std::iter;
//!
//! let max_prime = 10000;
//!
//! // Store the primes as a BitvSet
//! let primes = {
J
Jonas Hietala 已提交
31 32
//!     // Assume all numbers are prime to begin, and then we
//!     // cross off non-primes progressively
J
Jonas Hietala 已提交
33 34 35 36 37 38
//!     let mut bv = Bitv::with_capacity(max_prime, true);
//!
//!     // Neither 0 nor 1 are prime
//!     bv.set(0, false);
//!     bv.set(1, false);
//!
39
//!     for i in iter::range_inclusive(2, (max_prime as f64).sqrt() as uint) {
J
Jonas Hietala 已提交
40
//!         // if i is a prime
J
Jonas Hietala 已提交
41 42
//!         if bv[i] {
//!             // Mark all multiples of i as non-prime (any multiples below i * i
J
Jonas Hietala 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
//!             // will have been marked as non-prime previously)
//!             for j in iter::range_step(i * i, max_prime, i) { bv.set(j, false) }
//!         }
//!     }
//!     BitvSet::from_bitv(bv)
//! };
//!
//! // Simple primality tests below our max bound
//! let print_primes = 20;
//! print!("The primes below {} are: ", print_primes);
//! for x in range(0, print_primes) {
//!     if primes.contains(&x) {
//!         print!("{} ", x);
//!     }
//! }
//! println!("");
//!
//! // We can manipulate the internal Bitv
//! let num_primes = primes.get_ref().iter().filter(|x| *x).count();
//! println!("There are {} primes below {}", num_primes, max_prime);
//! ```

65
use core::prelude::*;
66

67
use core::cmp;
68
use core::default::Default;
69
use core::fmt;
70
use core::iter::{Chain, Enumerate, Repeat, Skip, Take};
N
nham 已提交
71
use core::iter;
72
use core::slice;
73
use core::u32;
74
use std::hash;
75 76

use vec::Vec;
77

78 79
// FIXME(conventions): look, we just need to refactor this whole thing. Inside and out.

80
type MatchWords<'a> = Chain<MaskWords<'a>, Skip<Take<Enumerate<Repeat<u32>>>>>;
81 82
// Take two BitV's, and return iterators of their words, where the shorter one
// has been padded with 0's
83 84 85 86 87 88
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 {
89 90
        (a.mask_words(0).chain(Repeat::new(0u32).enumerate().take(b_len).skip(a_len)),
         b.mask_words(0).chain(Repeat::new(0u32).enumerate().take(0).skip(0)))
91
    } else {
92 93
        (a.mask_words(0).chain(Repeat::new(0u32).enumerate().take(0).skip(0)),
         b.mask_words(0).chain(Repeat::new(0u32).enumerate().take(a_len).skip(b_len)))
94 95
    }
}
96 97 98 99

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

P
P1start 已提交
100
/// The bitvector type.
J
Joseph Crail 已提交
101 102 103 104
///
/// # Example
///
/// ```rust
105
/// use collections::Bitv;
J
Joseph Crail 已提交
106
///
107
/// let mut bv = Bitv::with_capacity(10, false);
J
Joseph Crail 已提交
108 109 110 111 112 113
///
/// // insert all primes less than 10
/// bv.set(2, true);
/// bv.set(3, true);
/// bv.set(5, true);
/// bv.set(7, true);
114
/// println!("{}", bv.to_string());
A
Aaron Turon 已提交
115
/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
J
Joseph Crail 已提交
116 117 118
///
/// // flip all values in bitvector, producing non-primes less than 10
/// bv.negate();
119
/// println!("{}", bv.to_string());
A
Aaron Turon 已提交
120
/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
J
Joseph Crail 已提交
121 122 123
///
/// // reset bitvector to empty
/// bv.clear();
124
/// println!("{}", bv.to_string());
A
Aaron Turon 已提交
125
/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
J
Joseph Crail 已提交
126
/// ```
127
pub struct Bitv {
128
    /// Internal representation of the bit vector
129
    storage: Vec<u32>,
130
    /// The number of valid bits in the internal representation
131
    nbits: uint
132
}
133

134 135 136 137 138 139 140 141 142 143 144
impl Index<uint,bool> for Bitv {
    #[inline]
    fn index<'a>(&'a self, i: &uint) -> &'a bool {
        if self.get(*i) {
            &TRUE
        } else {
            &FALSE
        }
    }
}

145
struct MaskWords<'a> {
146 147 148
    iter: slice::Items<'a, u32>,
    next_word: Option<&'a u32>,
    last_word_mask: u32,
149 150 151
    offset: uint
}

152
impl<'a> Iterator<(uint, u32)> for MaskWords<'a> {
153
    /// Returns (offset, word)
154
    #[inline]
155
    fn next<'a>(&'a mut self) -> Option<(uint, u32)> {
156 157 158 159 160 161 162 163 164 165 166 167 168 169
        let ret = self.next_word;
        match ret {
            Some(&w) => {
                self.next_word = self.iter.next();
                self.offset += 1;
                // The last word may need to be masked
                if self.next_word.is_none() {
                    Some((self.offset - 1, w & self.last_word_mask))
                } else {
                    Some((self.offset - 1, w))
                }
            },
            None => None
        }
170 171 172
    }
}

173
impl Bitv {
174
    #[inline]
175
    fn process(&mut self, other: &Bitv, op: |u32, u32| -> u32) -> bool {
176 177 178
        let len = other.storage.len();
        assert_eq!(self.storage.len(), len);
        let mut changed = false;
179 180 181 182
        // Notice: `a` is *not* masked here, which is fine as long as
        // `op` is a bitwise operation, since any bits that should've
        // been masked were fine to change anyway. `b` is masked to
        // make sure its unmasked bits do not cause damage.
A
Aaron Turon 已提交
183
        for (a, (_, b)) in self.storage.iter_mut()
184 185 186
                           .zip(other.mask_words(0)) {
            let w = op(*a, b);
            if *a != w {
187 188
                changed = true;
                *a = w;
189 190
            }
        }
191
        changed
192
    }
193

194
    #[inline]
195 196 197 198
    fn mask_words<'a>(&'a self, mut start: uint) -> MaskWords<'a> {
        if start > self.storage.len() {
            start = self.storage.len();
        }
199
        let mut iter = self.storage[start..].iter();
200 201 202 203
        MaskWords {
          next_word: iter.next(),
          iter: iter,
          last_word_mask: {
204
              let rem = self.nbits % u32::BITS;
205 206 207 208
              if rem > 0 {
                  (1 << rem) - 1
              } else { !0 }
          },
209 210 211
          offset: start
        }
    }
212

P
P1start 已提交
213
    /// Creates an empty `Bitv`.
J
Jonas Hietala 已提交
214 215 216 217 218 219 220
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::Bitv;
    /// let mut bv = Bitv::new();
    /// ```
221
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
222 223 224 225
    pub fn new() -> Bitv {
        Bitv { storage: Vec::new(), nbits: 0 }
    }

P
P1start 已提交
226
    /// Creates a `Bitv` that holds `nbits` elements, setting each element
J
Joseph Crail 已提交
227
    /// to `init`.
J
Jonas Hietala 已提交
228 229 230 231 232 233 234 235 236 237 238 239
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::Bitv;
    ///
    /// let mut bv = Bitv::with_capacity(10u, false);
    /// assert_eq!(bv.len(), 10u);
    /// for x in bv.iter() {
    ///     assert_eq!(x, false);
    /// }
    /// ```
240
    pub fn with_capacity(nbits: uint, init: bool) -> Bitv {
241
        let mut bitv = Bitv {
242 243
            storage: Vec::from_elem((nbits + u32::BITS - 1) / u32::BITS,
                                    if init { !0u32 } else { 0u32 }),
244
            nbits: nbits
245 246 247
        };

        // Zero out any unused bits in the highest word if necessary
248
        let used_bits = bitv.nbits % u32::BITS;
249
        if init && used_bits != 0 {
250
            let largest_used_word = (bitv.nbits + u32::BITS - 1) / u32::BITS - 1;
251
            bitv.storage[largest_used_word] &= (1 << used_bits) - 1;
252
        }
253 254

        bitv
255
    }
256

P
P1start 已提交
257
    /// Retrieves the value at index `i`.
J
Jonas Hietala 已提交
258 259 260
    ///
    /// # Failure
    ///
P
P1start 已提交
261
    /// Fails if `i` is out of bounds.
J
Jonas Hietala 已提交
262 263 264 265
    ///
    /// # Example
    ///
    /// ```
266
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
267
    ///
268
    /// let bv = bitv::from_bytes([0b01100000]);
J
Jonas Hietala 已提交
269 270
    /// assert_eq!(bv.get(0), false);
    /// assert_eq!(bv.get(1), true);
J
Jonas Hietala 已提交
271 272 273
    ///
    /// // Can also use array indexing
    /// assert_eq!(bv[1], true);
J
Jonas Hietala 已提交
274
    /// ```
275
    #[inline]
276
    pub fn get(&self, i: uint) -> bool {
277
        assert!(i < self.nbits);
278 279
        let w = i / u32::BITS;
        let b = i % u32::BITS;
280
        let x = self.storage[w] & (1 << b);
281
        x != 0
282
    }
283

P
P1start 已提交
284
    /// Sets the value of a bit at a index `i`.
J
Jonas Hietala 已提交
285 286 287
    ///
    /// # Failure
    ///
P
P1start 已提交
288
    /// Fails if `i` is out of bounds.
J
Jonas Hietala 已提交
289 290 291 292 293 294 295 296
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::Bitv;
    ///
    /// let mut bv = Bitv::with_capacity(5, false);
    /// bv.set(3, true);
J
Jonas Hietala 已提交
297
    /// assert_eq!(bv[3], true);
J
Jonas Hietala 已提交
298
    /// ```
299
    #[inline]
300
    pub fn set(&mut self, i: uint, x: bool) {
301
        assert!(i < self.nbits);
302 303
        let w = i / u32::BITS;
        let b = i % u32::BITS;
304
        let flag = 1 << b;
305 306 307
        let val = if x { self.storage[w] | flag }
                  else { self.storage[w] & !flag };
        self.storage[w] = val;
308
    }
309

P
P1start 已提交
310
    /// Sets all bits to 1.
J
Jonas Hietala 已提交
311 312 313 314
    ///
    /// # Example
    ///
    /// ```
315
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
316
    ///
317 318 319 320
    /// let before = 0b01100000;
    /// let after  = 0b11111111;
    ///
    /// let mut bv = bitv::from_bytes([before]);
J
Jonas Hietala 已提交
321
    /// bv.set_all();
322 323
    /// assert_eq!(bv, bitv::from_bytes([after]));
    /// ```
324
    #[inline]
325
    pub fn set_all(&mut self) {
326
        for w in self.storage.iter_mut() { *w = !0u32; }
327
    }
328

P
P1start 已提交
329
    /// Flips all bits.
J
Jonas Hietala 已提交
330 331 332 333
    ///
    /// # Example
    ///
    /// ```
334 335 336 337
    /// use std::collections::bitv;
    ///
    /// let before = 0b01100000;
    /// let after  = 0b10011111;
J
Jonas Hietala 已提交
338
    ///
339
    /// let mut bv = bitv::from_bytes([before]);
J
Jonas Hietala 已提交
340
    /// bv.negate();
341 342
    /// assert_eq!(bv, bitv::from_bytes([after]));
    /// ```
343
    #[inline]
D
Daniel Micay 已提交
344
    pub fn negate(&mut self) {
A
Aaron Turon 已提交
345
        for w in self.storage.iter_mut() { *w = !*w; }
346
    }
347

P
P1start 已提交
348 349
    /// Calculates the union of two bitvectors. This acts like the bitwise `or`
    /// function.
J
Jonas Hietala 已提交
350
    ///
P
P1start 已提交
351 352
    /// Sets `self` to the union of `self` and `other`. Both bitvectors must be
    /// the same length. Returns `true` if `self` changed.
J
Jonas Hietala 已提交
353 354 355
    ///
    /// # Failure
    ///
P
P1start 已提交
356
    /// Fails if the bitvectors are of different lengths.
J
Jonas Hietala 已提交
357 358 359 360
    ///
    /// # Example
    ///
    /// ```
361 362 363 364 365
    /// use std::collections::bitv;
    ///
    /// let a   = 0b01100100;
    /// let b   = 0b01011010;
    /// let res = 0b01111110;
J
Jonas Hietala 已提交
366
    ///
367 368
    /// let mut a = bitv::from_bytes([a]);
    /// let b = bitv::from_bytes([b]);
J
Jonas Hietala 已提交
369
    ///
370 371
    /// assert!(a.union(&b));
    /// assert_eq!(a, bitv::from_bytes([res]));
J
Jonas Hietala 已提交
372
    /// ```
373 374 375 376 377
    #[inline]
    pub fn union(&mut self, other: &Bitv) -> bool {
        self.process(other, |w1, w2| w1 | w2)
    }

P
P1start 已提交
378 379
    /// Calculates the intersection of two bitvectors. This acts like the
    /// bitwise `and` function.
J
Jonas Hietala 已提交
380
    ///
P
P1start 已提交
381 382
    /// Sets `self` to the intersection of `self` and `other`. Both bitvectors
    /// must be the same length. Returns `true` if `self` changed.
J
Jonas Hietala 已提交
383 384 385
    ///
    /// # Failure
    ///
P
P1start 已提交
386
    /// Fails if the bitvectors are of different lengths.
J
Jonas Hietala 已提交
387 388 389 390
    ///
    /// # Example
    ///
    /// ```
391
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
392
    ///
393 394 395
    /// let a   = 0b01100100;
    /// let b   = 0b01011010;
    /// let res = 0b01000000;
J
Jonas Hietala 已提交
396
    ///
397 398 399 400 401
    /// let mut a = bitv::from_bytes([a]);
    /// let b = bitv::from_bytes([b]);
    ///
    /// assert!(a.intersect(&b));
    /// assert_eq!(a, bitv::from_bytes([res]));
J
Jonas Hietala 已提交
402
    /// ```
403 404 405 406 407
    #[inline]
    pub fn intersect(&mut self, other: &Bitv) -> bool {
        self.process(other, |w1, w2| w1 & w2)
    }

P
P1start 已提交
408
    /// Calculates the difference between two bitvectors.
J
Jonas Hietala 已提交
409
    ///
P
P1start 已提交
410
    /// Sets each element of `self` to the value of that element minus the
J
Jonas Hietala 已提交
411
    /// element of `other` at the same index. Both bitvectors must be the same
P
P1start 已提交
412
    /// length. Returns `true` if `self` changed.
J
Jonas Hietala 已提交
413 414 415
    ///
    /// # Failure
    ///
P
P1start 已提交
416
    /// Fails if the bitvectors are of different length.
J
Jonas Hietala 已提交
417 418 419 420
    ///
    /// # Example
    ///
    /// ```
421 422 423 424 425 426 427 428 429
    /// use std::collections::bitv;
    ///
    /// let a   = 0b01100100;
    /// let b   = 0b01011010;
    /// let a_b = 0b00100100; // a - b
    /// let b_a = 0b00011010; // b - a
    ///
    /// let mut bva = bitv::from_bytes([a]);
    /// let bvb = bitv::from_bytes([b]);
J
Jonas Hietala 已提交
430
    ///
431 432
    /// assert!(bva.difference(&bvb));
    /// assert_eq!(bva, bitv::from_bytes([a_b]));
J
Jonas Hietala 已提交
433
    ///
434 435 436 437 438
    /// let bva = bitv::from_bytes([a]);
    /// let mut bvb = bitv::from_bytes([b]);
    ///
    /// assert!(bvb.difference(&bva));
    /// assert_eq!(bvb, bitv::from_bytes([b_a]));
J
Jonas Hietala 已提交
439
    /// ```
440
    #[inline]
441
    pub fn difference(&mut self, other: &Bitv) -> bool {
442
        self.process(other, |w1, w2| w1 & !w2)
443
    }
444

J
Jonas Hietala 已提交
445 446 447 448 449
    /// Returns `true` if all bits are 1.
    ///
    /// # Example
    ///
    /// ```
450
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
451 452 453 454 455 456 457
    ///
    /// let mut bv = Bitv::with_capacity(5, true);
    /// assert_eq!(bv.all(), true);
    ///
    /// bv.set(1, false);
    /// assert_eq!(bv.all(), false);
    /// ```
458
    #[inline]
459
    pub fn all(&self) -> bool {
460
        let mut last_word = !0u32;
461 462
        // Check that every word but the last is all-ones...
        self.mask_words(0).all(|(_, elem)|
463
            { let tmp = last_word; last_word = elem; tmp == !0u32 }) &&
464
        // ...and that the last word is ones as far as it needs to be
465
        (last_word == ((1 << self.nbits % u32::BITS) - 1) || last_word == !0u32)
466
    }
467

P
P1start 已提交
468
    /// Returns an iterator over the elements of the vector in order.
J
Joseph Crail 已提交
469 470 471
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
472
    /// ```
473
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
474
    ///
475 476
    /// let bv = bitv::from_bytes([0b01110100, 0b10010010]);
    /// assert_eq!(bv.iter().filter(|x| *x).count(), 7);
J
Joseph Crail 已提交
477
    /// ```
478
    #[inline]
P
Palmer Cox 已提交
479 480
    pub fn iter<'a>(&'a self) -> Bits<'a> {
        Bits {bitv: self, next_idx: 0, end_idx: self.nbits}
A
Alex Crichton 已提交
481
    }
482

P
P1start 已提交
483
    /// Returns `true` if all bits are 0.
J
Jonas Hietala 已提交
484 485 486 487
    ///
    /// # Example
    ///
    /// ```
488
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
489 490 491 492 493 494 495
    ///
    /// let mut bv = Bitv::with_capacity(10, false);
    /// assert_eq!(bv.none(), true);
    ///
    /// bv.set(3, true);
    /// assert_eq!(bv.none(), false);
    /// ```
496
    pub fn none(&self) -> bool {
497
        self.mask_words(0).all(|(_, w)| w == 0)
498
    }
499

P
P1start 已提交
500
    /// Returns `true` if any bit is 1.
J
Jonas Hietala 已提交
501 502 503 504
    ///
    /// # Example
    ///
    /// ```
505
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
506 507 508 509 510 511 512
    ///
    /// let mut bv = Bitv::with_capacity(10, false);
    /// assert_eq!(bv.any(), false);
    ///
    /// bv.set(3, true);
    /// assert_eq!(bv.any(), true);
    /// ```
513 514 515 516 517
    #[inline]
    pub fn any(&self) -> bool {
        !self.none()
    }

P
P1start 已提交
518
    /// Organises the bits into bytes, such that the first bit in the
J
Jonas Hietala 已提交
519
    /// `Bitv` becomes the high-order bit of the first byte. If the
P
P1start 已提交
520
    /// size of the `Bitv` is not a multiple of eight then trailing bits
J
Jonas Hietala 已提交
521
    /// will be filled-in with `false`.
J
Jonas Hietala 已提交
522 523 524 525
    ///
    /// # Example
    ///
    /// ```
526
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
527 528 529 530 531 532 533 534 535 536 537 538
    ///
    /// let mut bv = Bitv::with_capacity(3, true);
    /// bv.set(1, false);
    ///
    /// assert_eq!(bv.to_bytes(), vec!(0b10100000));
    ///
    /// let mut bv = Bitv::with_capacity(9, false);
    /// bv.set(2, true);
    /// bv.set(8, true);
    ///
    /// assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000));
    /// ```
539
    pub fn to_bytes(&self) -> Vec<u8> {
540 541 542 543 544
        fn bit (bitv: &Bitv, byte: uint, bit: uint) -> u8 {
            let offset = byte * 8 + bit;
            if offset >= bitv.nbits {
                0
            } else {
545
                bitv.get(offset) as u8 << (7 - bit)
546 547 548 549 550
            }
        }

        let len = self.nbits/8 +
                  if self.nbits % 8 == 0 { 0 } else { 1 };
551
        Vec::from_fn(len, |i|
552 553 554 555 556 557 558 559
            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)
560 561 562
        )
    }

P
P1start 已提交
563
    /// Transforms `self` into a `Vec<bool>` by turning each bit into a `bool`.
J
Jonas Hietala 已提交
564 565 566 567
    ///
    /// # Example
    ///
    /// ```
568
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
569
    ///
570 571 572
    /// let bv = bitv::from_bytes([0b10100000]);
    /// assert_eq!(bv.to_bools(), vec!(true, false, true, false,
    ///                                false, false, false, false));
J
Jonas Hietala 已提交
573
    /// ```
574 575 576 577
    pub fn to_bools(&self) -> Vec<bool> {
        Vec::from_fn(self.nbits, |i| self.get(i))
    }

P
P1start 已提交
578 579 580
    /// Compares a `Bitv` to a slice of `bool`s.
    /// Both the `Bitv` and slice must have the same length.
    ///
J
Jonas Hietala 已提交
581 582
    /// # Failure
    ///
P
P1start 已提交
583
    /// Fails if the the `Bitv` and slice are of different length.
J
Jonas Hietala 已提交
584 585 586 587
    ///
    /// # Example
    ///
    /// ```
588
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
589
    ///
590
    /// let bv = bitv::from_bytes([0b10100000]);
J
Jonas Hietala 已提交
591
    ///
592 593
    /// assert!(bv.eq_vec([true, false, true, false,
    ///                    false, false, false, false]));
J
Jonas Hietala 已提交
594
    /// ```
595
    pub fn eq_vec(&self, v: &[bool]) -> bool {
596
        assert_eq!(self.nbits, v.len());
597 598
        let mut i = 0;
        while i < self.nbits {
599
            if self.get(i) != v[i] { return false; }
600 601 602 603
            i = i + 1;
        }
        true
    }
604

P
P1start 已提交
605
    /// Shortens a `Bitv`, dropping excess elements.
606 607 608 609 610 611
    ///
    /// If `len` is greater than the vector's current length, this has no
    /// effect.
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
612
    /// ```
613
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
614
    ///
615
    /// let mut bv = bitv::from_bytes([0b01001011]);
J
Jonas Hietala 已提交
616 617
    /// bv.truncate(2);
    /// assert!(bv.eq_vec([false, true]));
618
    /// ```
619
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
620 621 622
    pub fn truncate(&mut self, len: uint) {
        if len < self.len() {
            self.nbits = len;
623
            let word_len = (len + u32::BITS - 1) / u32::BITS;
624
            self.storage.truncate(word_len);
625 626
            if len % u32::BITS > 0 {
                let mask = (1 << len % u32::BITS) - 1;
627
                self.storage[word_len - 1] &= mask;
628 629 630 631
            }
        }
    }

P
P1start 已提交
632
    /// Grows the vector to be able to store `size` bits without resizing.
J
Jonas Hietala 已提交
633 634 635 636
    ///
    /// # Example
    ///
    /// ```
637
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
638 639 640 641 642 643
    ///
    /// let mut bv = Bitv::with_capacity(3, false);
    /// bv.reserve(10);
    /// assert_eq!(bv.len(), 3);
    /// assert!(bv.capacity() >= 10);
    /// ```
644 645
    pub fn reserve(&mut self, size: uint) {
        let old_size = self.storage.len();
646
        let new_size = (size + u32::BITS - 1) / u32::BITS;
647 648
        if old_size < new_size {
            self.storage.grow(new_size - old_size, 0);
649 650 651
        }
    }

P
P1start 已提交
652
    /// Returns the capacity in bits for this bit vector. Inserting any
653
    /// element less than this amount will not trigger a resizing.
J
Jonas Hietala 已提交
654 655 656 657
    ///
    /// # Example
    ///
    /// ```
658
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
659 660 661 662 663
    ///
    /// let mut bv = Bitv::new();
    /// bv.reserve(10);
    /// assert!(bv.capacity() >= 10);
    /// ```
664 665
    #[inline]
    pub fn capacity(&self) -> uint {
666
        self.storage.len() * u32::BITS
667 668
    }

P
P1start 已提交
669
    /// Grows the `Bitv` in-place, adding `n` copies of `value` to the `Bitv`.
670 671 672
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
673
    /// ```
674
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
675
    ///
676
    /// let mut bv = bitv::from_bytes([0b01001011]);
J
Jonas Hietala 已提交
677
    /// bv.grow(2, true);
678 679
    /// assert_eq!(bv.len(), 10);
    /// assert_eq!(bv.to_bytes(), vec!(0b01001011, 0b11000000));
680 681 682
    /// ```
    pub fn grow(&mut self, n: uint, value: bool) {
        let new_nbits = self.nbits + n;
683
        let new_nwords = (new_nbits + u32::BITS - 1) / u32::BITS;
684 685
        let full_value = if value { !0 } else { 0 };
        // Correct the old tail word
686 687 688
        let old_last_word = (self.nbits + u32::BITS - 1) / u32::BITS - 1;
        if self.nbits % u32::BITS > 0 {
            let overhang = self.nbits % u32::BITS; // # of already-used bits
689 690
            let mask = !((1 << overhang) - 1);  // e.g. 5 unused bits => 111110....0
            if value {
691
                self.storage[old_last_word] |= mask;
692
            } else {
693
                self.storage[old_last_word] &= !mask;
694 695 696 697 698
            }
        }
        // Fill in words after the old tail word
        let stop_idx = cmp::min(self.storage.len(), new_nwords);
        for idx in range(old_last_word + 1, stop_idx) {
699
            self.storage[idx] = full_value;
700 701 702
        }
        // Allocate new words, if needed
        if new_nwords > self.storage.len() {
703 704 705 706 707 708
            let to_add = new_nwords - self.storage.len();
            self.storage.grow(to_add, full_value);

            // Zero out and unused bits in the new tail word
            if value {
                let tail_word = new_nwords - 1;
709
                let used_bits = new_nbits % u32::BITS;
710
                self.storage[tail_word] &= (1 << used_bits) - 1;
711
            }
712 713 714 715 716
        }
        // Adjust internal bit count
        self.nbits = new_nbits;
    }

P
P1start 已提交
717
    /// Shortens by one element and returns the removed element.
J
Jonas Hietala 已提交
718 719 720 721
    ///
    /// # Failure
    ///
    /// Assert if empty.
722 723 724
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
725
    /// ```
726
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
727
    ///
728 729
    /// let mut bv = bitv::from_bytes([0b01001001]);
    /// assert_eq!(bv.pop(), true);
J
Jonas Hietala 已提交
730
    /// assert_eq!(bv.pop(), false);
731 732
    /// assert_eq!(bv.len(), 6);
    /// assert_eq!(bv.to_bytes(), vec!(0b01001000));
733 734 735 736
    /// ```
    pub fn pop(&mut self) -> bool {
        let ret = self.get(self.nbits - 1);
        // If we are unusing a whole word, make sure it is zeroed out
737
        if self.nbits % u32::BITS == 1 {
738
            self.storage[self.nbits / u32::BITS] = 0;
739 740 741 742 743
        }
        self.nbits -= 1;
        ret
    }

P
P1start 已提交
744
    /// Pushes a `bool` onto the end.
745 746 747
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
748
    /// ```
749
    /// use std::collections::Bitv;
J
Jonas Hietala 已提交
750
    ///
751
    /// let mut bv = Bitv::new();
J
Jonas Hietala 已提交
752 753
    /// bv.push(true);
    /// bv.push(false);
754
    /// assert!(bv.eq_vec([true, false]));
755 756 757 758
    /// ```
    pub fn push(&mut self, elem: bool) {
        let insert_pos = self.nbits;
        self.nbits += 1;
759
        if self.storage.len() * u32::BITS < self.nbits {
760 761 762 763
            self.storage.push(0);
        }
        self.set(insert_pos, elem);
    }
764 765 766

    /// Return the total number of bits in this vector
    #[inline]
767
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
768 769 770 771
    pub fn len(&self) -> uint { self.nbits }

    /// Returns true if there are no bits in this vector
    #[inline]
772
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
773 774 775 776
    pub fn is_empty(&self) -> bool { self.len() == 0 }

    /// Clears all bits in this vector.
    #[inline]
777
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
778 779 780
    pub fn clear(&mut self) {
        for w in self.storage.iter_mut() { *w = 0u32; }
    }
781
}
782

P
P1start 已提交
783
/// Transforms a byte-vector into a `Bitv`. Each byte becomes eight bits,
J
Jonas Hietala 已提交
784 785 786 787 788 789
/// with the most significant bits of each byte coming first. Each
/// bit becomes `true` if equal to 1 or `false` if equal to 0.
///
/// # Example
///
/// ```
J
Jonas Hietala 已提交
790
/// use std::collections::bitv;
J
Jonas Hietala 已提交
791
///
J
Jonas Hietala 已提交
792
/// let bv = bitv::from_bytes([0b10100000, 0b00010010]);
J
Jonas Hietala 已提交
793 794 795 796 797
/// assert!(bv.eq_vec([true, false, true, false,
///                    false, false, false, false,
///                    false, false, false, true,
///                    false, false, true, false]));
/// ```
798
pub fn from_bytes(bytes: &[u8]) -> Bitv {
799
    from_fn(bytes.len() * 8, |i| {
800
        let b = bytes[i / 8] as u32;
801 802 803 804 805
        let offset = i % 8;
        b >> (7 - offset) & 1 == 1
    })
}

P
P1start 已提交
806
/// Creates a `Bitv` of the specified length where the value at each
J
Jonas Hietala 已提交
807 808 809 810 811 812 813 814 815 816
/// index is `f(index)`.
///
/// # Example
///
/// ```
/// use std::collections::bitv::from_fn;
///
/// let bv = from_fn(5, |i| { i % 2 == 0 });
/// assert!(bv.eq_vec([true, false, true, false, true]));
/// ```
817
pub fn from_fn(len: uint, f: |index: uint| -> bool) -> Bitv {
818
    let mut bitv = Bitv::with_capacity(len, false);
D
Daniel Micay 已提交
819
    for i in range(0u, len) {
820 821
        bitv.set(i, f(i));
    }
L
Luqman Aden 已提交
822
    bitv
823 824
}

825 826
impl Default for Bitv {
    #[inline]
827
    fn default() -> Bitv { Bitv::new() }
828 829 830 831
}

impl FromIterator<bool> for Bitv {
    fn from_iter<I:Iterator<bool>>(iterator: I) -> Bitv {
832
        let mut ret = Bitv::new();
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
        ret.extend(iterator);
        ret
    }
}

impl Extendable<bool> for Bitv {
    #[inline]
    fn extend<I: Iterator<bool>>(&mut self, mut iterator: I) {
        let (min, _) = iterator.size_hint();
        let nbits = self.nbits;
        self.reserve(nbits + min);
        for element in iterator {
            self.push(element)
        }
    }
}

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;
859
        self.storage.clone_from(&source.storage);
860 861 862
    }
}

N
nham 已提交
863 864 865 866 867 868 869
impl PartialOrd for Bitv {
    #[inline]
    fn partial_cmp(&self, other: &Bitv) -> Option<Ordering> {
        iter::order::partial_cmp(self.iter(), other.iter())
    }
}

870 871 872 873 874 875 876
impl Ord for Bitv {
    #[inline]
    fn cmp(&self, other: &Bitv) -> Ordering {
        iter::order::cmp(self.iter(), other.iter())
    }
}

S
Steven Fackler 已提交
877 878 879
impl fmt::Show for Bitv {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        for bit in self.iter() {
880
            try!(write!(fmt, "{}", if bit { 1u } else { 0u }));
S
Steven Fackler 已提交
881 882 883 884 885
        }
        Ok(())
    }
}

886 887 888
impl<S: hash::Writer> hash::Hash<S> for Bitv {
    fn hash(&self, state: &mut S) {
        self.nbits.hash(state);
889 890
        for (_, elem) in self.mask_words(0) {
            elem.hash(state);
891 892 893 894
        }
    }
}

895 896 897
impl cmp::PartialEq for Bitv {
    #[inline]
    fn eq(&self, other: &Bitv) -> bool {
898 899 900
        if self.nbits != other.nbits {
            return false;
        }
901
        self.mask_words(0).zip(other.mask_words(0)).all(|((_, w1), (_, w2))| w1 == w2)
902 903 904 905 906
    }
}

impl cmp::Eq for Bitv {}

907
/// An iterator for `Bitv`.
P
Palmer Cox 已提交
908
pub struct Bits<'a> {
909 910 911
    bitv: &'a Bitv,
    next_idx: uint,
    end_idx: uint,
912 913
}

P
Palmer Cox 已提交
914
impl<'a> Iterator<bool> for Bits<'a> {
S
Steven Fackler 已提交
915
    #[inline]
916
    fn next(&mut self) -> Option<bool> {
917
        if self.next_idx != self.end_idx {
918 919 920 921 922 923 924 925 926
            let idx = self.next_idx;
            self.next_idx += 1;
            Some(self.bitv.get(idx))
        } else {
            None
        }
    }

    fn size_hint(&self) -> (uint, Option<uint>) {
927
        let rem = self.end_idx - self.next_idx;
928 929 930 931
        (rem, Some(rem))
    }
}

P
Palmer Cox 已提交
932
impl<'a> DoubleEndedIterator<bool> for Bits<'a> {
933 934 935 936 937 938 939 940 941 942 943
    #[inline]
    fn next_back(&mut self) -> Option<bool> {
        if self.next_idx != self.end_idx {
            self.end_idx -= 1;
            Some(self.bitv.get(self.end_idx))
        } else {
            None
        }
    }
}

P
Palmer Cox 已提交
944
impl<'a> ExactSize<bool> for Bits<'a> {}
945

P
Palmer Cox 已提交
946
impl<'a> RandomAccessIterator<bool> for Bits<'a> {
947 948 949 950 951 952
    #[inline]
    fn indexable(&self) -> uint {
        self.end_idx - self.next_idx
    }

    #[inline]
953
    fn idx(&mut self, index: uint) -> Option<bool> {
954 955 956 957 958 959 960 961
        if index >= self.indexable() {
            None
        } else {
            Some(self.bitv.get(index))
        }
    }
}

962
/// An implementation of a set using a bit vector as an underlying
J
Jonas Hietala 已提交
963
/// representation for holding unsigned numerical elements.
964 965 966
///
/// 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
967
/// as a `uint`.
J
Jonas Hietala 已提交
968 969 970 971 972
///
/// # Example
///
/// ```
/// use std::collections::{BitvSet, Bitv};
J
Jonas Hietala 已提交
973
/// use std::collections::bitv;
J
Jonas Hietala 已提交
974 975 976 977 978 979 980 981 982 983 984 985 986 987
///
/// // 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`
J
Jonas Hietala 已提交
988
/// let other = BitvSet::from_bitv(bitv::from_bytes([0b11010000]));
J
Jonas Hietala 已提交
989 990 991 992 993 994 995 996 997
///
/// s.union_with(&other);
///
/// // Print 0, 1, 3 in some order
/// for x in s.iter() {
///     println!("{}", x);
/// }
///
/// // Can convert back to a `Bitv`
998 999
/// let bv: Bitv = s.into_bitv();
/// assert!(bv.get(3));
J
Jonas Hietala 已提交
1000
/// ```
1001
#[deriving(Clone)]
1002
pub struct BitvSet(Bitv);
1003

1004 1005 1006 1007 1008
impl Default for BitvSet {
    #[inline]
    fn default() -> BitvSet { BitvSet::new() }
}

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
impl FromIterator<bool> for BitvSet {
    fn from_iter<I:Iterator<bool>>(iterator: I) -> BitvSet {
        let mut ret = BitvSet::new();
        ret.extend(iterator);
        ret
    }
}

impl Extendable<bool> for BitvSet {
    #[inline]
    fn extend<I: Iterator<bool>>(&mut self, iterator: I) {
1020 1021
        let &BitvSet(ref mut self_bitv) = self;
        self_bitv.extend(iterator);
1022 1023 1024
    }
}

1025 1026 1027
impl PartialOrd for BitvSet {
    #[inline]
    fn partial_cmp(&self, other: &BitvSet) -> Option<Ordering> {
1028
        let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1029 1030 1031 1032 1033 1034 1035
        iter::order::partial_cmp(a_iter, b_iter)
    }
}

impl Ord for BitvSet {
    #[inline]
    fn cmp(&self, other: &BitvSet) -> Ordering {
1036
        let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1037 1038 1039 1040 1041 1042 1043
        iter::order::cmp(a_iter, b_iter)
    }
}

impl cmp::PartialEq for BitvSet {
    #[inline]
    fn eq(&self, other: &BitvSet) -> bool {
1044
        let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1045 1046 1047 1048 1049 1050
        iter::order::eq(a_iter, b_iter)
    }
}

impl cmp::Eq for BitvSet {}

1051
impl BitvSet {
P
P1start 已提交
1052
    /// Creates a new bit vector set with initially no contents.
J
Jonas Hietala 已提交
1053 1054 1055 1056 1057 1058 1059
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
    /// let mut s = BitvSet::new();
    /// ```
1060
    #[inline]
1061
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1062
    pub fn new() -> BitvSet {
1063 1064 1065
        BitvSet(Bitv::new())
    }

P
P1start 已提交
1066
    /// Creates a new bit vector set with initially no contents, able to
J
Jonas Hietala 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075
    /// hold `nbits` elements without resizing.
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
    /// let mut s = BitvSet::with_capacity(100);
    /// assert!(s.capacity() >= 100);
    /// ```
1076
    #[inline]
1077
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1078
    pub fn with_capacity(nbits: uint) -> BitvSet {
1079 1080
        let bitv = Bitv::with_capacity(nbits, false);
        BitvSet::from_bitv(bitv)
1081
    }
E
Eric Holk 已提交
1082

P
P1start 已提交
1083
    /// Creates a new bit vector set from the given bit vector.
J
Jonas Hietala 已提交
1084 1085 1086 1087
    ///
    /// # Example
    ///
    /// ```
1088
    /// use std::collections::{bitv, BitvSet};
J
Jonas Hietala 已提交
1089
    ///
1090
    /// let bv = bitv::from_bytes([0b01100000]);
J
Jonas Hietala 已提交
1091 1092 1093 1094 1095 1096 1097
    /// let s = BitvSet::from_bitv(bv);
    ///
    /// // Print 1, 2 in arbitrary order
    /// for x in s.iter() {
    ///     println!("{}", x);
    /// }
    /// ```
1098
    #[inline]
1099 1100 1101
    pub fn from_bitv(mut bitv: Bitv) -> BitvSet {
        // Mark every bit as valid
        bitv.nbits = bitv.capacity();
1102
        BitvSet(bitv)
1103 1104 1105 1106
    }

    /// Returns the capacity in bits for this bit vector. Inserting any
    /// element less than this amount will not trigger a resizing.
J
Jonas Hietala 已提交
1107 1108 1109 1110 1111 1112 1113 1114 1115
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::with_capacity(100);
    /// assert!(s.capacity() >= 100);
    /// ```
1116
    #[inline]
1117
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1118 1119
    pub fn capacity(&self) -> uint {
        let &BitvSet(ref bitv) = self;
1120 1121 1122
        bitv.capacity()
    }

J
Jonas Hietala 已提交
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
    /// Grows the underlying vector to be able to store `size` bits.
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::new();
    /// s.reserve(10);
    /// assert!(s.capacity() >= 10);
    /// ```
1134 1135
    pub fn reserve(&mut self, size: uint) {
        let &BitvSet(ref mut bitv) = self;
1136 1137 1138 1139
        bitv.reserve(size);
        if bitv.nbits < size {
            bitv.nbits = bitv.capacity();
        }
1140
    }
1141

P
P1start 已提交
1142
    /// Consumes this set to return the underlying bit vector.
J
Jonas Hietala 已提交
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::new();
    /// s.insert(0);
    /// s.insert(3);
    ///
1153 1154 1155
    /// let bv = s.into_bitv();
    /// assert!(bv.get(0));
    /// assert!(bv.get(3));
J
Jonas Hietala 已提交
1156
    /// ```
1157
    #[inline]
1158
    pub fn into_bitv(self) -> Bitv {
1159 1160 1161 1162
        let BitvSet(bitv) = self;
        bitv
    }

P
P1start 已提交
1163
    /// Returns a reference to the underlying bit vector.
J
Jonas Hietala 已提交
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
    ///
    /// let mut s = BitvSet::new();
    /// s.insert(0);
    ///
    /// let bv = s.get_ref();
J
Jonas Hietala 已提交
1174
    /// assert_eq!(bv[0], true);
J
Jonas Hietala 已提交
1175
    /// ```
1176 1177 1178 1179 1180 1181
    #[inline]
    pub fn get_ref<'a>(&'a self) -> &'a Bitv {
        let &BitvSet(ref bitv) = self;
        bitv
    }

1182
    #[inline]
1183
    fn other_op(&mut self, other: &BitvSet, f: |u32, u32| -> u32) {
1184 1185 1186
        // Expand the vector if necessary
        self.reserve(other.capacity());

1187 1188 1189
        // Unwrap Bitvs
        let &BitvSet(ref mut self_bitv) = self;
        let &BitvSet(ref other_bitv) = other;
1190 1191

        // virtually pad other with 0's for equal lengths
1192 1193 1194 1195
        let mut other_words = {
            let (_, result) = match_words(self_bitv, other_bitv);
            result
        };
1196 1197 1198

        // Apply values found in other
        for (i, w) in other_words {
1199
            let old = self_bitv.storage[i];
1200
            let new = f(old, w);
1201
            self_bitv.storage[i] = new;
1202
        }
1203 1204
    }

P
P1start 已提交
1205
    /// Truncates the underlying vector to the least length required.
J
Jonas Hietala 已提交
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
    ///
    /// # Example
    ///
    /// ```
    /// 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());
    /// ```
1223
    #[inline]
1224
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1225 1226
    pub fn shrink_to_fit(&mut self) {
        let &BitvSet(ref mut bitv) = self;
1227 1228 1229 1230 1231 1232
        // 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);
1233
        bitv.storage.truncate(trunc_len);
1234
        bitv.nbits = trunc_len * u32::BITS;
1235 1236
    }

1237
    /// Iterator over each u32 stored in the `BitvSet`.
J
Jonas Hietala 已提交
1238 1239 1240 1241 1242
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
J
Jonas Hietala 已提交
1243
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
1244
    ///
J
Jonas Hietala 已提交
1245
    /// let s = BitvSet::from_bitv(bitv::from_bytes([0b01001010]));
J
Jonas Hietala 已提交
1246 1247 1248 1249 1250 1251
    ///
    /// // Print 1, 4, 6 in arbitrary order
    /// for x in s.iter() {
    ///     println!("{}", x);
    /// }
    /// ```
1252
    #[inline]
1253
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
P
Palmer Cox 已提交
1254
    pub fn iter<'a>(&'a self) -> BitPositions<'a> {
1255
        BitPositions {set: self, next_idx: 0u}
1256
    }
1257

1258
    /// Iterator over each u32 stored in `self` union `other`.
J
Jonas Hietala 已提交
1259 1260 1261 1262 1263 1264
    /// See [union_with](#method.union_with) for an efficient in-place version.
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
J
Jonas Hietala 已提交
1265
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
1266
    ///
J
Jonas Hietala 已提交
1267 1268
    /// let a = BitvSet::from_bitv(bitv::from_bytes([0b01101000]));
    /// let b = BitvSet::from_bitv(bitv::from_bytes([0b10100000]));
J
Jonas Hietala 已提交
1269 1270 1271 1272 1273 1274
    ///
    /// // Print 0, 1, 2, 4 in arbitrary order
    /// for x in a.union(&b) {
    ///     println!("{}", x);
    /// }
    /// ```
1275
    #[inline]
1276
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1277 1278 1279 1280 1281
    pub fn union<'a>(&'a self, other: &'a BitvSet) -> TwoBitPositions<'a> {
        TwoBitPositions {
            set: self,
            other: other,
            merge: |w1, w2| w1 | w2,
1282 1283
            current_word: 0u32,
            next_idx: 0u
1284 1285 1286
        }
    }

1287 1288
    /// Iterator over each uint stored in `self` intersect `other`.
    /// See [intersect_with](#method.intersect_with) for an efficient in-place version.
J
Jonas Hietala 已提交
1289 1290 1291 1292 1293
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
J
Jonas Hietala 已提交
1294
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
1295
    ///
J
Jonas Hietala 已提交
1296 1297
    /// let a = BitvSet::from_bitv(bitv::from_bytes([0b01101000]));
    /// let b = BitvSet::from_bitv(bitv::from_bytes([0b10100000]));
J
Jonas Hietala 已提交
1298
    ///
1299 1300
    /// // Print 2
    /// for x in a.intersection(&b) {
J
Jonas Hietala 已提交
1301 1302 1303
    ///     println!("{}", x);
    /// }
    /// ```
1304
    #[inline]
1305
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1306 1307
    pub fn intersection<'a>(&'a self, other: &'a BitvSet) -> Take<TwoBitPositions<'a>> {
        let min = cmp::min(self.capacity(), other.capacity());
1308 1309 1310
        TwoBitPositions {
            set: self,
            other: other,
1311
            merge: |w1, w2| w1 & w2,
1312
            current_word: 0u32,
1313
            next_idx: 0
1314
        }.take(min)
1315 1316
    }

1317 1318
    /// 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 已提交
1319 1320 1321 1322 1323
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
J
Jonas Hietala 已提交
1324
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
1325
    ///
J
Jonas Hietala 已提交
1326 1327
    /// let a = BitvSet::from_bitv(bitv::from_bytes([0b01101000]));
    /// let b = BitvSet::from_bitv(bitv::from_bytes([0b10100000]));
J
Jonas Hietala 已提交
1328
    ///
1329
    /// // Print 1, 4 in arbitrary order
1330 1331 1332 1333 1334 1335 1336 1337
    /// 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 已提交
1338 1339 1340
    ///     println!("{}", x);
    /// }
    /// ```
1341
    #[inline]
1342
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1343
    pub fn difference<'a>(&'a self, other: &'a BitvSet) -> TwoBitPositions<'a> {
1344 1345 1346
        TwoBitPositions {
            set: self,
            other: other,
1347
            merge: |w1, w2| w1 & !w2,
1348
            current_word: 0u32,
1349 1350
            next_idx: 0
        }
1351 1352
    }

1353
    /// Iterator over each u32 stored in the symmetric difference of `self` and `other`.
1354 1355
    /// See [symmetric_difference_with](#method.symmetric_difference_with) for
    /// an efficient in-place version.
J
Jonas Hietala 已提交
1356 1357 1358 1359 1360
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
J
Jonas Hietala 已提交
1361
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
1362
    ///
J
Jonas Hietala 已提交
1363 1364
    /// let a = BitvSet::from_bitv(bitv::from_bytes([0b01101000]));
    /// let b = BitvSet::from_bitv(bitv::from_bytes([0b10100000]));
J
Jonas Hietala 已提交
1365
    ///
1366 1367
    /// // Print 0, 1, 4 in arbitrary order
    /// for x in a.symmetric_difference(&b) {
J
Jonas Hietala 已提交
1368 1369 1370
    ///     println!("{}", x);
    /// }
    /// ```
1371
    #[inline]
1372
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1373
    pub fn symmetric_difference<'a>(&'a self, other: &'a BitvSet) -> TwoBitPositions<'a> {
1374 1375 1376
        TwoBitPositions {
            set: self,
            other: other,
1377
            merge: |w1, w2| w1 ^ w2,
1378
            current_word: 0u32,
1379
            next_idx: 0
1380
        }
1381 1382
    }

P
P1start 已提交
1383
    /// Unions in-place with the specified other bit vector.
J
Jonas Hietala 已提交
1384 1385 1386 1387 1388
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
J
Jonas Hietala 已提交
1389
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
1390
    ///
1391 1392 1393 1394 1395 1396
    /// let a   = 0b01101000;
    /// let b   = 0b10100000;
    /// let res = 0b11101000;
    ///
    /// let mut a = BitvSet::from_bitv(bitv::from_bytes([a]));
    /// let b = BitvSet::from_bitv(bitv::from_bytes([b]));
1397
    /// let res = BitvSet::from_bitv(bitv::from_bytes([res]));
J
Jonas Hietala 已提交
1398 1399
    ///
    /// a.union_with(&b);
1400
    /// assert_eq!(a, res);
J
Jonas Hietala 已提交
1401
    /// ```
1402 1403 1404 1405 1406
    #[inline]
    pub fn union_with(&mut self, other: &BitvSet) {
        self.other_op(other, |w1, w2| w1 | w2);
    }

P
P1start 已提交
1407
    /// Intersects in-place with the specified other bit vector.
J
Jonas Hietala 已提交
1408 1409 1410 1411 1412
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
J
Jonas Hietala 已提交
1413
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
1414
    ///
1415 1416 1417 1418 1419 1420
    /// let a   = 0b01101000;
    /// let b   = 0b10100000;
    /// let res = 0b00100000;
    ///
    /// let mut a = BitvSet::from_bitv(bitv::from_bytes([a]));
    /// let b = BitvSet::from_bitv(bitv::from_bytes([b]));
1421
    /// let res = BitvSet::from_bitv(bitv::from_bytes([res]));
J
Jonas Hietala 已提交
1422 1423
    ///
    /// a.intersect_with(&b);
1424
    /// assert_eq!(a, res);
J
Jonas Hietala 已提交
1425
    /// ```
1426 1427 1428 1429 1430
    #[inline]
    pub fn intersect_with(&mut self, other: &BitvSet) {
        self.other_op(other, |w1, w2| w1 & w2);
    }

P
P1start 已提交
1431 1432
    /// Makes this bit vector the difference with the specified other bit vector
    /// in-place.
J
Jonas Hietala 已提交
1433 1434 1435 1436 1437
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
J
Jonas Hietala 已提交
1438
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
1439
    ///
1440 1441 1442 1443 1444 1445 1446
    /// let a   = 0b01101000;
    /// let b   = 0b10100000;
    /// let a_b = 0b01001000; // a - b
    /// let b_a = 0b10000000; // b - a
    ///
    /// let mut bva = BitvSet::from_bitv(bitv::from_bytes([a]));
    /// let bvb = BitvSet::from_bitv(bitv::from_bytes([b]));
1447 1448
    /// let bva_b = BitvSet::from_bitv(bitv::from_bytes([a_b]));
    /// let bvb_a = BitvSet::from_bitv(bitv::from_bytes([b_a]));
1449 1450
    ///
    /// bva.difference_with(&bvb);
1451
    /// assert_eq!(bva, bva_b);
J
Jonas Hietala 已提交
1452
    ///
1453 1454 1455 1456
    /// let bva = BitvSet::from_bitv(bitv::from_bytes([a]));
    /// let mut bvb = BitvSet::from_bitv(bitv::from_bytes([b]));
    ///
    /// bvb.difference_with(&bva);
1457
    /// assert_eq!(bvb, bvb_a);
J
Jonas Hietala 已提交
1458
    /// ```
1459 1460 1461 1462 1463
    #[inline]
    pub fn difference_with(&mut self, other: &BitvSet) {
        self.other_op(other, |w1, w2| w1 & !w2);
    }

P
P1start 已提交
1464 1465
    /// Makes this bit vector the symmetric difference with the specified other
    /// bit vector in-place.
J
Jonas Hietala 已提交
1466 1467 1468 1469 1470
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::BitvSet;
J
Jonas Hietala 已提交
1471
    /// use std::collections::bitv;
J
Jonas Hietala 已提交
1472
    ///
1473 1474 1475 1476 1477 1478
    /// let a   = 0b01101000;
    /// let b   = 0b10100000;
    /// let res = 0b11001000;
    ///
    /// let mut a = BitvSet::from_bitv(bitv::from_bytes([a]));
    /// let b = BitvSet::from_bitv(bitv::from_bytes([b]));
1479
    /// let res = BitvSet::from_bitv(bitv::from_bytes([res]));
J
Jonas Hietala 已提交
1480 1481
    ///
    /// a.symmetric_difference_with(&b);
1482
    /// assert_eq!(a, res);
J
Jonas Hietala 已提交
1483
    /// ```
1484 1485 1486 1487
    #[inline]
    pub fn symmetric_difference_with(&mut self, other: &BitvSet) {
        self.other_op(other, |w1, w2| w1 ^ w2);
    }
S
Steven Fackler 已提交
1488

1489 1490
    /// Return the number of set bits in this set.
    #[inline]
1491
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1492 1493 1494
    pub fn len(&self) -> uint  {
        let &BitvSet(ref bitv) = self;
        bitv.storage.iter().fold(0, |acc, &n| acc + n.count_ones())
1495 1496
    }

1497
    /// Returns whether there are no bits set in this set
1498
    #[inline]
1499
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1500
    pub fn is_empty(&self) -> bool {
1501
        let &BitvSet(ref bitv) = self;
1502
        bitv.storage.iter().all(|&n| n == 0)
1503
    }
1504

1505
    /// Clears all bits in this set
1506
    #[inline]
1507
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1508
    pub fn clear(&mut self) {
1509 1510
        let &BitvSet(ref mut bitv) = self;
        bitv.clear();
1511 1512
    }

1513
    /// Returns `true` if this set contains the specified integer.
1514
    #[inline]
1515
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1516
    pub fn contains(&self, value: &uint) -> bool {
1517 1518
        let &BitvSet(ref bitv) = self;
        *value < bitv.nbits && bitv.get(*value)
1519 1520
    }

1521 1522
    /// Returns `true` if the set has no elements in common with `other`.
    /// This is equivalent to checking for an empty intersection.
1523
    #[inline]
1524
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1525
    pub fn is_disjoint(&self, other: &BitvSet) -> bool {
1526
        self.intersection(other).next().is_none()
1527 1528
    }

1529
    /// Returns `true` if the set is a subset of another.
1530
    #[inline]
1531
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1532
    pub fn is_subset(&self, other: &BitvSet) -> bool {
1533 1534 1535 1536 1537 1538 1539 1540
        let &BitvSet(ref self_bitv) = self;
        let &BitvSet(ref other_bitv) = other;

        // Check that `self` intersect `other` is self
        self_bitv.mask_words(0).zip(other_bitv.mask_words(0))
                               .all(|((_, w1), (_, w2))| w1 & w2 == w1) &&
        // Check that `self` setminus `other` is empty
        self_bitv.mask_words(other_bitv.storage.len()).all(|(_, w)| w == 0)
1541 1542
    }

1543
    /// Returns `true` if the set is a superset of another.
1544
    #[inline]
1545
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1546
    pub fn is_superset(&self, other: &BitvSet) -> bool {
1547 1548 1549
        other.is_subset(self)
    }

1550 1551
    /// Adds a value to the set. Returns `true` if the value was not already
    /// present in the set.
1552
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1553
    pub fn insert(&mut self, value: uint) -> bool {
1554 1555 1556
        if self.contains(&value) {
            return false;
        }
1557 1558

        // Ensure we have enough space to hold the new element
1559 1560
        if value >= self.capacity() {
            let new_cap = cmp::max(value + 1, self.capacity() * 2);
1561
            self.reserve(new_cap);
1562
        }
1563

1564 1565
        let &BitvSet(ref mut bitv) = self;
        bitv.set(value, true);
1566 1567 1568
        return true;
    }

1569 1570
    /// Removes a value from the set. Returns `true` if the value was
    /// present in the set.
1571
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1572
    pub fn remove(&mut self, value: &uint) -> bool {
1573 1574 1575
        if !self.contains(value) {
            return false;
        }
1576 1577
        let &BitvSet(ref mut bitv) = self;
        bitv.set(*value, false);
1578 1579 1580 1581
        return true;
    }
}

1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
impl fmt::Show for BitvSet {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(fmt, "{{"));
        let mut first = true;
        for n in self.iter() {
            if !first {
                try!(write!(fmt, ", "));
            }
            try!(write!(fmt, "{}", n));
            first = false;
        }
        write!(fmt, "}}")
    }
}

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

1605
/// An iterator for `BitvSet`.
P
Palmer Cox 已提交
1606
pub struct BitPositions<'a> {
1607 1608
    set: &'a BitvSet,
    next_idx: uint
1609 1610
}

J
Joseph Crail 已提交
1611
/// An iterator combining two `BitvSet` iterators.
1612 1613 1614
pub struct TwoBitPositions<'a> {
    set: &'a BitvSet,
    other: &'a BitvSet,
1615 1616
    merge: |u32, u32|: 'a -> u32,
    current_word: u32,
1617 1618 1619
    next_idx: uint
}

P
Palmer Cox 已提交
1620
impl<'a> Iterator<uint> for BitPositions<'a> {
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
    fn next(&mut self) -> Option<uint> {
        while self.next_idx < self.set.capacity() {
            let idx = self.next_idx;
            self.next_idx += 1;

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

        return None;
    }

1634
    #[inline]
1635 1636 1637 1638 1639
    fn size_hint(&self) -> (uint, Option<uint>) {
        (0, Some(self.set.capacity() - self.next_idx))
    }
}

1640 1641 1642 1643
impl<'a> Iterator<uint> for TwoBitPositions<'a> {
    fn next(&mut self) -> Option<uint> {
        while self.next_idx < self.set.capacity() ||
              self.next_idx < self.other.capacity() {
1644
            let bit_idx = self.next_idx % u32::BITS;
1645 1646 1647 1648 1649
            if bit_idx == 0 {
                let &BitvSet(ref s_bitv) = self.set;
                let &BitvSet(ref o_bitv) = self.other;
                // Merging the two words is a bit of an awkward dance since
                // one Bitv might be longer than the other
1650
                let word_idx = self.next_idx / u32::BITS;
1651
                let w1 = if word_idx < s_bitv.storage.len() {
1652
                             s_bitv.storage[word_idx]
1653 1654
                         } else { 0 };
                let w2 = if word_idx < o_bitv.storage.len() {
1655
                             o_bitv.storage[word_idx]
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
                         } 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;
    }

1668
    #[inline]
1669 1670 1671 1672 1673 1674
    fn size_hint(&self) -> (uint, Option<uint>) {
        let cap = cmp::max(self.set.capacity(), self.other.capacity());
        (0, Some(cap - self.next_idx))
    }
}

1675 1676
#[cfg(test)]
mod tests {
1677
    use std::prelude::*;
1678
    use std::iter::range_step;
1679
    use std::u32;
1680 1681 1682
    use std::rand;
    use std::rand::Rng;
    use test::Bencher;
1683

1684
    use super::{Bitv, BitvSet, from_fn, from_bytes};
1685
    use bitv;
1686
    use vec::Vec;
1687

1688
    static BENCH_BITS : uint = 1 << 14;
1689

1690
    #[test]
1691
    fn test_to_str() {
1692
        let zerolen = Bitv::new();
1693
        assert_eq!(zerolen.to_string().as_slice(), "");
1694

1695
        let eightbits = Bitv::with_capacity(8u, false);
1696
        assert_eq!(eightbits.to_string().as_slice(), "00000000")
1697 1698
    }

1699
    #[test]
1700
    fn test_0_elements() {
1701
        let act = Bitv::new();
1702 1703
        let exp = Vec::from_elem(0u, false);
        assert!(act.eq_vec(exp.as_slice()));
1704 1705 1706
    }

    #[test]
1707
    fn test_1_element() {
1708
        let mut act = Bitv::with_capacity(1u, false);
B
blake2-ppc 已提交
1709
        assert!(act.eq_vec([false]));
1710
        act = Bitv::with_capacity(1u, true);
B
blake2-ppc 已提交
1711
        assert!(act.eq_vec([true]));
1712 1713
    }

1714
    #[test]
1715
    fn test_2_elements() {
1716
        let mut b = bitv::Bitv::with_capacity(2, false);
1717 1718
        b.set(0, true);
        b.set(1, false);
1719
        assert_eq!(b.to_string().as_slice(), "10");
1720 1721
    }

1722
    #[test]
1723
    fn test_10_elements() {
1724
        let mut act;
1725 1726
        // all 0

1727
        act = Bitv::with_capacity(10u, false);
1728
        assert!((act.eq_vec(
B
blake2-ppc 已提交
1729
                    [false, false, false, false, false, false, false, false, false, false])));
1730 1731
        // all 1

1732
        act = Bitv::with_capacity(10u, true);
B
blake2-ppc 已提交
1733
        assert!((act.eq_vec([true, true, true, true, true, true, true, true, true, true])));
1734 1735
        // mixed

1736
        act = Bitv::with_capacity(10u, false);
1737 1738 1739 1740 1741
        act.set(0u, true);
        act.set(1u, true);
        act.set(2u, true);
        act.set(3u, true);
        act.set(4u, true);
B
blake2-ppc 已提交
1742
        assert!((act.eq_vec([true, true, true, true, true, false, false, false, false, false])));
1743 1744
        // mixed

1745
        act = Bitv::with_capacity(10u, false);
1746 1747 1748 1749 1750
        act.set(5u, true);
        act.set(6u, true);
        act.set(7u, true);
        act.set(8u, true);
        act.set(9u, true);
B
blake2-ppc 已提交
1751
        assert!((act.eq_vec([false, false, false, false, false, true, true, true, true, true])));
1752 1753
        // mixed

1754
        act = Bitv::with_capacity(10u, false);
1755 1756 1757 1758
        act.set(0u, true);
        act.set(3u, true);
        act.set(6u, true);
        act.set(9u, true);
B
blake2-ppc 已提交
1759
        assert!((act.eq_vec([true, false, false, true, false, false, true, false, false, true])));
1760 1761 1762
    }

    #[test]
1763
    fn test_31_elements() {
1764
        let mut act;
1765 1766
        // all 0

1767
        act = Bitv::with_capacity(31u, false);
P
Patrick Walton 已提交
1768
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1769
                [false, false, false, false, false, false, false, false, false, false, false,
1770 1771
                false, false, false, false, false, false, false, false, false, false, false, false,
                false, false, false, false, false, false, false, false]));
1772 1773
        // all 1

1774
        act = Bitv::with_capacity(31u, true);
P
Patrick Walton 已提交
1775
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1776
                [true, true, true, true, true, true, true, true, true, true, true, true, true,
1777 1778
                true, true, true, true, true, true, true, true, true, true, true, true, true, true,
                true, true, true, true]));
1779 1780
        // mixed

1781
        act = Bitv::with_capacity(31u, false);
1782 1783 1784 1785 1786 1787 1788 1789
        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 已提交
1790
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1791
                [true, true, true, true, true, true, true, true, false, false, false, false, false,
1792 1793
                false, false, false, false, false, false, false, false, false, false, false, false,
                false, false, false, false, false, false]));
1794 1795
        // mixed

1796
        act = Bitv::with_capacity(31u, false);
1797 1798 1799 1800 1801 1802 1803 1804
        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 已提交
1805
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1806
                [false, false, false, false, false, false, false, false, false, false, false,
1807 1808
                false, false, false, false, false, true, true, true, true, true, true, true, true,
                false, false, false, false, false, false, false]));
1809 1810
        // mixed

1811
        act = Bitv::with_capacity(31u, false);
1812 1813 1814 1815 1816 1817 1818
        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 已提交
1819
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1820
                [false, false, false, false, false, false, false, false, false, false, false,
1821 1822
                false, false, false, false, false, false, false, false, false, false, false, false,
                false, true, true, true, true, true, true, true]));
1823 1824
        // mixed

1825
        act = Bitv::with_capacity(31u, false);
1826 1827 1828
        act.set(3u, true);
        act.set(17u, true);
        act.set(30u, true);
P
Patrick Walton 已提交
1829
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1830
                [false, false, false, true, false, false, false, false, false, false, false, false,
1831 1832
                false, false, false, false, false, true, false, false, false, false, false, false,
                false, false, false, false, false, false, true]));
1833 1834 1835
    }

    #[test]
1836
    fn test_32_elements() {
1837
        let mut act;
1838 1839
        // all 0

1840
        act = Bitv::with_capacity(32u, false);
P
Patrick Walton 已提交
1841
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1842
                [false, false, false, false, false, false, false, false, false, false, false,
1843 1844
                false, false, false, false, false, false, false, false, false, false, false, false,
                false, false, false, false, false, false, false, false, false]));
1845 1846
        // all 1

1847
        act = Bitv::with_capacity(32u, true);
P
Patrick Walton 已提交
1848
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1849
                [true, true, true, true, true, true, true, true, true, true, true, true, true,
1850 1851
                true, true, true, true, true, true, true, true, true, true, true, true, true, true,
                true, true, true, true, true]));
1852 1853
        // mixed

1854
        act = Bitv::with_capacity(32u, false);
1855 1856 1857 1858 1859 1860 1861 1862
        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 已提交
1863
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1864
                [true, true, true, true, true, true, true, true, false, false, false, false, false,
1865 1866
                false, false, false, false, false, false, false, false, false, false, false, false,
                false, false, false, false, false, false, false]));
1867 1868
        // mixed

1869
        act = Bitv::with_capacity(32u, false);
1870 1871 1872 1873 1874 1875 1876 1877
        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 已提交
1878
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1879
                [false, false, false, false, false, false, false, false, false, false, false,
1880 1881
                false, false, false, false, false, true, true, true, true, true, true, true, true,
                false, false, false, false, false, false, false, false]));
1882 1883
        // mixed

1884
        act = Bitv::with_capacity(32u, false);
1885 1886 1887 1888 1889 1890 1891 1892
        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 已提交
1893
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1894
                [false, false, false, false, false, false, false, false, false, false, false,
1895 1896
                false, false, false, false, false, false, false, false, false, false, false, false,
                false, true, true, true, true, true, true, true, true]));
1897 1898
        // mixed

1899
        act = Bitv::with_capacity(32u, false);
1900 1901 1902 1903
        act.set(3u, true);
        act.set(17u, true);
        act.set(30u, true);
        act.set(31u, true);
P
Patrick Walton 已提交
1904
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1905
                [false, false, false, true, false, false, false, false, false, false, false, false,
1906 1907
                false, false, false, false, false, true, false, false, false, false, false, false,
                false, false, false, false, false, false, true, true]));
1908 1909 1910
    }

    #[test]
1911
    fn test_33_elements() {
1912
        let mut act;
1913 1914
        // all 0

1915
        act = Bitv::with_capacity(33u, false);
P
Patrick Walton 已提交
1916
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1917
                [false, false, false, false, false, false, false, false, false, false, false,
1918 1919
                false, false, false, false, false, false, false, false, false, false, false, false,
                false, false, false, false, false, false, false, false, false, false]));
1920 1921
        // all 1

1922
        act = Bitv::with_capacity(33u, true);
P
Patrick Walton 已提交
1923
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1924
                [true, true, true, true, true, true, true, true, true, true, true, true, true,
1925 1926
                true, true, true, true, true, true, true, true, true, true, true, true, true, true,
                true, true, true, true, true, true]));
1927 1928
        // mixed

1929
        act = Bitv::with_capacity(33u, false);
1930 1931 1932 1933 1934 1935 1936 1937
        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 已提交
1938
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1939
                [true, true, true, true, true, true, true, true, false, false, false, false, false,
1940 1941
                false, false, false, false, false, false, false, false, false, false, false, false,
                false, false, false, false, false, false, false, false]));
1942 1943
        // mixed

1944
        act = Bitv::with_capacity(33u, false);
1945 1946 1947 1948 1949 1950 1951 1952
        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 已提交
1953
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1954
                [false, false, false, false, false, false, false, false, false, false, false,
1955 1956
                false, false, false, false, false, true, true, true, true, true, true, true, true,
                false, false, false, false, false, false, false, false, false]));
1957 1958
        // mixed

1959
        act = Bitv::with_capacity(33u, false);
1960 1961 1962 1963 1964 1965 1966 1967
        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 已提交
1968
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1969
                [false, false, false, false, false, false, false, false, false, false, false,
1970 1971
                false, false, false, false, false, false, false, false, false, false, false, false,
                false, true, true, true, true, true, true, true, true, false]));
1972 1973
        // mixed

1974
        act = Bitv::with_capacity(33u, false);
1975 1976 1977 1978 1979
        act.set(3u, true);
        act.set(17u, true);
        act.set(30u, true);
        act.set(31u, true);
        act.set(32u, true);
P
Patrick Walton 已提交
1980
        assert!(act.eq_vec(
B
blake2-ppc 已提交
1981
                [false, false, false, true, false, false, false, false, false, false, false, false,
1982 1983
                false, false, false, false, false, true, false, false, false, false, false, false,
                false, false, false, false, false, false, true, true, true]));
1984 1985
    }

G
Graydon Hoare 已提交
1986
    #[test]
1987
    fn test_equal_differing_sizes() {
1988 1989
        let v0 = Bitv::with_capacity(10u, false);
        let v1 = Bitv::with_capacity(11u, false);
1990
        assert!(v0 != v1);
G
Graydon Hoare 已提交
1991 1992 1993
    }

    #[test]
1994
    fn test_equal_greatly_differing_sizes() {
1995 1996
        let v0 = Bitv::with_capacity(10u, false);
        let v1 = Bitv::with_capacity(110u, false);
1997
        assert!(v0 != v1);
G
Graydon Hoare 已提交
1998
    }
1999 2000

    #[test]
2001
    fn test_equal_sneaky_small() {
2002
        let mut a = bitv::Bitv::with_capacity(1, false);
2003 2004
        a.set(0, true);

2005
        let mut b = bitv::Bitv::with_capacity(1, true);
2006 2007
        b.set(0, true);

2008
        assert_eq!(a, b);
2009 2010 2011
    }

    #[test]
2012
    fn test_equal_sneaky_big() {
2013
        let mut a = bitv::Bitv::with_capacity(100, false);
D
Daniel Micay 已提交
2014
        for i in range(0u, 100) {
2015 2016 2017
            a.set(i, true);
        }

2018
        let mut b = bitv::Bitv::with_capacity(100, true);
D
Daniel Micay 已提交
2019
        for i in range(0u, 100) {
2020 2021 2022
            b.set(i, true);
        }

2023
        assert_eq!(a, b);
2024 2025
    }

2026
    #[test]
2027 2028
    fn test_from_bytes() {
        let bitv = from_bytes([0b10110110, 0b00000000, 0b11111111]);
2029
        let str = format!("{}{}{}", "10110110", "00000000", "11111111");
2030
        assert_eq!(bitv.to_string().as_slice(), str.as_slice());
2031 2032 2033
    }

    #[test]
2034
    fn test_to_bytes() {
2035
        let mut bv = Bitv::with_capacity(3, true);
2036
        bv.set(1, false);
2037
        assert_eq!(bv.to_bytes(), vec!(0b10100000));
2038

2039
        let mut bv = Bitv::with_capacity(9, false);
2040 2041
        bv.set(2, true);
        bv.set(8, true);
2042
        assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000));
2043 2044 2045
    }

    #[test]
2046
    fn test_from_bools() {
2047 2048
        let bools = vec![true, false, true, true];
        let bitv: Bitv = bools.iter().map(|n| *n).collect();
2049
        assert_eq!(bitv.to_string().as_slice(), "1011");
2050 2051
    }

2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
    #[test]
    fn test_bitv_set_from_bools() {
        let bools = vec![true, false, true, true];
        let a: BitvSet = bools.iter().map(|n| *n).collect();
        let mut b = BitvSet::new();
        b.insert(0);
        b.insert(2);
        b.insert(3);
        assert_eq!(a, b);
    }

2063
    #[test]
2064
    fn test_to_bools() {
2065
        let bools = vec!(false, false, true, false, false, true, true, false);
2066
        assert_eq!(from_bytes([0b00100110]).iter().collect::<Vec<bool>>(), bools);
2067
    }
2068

S
Steven Fackler 已提交
2069 2070
    #[test]
    fn test_bitv_iterator() {
2071
        let bools = vec![true, false, true, true];
2072
        let bitv: Bitv = bools.iter().map(|n| *n).collect();
S
Steven Fackler 已提交
2073

2074 2075 2076 2077 2078
        assert_eq!(bitv.iter().collect::<Vec<bool>>(), bools)

        let long = Vec::from_fn(10000, |i| i % 2 == 0);
        let bitv: Bitv = long.iter().map(|n| *n).collect();
        assert_eq!(bitv.iter().collect::<Vec<bool>>(), long)
S
Steven Fackler 已提交
2079 2080 2081 2082 2083
    }

    #[test]
    fn test_bitv_set_iterator() {
        let bools = [true, false, true, true];
2084
        let bitv: BitvSet = bools.iter().map(|n| *n).collect();
S
Steven Fackler 已提交
2085

2086 2087
        let idxs: Vec<uint> = bitv.iter().collect();
        assert_eq!(idxs, vec!(0, 2, 3));
2088 2089 2090 2091 2092 2093

        let long: BitvSet = range(0u, 10000).map(|n| n % 2 == 0).collect();
        let real = range_step(0, 10000, 2).collect::<Vec<uint>>();

        let idxs: Vec<uint> = long.iter().collect();
        assert_eq!(idxs, real);
S
Steven Fackler 已提交
2094 2095
    }

2096 2097 2098 2099 2100 2101
    #[test]
    fn test_bitv_set_frombitv_init() {
        let bools = [true, false];
        let lengths = [10, 64, 100];
        for &b in bools.iter() {
            for &l in lengths.iter() {
2102
                let bitset = BitvSet::from_bitv(Bitv::with_capacity(l, b));
2103 2104 2105 2106 2107 2108 2109
                assert_eq!(bitset.contains(&1u), b)
                assert_eq!(bitset.contains(&(l-1u)), b)
                assert!(!bitset.contains(&l))
            }
        }
    }

2110
    #[test]
2111
    fn test_small_difference() {
2112 2113
        let mut b1 = Bitv::with_capacity(3, false);
        let mut b2 = Bitv::with_capacity(3, false);
2114 2115 2116 2117
        b1.set(0, true);
        b1.set(1, true);
        b2.set(1, true);
        b2.set(2, true);
P
Patrick Walton 已提交
2118
        assert!(b1.difference(&b2));
2119 2120 2121
        assert!(b1.get(0));
        assert!(!b1.get(1));
        assert!(!b1.get(2));
2122 2123 2124
    }

    #[test]
2125
    fn test_big_difference() {
2126 2127
        let mut b1 = Bitv::with_capacity(100, false);
        let mut b2 = Bitv::with_capacity(100, false);
2128 2129 2130 2131
        b1.set(0, true);
        b1.set(40, true);
        b2.set(40, true);
        b2.set(80, true);
P
Patrick Walton 已提交
2132
        assert!(b1.difference(&b2));
2133 2134 2135
        assert!(b1.get(0));
        assert!(!b1.get(40));
        assert!(!b1.get(80));
2136
    }
2137 2138

    #[test]
2139
    fn test_small_clear() {
2140
        let mut b = Bitv::with_capacity(14, true);
2141
        b.clear();
2142
        assert!(b.none());
2143 2144 2145
    }

    #[test]
2146
    fn test_big_clear() {
2147
        let mut b = Bitv::with_capacity(140, true);
2148
        b.clear();
2149
        assert!(b.none());
2150 2151
    }

2152 2153
    #[test]
    fn test_bitv_masking() {
2154
        let b = Bitv::with_capacity(140, true);
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
        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));
    }

2165
    #[test]
2166
    fn test_bitv_set_basic() {
2167
        // calculate nbits with u32::BITS granularity
2168
        fn calc_nbits(bits: uint) -> uint {
2169
            u32::BITS * ((bits + u32::BITS - 1) / u32::BITS)
2170 2171
        }

2172
        let mut b = BitvSet::new();
2173
        assert_eq!(b.capacity(), calc_nbits(0));
P
Patrick Walton 已提交
2174
        assert!(b.insert(3));
2175
        assert_eq!(b.capacity(), calc_nbits(3));
P
Patrick Walton 已提交
2176 2177
        assert!(!b.insert(3));
        assert!(b.contains(&3));
2178 2179 2180
        assert!(b.insert(4));
        assert!(!b.insert(4));
        assert!(b.contains(&3));
P
Patrick Walton 已提交
2181
        assert!(b.insert(400));
2182
        assert_eq!(b.capacity(), calc_nbits(400));
P
Patrick Walton 已提交
2183 2184
        assert!(!b.insert(400));
        assert!(b.contains(&400));
2185
        assert_eq!(b.len(), 3);
2186 2187 2188 2189 2190 2191 2192
    }

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

P
Patrick Walton 已提交
2193 2194 2195 2196 2197 2198
        assert!(a.insert(11));
        assert!(a.insert(1));
        assert!(a.insert(3));
        assert!(a.insert(77));
        assert!(a.insert(103));
        assert!(a.insert(5));
2199

P
Patrick Walton 已提交
2200 2201 2202 2203 2204
        assert!(b.insert(2));
        assert!(b.insert(11));
        assert!(b.insert(77));
        assert!(b.insert(5));
        assert!(b.insert(3));
2205 2206

        let expected = [3, 5, 11, 77];
2207 2208
        let actual = a.intersection(&b).collect::<Vec<uint>>();
        assert_eq!(actual.as_slice(), expected.as_slice());
2209 2210 2211 2212 2213 2214 2215
    }

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

P
Patrick Walton 已提交
2216 2217 2218 2219 2220
        assert!(a.insert(1));
        assert!(a.insert(3));
        assert!(a.insert(5));
        assert!(a.insert(200));
        assert!(a.insert(500));
2221

P
Patrick Walton 已提交
2222 2223
        assert!(b.insert(3));
        assert!(b.insert(200));
2224 2225

        let expected = [1, 5, 500];
2226 2227
        let actual = a.difference(&b).collect::<Vec<uint>>();
        assert_eq!(actual.as_slice(), expected.as_slice());
2228 2229 2230 2231 2232 2233 2234
    }

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

P
Patrick Walton 已提交
2235 2236 2237 2238 2239
        assert!(a.insert(1));
        assert!(a.insert(3));
        assert!(a.insert(5));
        assert!(a.insert(9));
        assert!(a.insert(11));
2240

P
Patrick Walton 已提交
2241 2242 2243 2244
        assert!(b.insert(3));
        assert!(b.insert(9));
        assert!(b.insert(14));
        assert!(b.insert(220));
2245 2246

        let expected = [1, 5, 11, 14, 220];
2247 2248
        let actual = a.symmetric_difference(&b).collect::<Vec<uint>>();
        assert_eq!(actual.as_slice(), expected.as_slice());
2249 2250 2251
    }

    #[test]
2252
    fn test_bitv_set_union() {
2253 2254
        let mut a = BitvSet::new();
        let mut b = BitvSet::new();
P
Patrick Walton 已提交
2255 2256 2257 2258 2259 2260 2261 2262
        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));
2263
        assert!(a.insert(200));
P
Patrick Walton 已提交
2264 2265 2266 2267 2268 2269

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

2271
        let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160, 200];
2272 2273
        let actual = a.union(&b).collect::<Vec<uint>>();
        assert_eq!(actual.as_slice(), expected.as_slice());
2274 2275
    }

2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
    #[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 }
    }

2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
    #[test]
    fn test_bitv_set_is_disjoint() {
        let a = BitvSet::from_bitv(from_bytes([0b10100010]));
        let b = BitvSet::from_bitv(from_bytes([0b01000000]));
        let c = BitvSet::new();
        let d = BitvSet::from_bitv(from_bytes([0b00110000]));

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

        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))
    }

2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340
    #[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);
        let expected = BitvSet::from_bitv(from_bytes([0b10000100]));
        a.union_with(&b);
        assert_eq!(a, expected);

        // Standard
        let mut a = BitvSet::from_bitv(from_bytes([0b10100010]));
        let mut b = BitvSet::from_bitv(from_bytes([0b01100010]));
        let c = a.clone();
        a.union_with(&b);
        b.union_with(&c);
        assert_eq!(a.len(), 4);
        assert_eq!(b.len(), 4);
    }

2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370
    #[test]
    fn test_bitv_set_intersect_with() {
        // Explicitly 0'ed bits
        let mut a = BitvSet::from_bitv(from_bytes([0b10100010]));
        let mut b = BitvSet::from_bitv(from_bytes([0b00000000]));
        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
        let mut a = BitvSet::from_bitv(from_bytes([0b10100010]));
        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
        let mut a = BitvSet::from_bitv(from_bytes([0b10100010]));
        let mut b = BitvSet::from_bitv(from_bytes([0b01100010]));
        let c = a.clone();
        a.intersect_with(&b);
        b.intersect_with(&c);
        assert_eq!(a.len(), 2);
        assert_eq!(b.len(), 2);
    }

2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
    #[test]
    fn test_bitv_set_difference_with() {
        // Explicitly 0'ed bits
        let mut a = BitvSet::from_bitv(from_bytes([0b00000000]));
        let b = BitvSet::from_bitv(from_bytes([0b10100010]));
        a.difference_with(&b);
        assert!(a.is_empty());

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

        // Standard
        let mut a = BitvSet::from_bitv(from_bytes([0b10100010]));
        let mut b = BitvSet::from_bitv(from_bytes([0b01100010]));
        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);
        let expected = BitvSet::from_bitv(from_bytes([0b10000100]));
        a.symmetric_difference_with(&b);
        assert_eq!(a, expected);

        let mut a = BitvSet::from_bitv(from_bytes([0b10100010]));
        let b = BitvSet::new();
        let c = a.clone();
        a.symmetric_difference_with(&b);
        assert_eq!(a, c);

        // Standard
        let mut a = BitvSet::from_bitv(from_bytes([0b11100010]));
        let mut b = BitvSet::from_bitv(from_bytes([0b01101010]));
        let c = a.clone();
        a.symmetric_difference_with(&b);
        b.symmetric_difference_with(&c);
        assert_eq!(a.len(), 2);
        assert_eq!(b.len(), 2);
    }

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
    #[test]
    fn test_bitv_set_eq() {
        let a = BitvSet::from_bitv(from_bytes([0b10100010]));
        let b = BitvSet::from_bitv(from_bytes([0b00000000]));
        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() {
        let a = BitvSet::from_bitv(from_bytes([0b10100010]));
        let b = BitvSet::from_bitv(from_bytes([0b00000000]));
        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);
    }

2452
    #[test]
2453
    fn test_bitv_remove() {
2454 2455
        let mut a = BitvSet::new();

P
Patrick Walton 已提交
2456 2457
        assert!(a.insert(1));
        assert!(a.remove(&1));
2458

P
Patrick Walton 已提交
2459 2460
        assert!(a.insert(100));
        assert!(a.remove(&100));
2461

P
Patrick Walton 已提交
2462 2463
        assert!(a.insert(1000));
        assert!(a.remove(&1000));
2464
        a.shrink_to_fit();
2465
        assert_eq!(a.capacity(), u32::BITS);
2466
    }
2467

N
nham 已提交
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
    #[test]
    fn test_bitv_lt() {
        let mut a = Bitv::with_capacity(5u, false);
        let mut b = Bitv::with_capacity(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);
    }

    #[test]
    fn test_ord() {
        let mut a = Bitv::with_capacity(5u, false);
        let mut b = Bitv::with_capacity(5u, false);

        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);
    }

S
Steven Fackler 已提交
2499 2500 2501 2502 2503 2504 2505 2506 2507 2508
    #[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();

2509
        assert!(a == b);
S
Steven Fackler 已提交
2510 2511 2512 2513 2514 2515 2516 2517

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

        assert!(a.remove(&1000));
        assert!(b.contains(&1000));
    }

2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
    #[test]
    fn test_small_bitv_tests() {
        let v = from_bytes([0]);
        assert!(!v.all());
        assert!(!v.any());
        assert!(v.none());

        let v = from_bytes([0b00010100]);
        assert!(!v.all());
        assert!(v.any());
        assert!(!v.none());

        let v = from_bytes([0xFF]);
        assert!(v.all());
        assert!(v.any());
        assert!(!v.none());
    }

    #[test]
    fn test_big_bitv_tests() {
        let v = 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 = 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 = from_bytes([ // 88 bits
            0xFF, 0xFF, 0xFF, 0xFF,
            0xFF, 0xFF, 0xFF, 0xFF,
            0xFF, 0xFF, 0xFF]);
        assert!(v.all());
        assert!(v.any());
        assert!(!v.none());
    }

2563 2564
    #[test]
    fn test_bitv_push_pop() {
2565 2566 2567
        let mut s = Bitv::with_capacity(5 * u32::BITS - 2, false);
        assert_eq!(s.len(), 5 * u32::BITS - 2);
        assert_eq!(s.get(5 * u32::BITS - 3), false);
2568 2569
        s.push(true);
        s.push(true);
2570 2571
        assert_eq!(s.get(5 * u32::BITS - 2), true);
        assert_eq!(s.get(5 * u32::BITS - 1), true);
2572 2573
        // Here the internal vector will need to be extended
        s.push(false);
2574
        assert_eq!(s.get(5 * u32::BITS), false);
2575
        s.push(false);
2576 2577
        assert_eq!(s.get(5 * u32::BITS + 1), false);
        assert_eq!(s.len(), 5 * u32::BITS + 2);
2578 2579 2580 2581 2582
        // Pop it all off
        assert_eq!(s.pop(), false);
        assert_eq!(s.pop(), false);
        assert_eq!(s.pop(), true);
        assert_eq!(s.pop(), true);
2583
        assert_eq!(s.len(), 5 * u32::BITS - 2);
2584 2585 2586 2587
    }

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

2590 2591 2592 2593 2594
        assert_eq!(s, Bitv::with_capacity(5 * u32::BITS, true));
        assert_eq!(s.len(), 5 * u32::BITS);
        s.truncate(4 * u32::BITS);
        assert_eq!(s, Bitv::with_capacity(4 * u32::BITS, true));
        assert_eq!(s.len(), 4 * u32::BITS);
2595
        // Truncating to a size > s.len() should be a noop
2596 2597 2598 2599 2600 2601
        s.truncate(5 * u32::BITS);
        assert_eq!(s, Bitv::with_capacity(4 * u32::BITS, true));
        assert_eq!(s.len(), 4 * u32::BITS);
        s.truncate(3 * u32::BITS - 10);
        assert_eq!(s, Bitv::with_capacity(3 * u32::BITS - 10, true));
        assert_eq!(s.len(), 3 * u32::BITS - 10);
2602
        s.truncate(0);
2603
        assert_eq!(s, Bitv::with_capacity(0, true));
2604 2605 2606 2607 2608
        assert_eq!(s.len(), 0);
    }

    #[test]
    fn test_bitv_reserve() {
2609
        let mut s = Bitv::with_capacity(5 * u32::BITS, true);
2610
        // Check capacity
2611 2612 2613 2614 2615 2616 2617 2618 2619
        assert_eq!(s.capacity(), 5 * u32::BITS);
        s.reserve(2 * u32::BITS);
        assert_eq!(s.capacity(), 5 * u32::BITS);
        s.reserve(7 * u32::BITS);
        assert_eq!(s.capacity(), 7 * u32::BITS);
        s.reserve(7 * u32::BITS);
        assert_eq!(s.capacity(), 7 * u32::BITS);
        s.reserve(7 * u32::BITS + 1);
        assert_eq!(s.capacity(), 8 * u32::BITS);
2620
        // Check that length hasn't changed
2621
        assert_eq!(s.len(), 5 * u32::BITS);
2622 2623 2624
        s.push(true);
        s.push(false);
        s.push(true);
2625 2626 2627 2628
        assert_eq!(s.get(5 * u32::BITS - 1), true);
        assert_eq!(s.get(5 * u32::BITS - 0), true);
        assert_eq!(s.get(5 * u32::BITS + 1), false);
        assert_eq!(s.get(5 * u32::BITS + 2), true);
2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653
    }

    #[test]
    fn test_bitv_grow() {
        let mut bitv = from_bytes([0b10110110, 0b00000000, 0b10101010]);
        bitv.grow(32, true);
        assert_eq!(bitv, from_bytes([0b10110110, 0b00000000, 0b10101010,
                                     0xFF, 0xFF, 0xFF, 0xFF]));
        bitv.grow(64, false);
        assert_eq!(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, 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 = from_bytes([0b10110110, 0b00000000, 0b11111111]);
        let ext = from_bytes([0b01001001, 0b10010010, 0b10111101]);
        bitv.extend(ext.iter());
        assert_eq!(bitv, from_bytes([0b10110110, 0b00000000, 0b11111111,
                                     0b01001001, 0b10010010, 0b10111101]));
    }

S
Steven Fackler 已提交
2654 2655 2656 2657 2658 2659 2660
    #[test]
    fn test_bitv_set_show() {
        let mut s = BitvSet::new();
        s.insert(1);
        s.insert(10);
        s.insert(50);
        s.insert(2);
2661
        assert_eq!("{1, 2, 10, 50}".to_string(), s.to_string());
S
Steven Fackler 已提交
2662 2663
    }

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

    #[bench]
2670
    fn bench_uint_small(b: &mut Bencher) {
P
Patrick Walton 已提交
2671
        let mut r = rng();
2672
        let mut bitv = 0 as uint;
2673
        b.iter(|| {
2674
            for _ in range(0u, 100) {
2675
                bitv |= 1 << ((r.next_u32() as uint) % u32::BITS);
2676
            }
2677
            &bitv
2678
        })
2679 2680 2681
    }

    #[bench]
2682
    fn bench_bitv_set_big_fixed(b: &mut Bencher) {
P
Patrick Walton 已提交
2683
        let mut r = rng();
2684
        let mut bitv = Bitv::with_capacity(BENCH_BITS, false);
2685
        b.iter(|| {
2686 2687 2688
            for _ in range(0u, 100) {
                bitv.set((r.next_u32() as uint) % BENCH_BITS, true);
            }
2689
            &bitv
2690
        })
2691 2692 2693
    }

    #[bench]
2694 2695 2696 2697
    fn bench_bitv_set_big_variable(b: &mut Bencher) {
        let mut r = rng();
        let mut bitv = Bitv::with_capacity(BENCH_BITS, false);
        b.iter(|| {
N
NODA, Kai 已提交
2698
            for _ in range(0u, 100) {
2699 2700 2701 2702 2703 2704 2705 2706
                bitv.set((r.next_u32() as uint) % BENCH_BITS, r.gen());
            }
            &bitv
        })
    }

    #[bench]
    fn bench_bitv_set_small(b: &mut Bencher) {
P
Patrick Walton 已提交
2707
        let mut r = rng();
2708
        let mut bitv = Bitv::with_capacity(u32::BITS, false);
2709
        b.iter(|| {
2710
            for _ in range(0u, 100) {
2711
                bitv.set((r.next_u32() as uint) % u32::BITS, true);
2712
            }
2713
            &bitv
2714
        })
2715 2716 2717
    }

    #[bench]
2718
    fn bench_bitvset_small(b: &mut Bencher) {
P
Patrick Walton 已提交
2719
        let mut r = rng();
2720
        let mut bitv = BitvSet::new();
2721
        b.iter(|| {
2722
            for _ in range(0u, 100) {
2723
                bitv.insert((r.next_u32() as uint) % u32::BITS);
2724
            }
2725
            &bitv
2726
        })
2727 2728 2729
    }

    #[bench]
2730
    fn bench_bitvset_big(b: &mut Bencher) {
P
Patrick Walton 已提交
2731
        let mut r = rng();
2732
        let mut bitv = BitvSet::new();
2733
        b.iter(|| {
2734 2735 2736
            for _ in range(0u, 100) {
                bitv.insert((r.next_u32() as uint) % BENCH_BITS);
            }
2737
            &bitv
2738
        })
2739 2740 2741
    }

    #[bench]
2742
    fn bench_bitv_big_union(b: &mut Bencher) {
2743 2744
        let mut b1 = Bitv::with_capacity(BENCH_BITS, false);
        let b2 = Bitv::with_capacity(BENCH_BITS, false);
2745
        b.iter(|| {
2746
            b1.union(&b2)
2747
        })
2748
    }
S
Steven Fackler 已提交
2749 2750

    #[bench]
2751
    fn bench_bitv_small_iter(b: &mut Bencher) {
2752
        let bitv = Bitv::with_capacity(u32::BITS, false);
2753
        b.iter(|| {
2754
            let mut sum = 0u;
2755 2756 2757 2758
            for _ in range(0u, 10) {
                for pres in bitv.iter() {
                    sum += pres as uint;
                }
S
Steven Fackler 已提交
2759
            }
2760
            sum
2761
        })
S
Steven Fackler 已提交
2762 2763 2764
    }

    #[bench]
2765
    fn bench_bitv_big_iter(b: &mut Bencher) {
2766
        let bitv = Bitv::with_capacity(BENCH_BITS, false);
2767
        b.iter(|| {
2768
            let mut sum = 0u;
D
Daniel Micay 已提交
2769
            for pres in bitv.iter() {
2770
                sum += pres as uint;
S
Steven Fackler 已提交
2771
            }
2772
            sum
2773
        })
S
Steven Fackler 已提交
2774 2775 2776
    }

    #[bench]
2777
    fn bench_bitvset_iter(b: &mut Bencher) {
S
Steven Fackler 已提交
2778 2779
        let bitv = BitvSet::from_bitv(from_fn(BENCH_BITS,
                                              |idx| {idx % 3 == 0}));
2780
        b.iter(|| {
2781
            let mut sum = 0u;
D
Daniel Micay 已提交
2782
            for idx in bitv.iter() {
2783
                sum += idx as uint;
S
Steven Fackler 已提交
2784
            }
2785
            sum
2786
        })
S
Steven Fackler 已提交
2787
    }
2788
}