1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // FIXME(Gankro): Bitv and BitvSet are very tightly coupled. Ideally (for
12 // maintenance), they should be in separate files/modules, with BitvSet only
13 // using Bitv's public API. This will be hard for performance though, because
14 // `Bitv` will not want to leak its internal representation while its internal
15 // representation as `u32`s must be assumed for best performance.
17 // FIXME(tbu-): `Bitv`'s methods shouldn't be `union`, `intersection`, but
18 // rather `or` and `and`.
20 // (1) Be careful, most things can overflow here because the amount of bits in
21 // memory can overflow `usize`.
22 // (2) Make sure that the underlying vector has no excess length:
23 // E. g. `nbits == 16`, `storage.len() == 2` would be excess length,
24 // because the last word isn't used at all. This is important because some
25 // methods rely on it (for *CORRECTNESS*).
26 // (3) Make sure that the unused bits in the last word are zeroed out, again
27 // other methods rely on it for *CORRECTNESS*.
28 // (4) `BitvSet` is tightly coupled with `Bitv`, so any changes you make in
29 // `Bitv` will need to be reflected in `BitvSet`.
31 //! Collections implemented with bit vectors.
35 //! This is a simple example of the [Sieve of Eratosthenes][sieve]
36 //! which calculates prime numbers up to a given limit.
38 //! [sieve]: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
41 //! use std::collections::{BitvSet, Bitv};
42 //! use std::num::Float;
45 //! let max_prime = 10000;
47 //! // Store the primes as a BitvSet
49 //! // Assume all numbers are prime to begin, and then we
50 //! // cross off non-primes progressively
51 //! let mut bv = Bitv::from_elem(max_prime, true);
53 //! // Neither 0 nor 1 are prime
57 //! for i in iter::range_inclusive(2, (max_prime as f64).sqrt() as usize) {
58 //! // if i is a prime
60 //! // Mark all multiples of i as non-prime (any multiples below i * i
61 //! // will have been marked as non-prime previously)
62 //! for j in iter::range_step(i * i, max_prime, i) { bv.set(j, false) }
65 //! BitvSet::from_bitv(bv)
68 //! // Simple primality tests below our max bound
69 //! let print_primes = 20;
70 //! print!("The primes below {} are: ", print_primes);
71 //! for x in 0..print_primes {
72 //! if primes.contains(&x) {
78 //! // We can manipulate the internal Bitv
79 //! let num_primes = primes.get_ref().iter().filter(|x| *x).count();
80 //! println!("There are {} primes below {}", num_primes, max_prime);
85 use core::cmp::Ordering;
87 use core::default::Default;
90 use core::iter::RandomAccessIterator;
91 use core::iter::{Chain, Enumerate, Repeat, Skip, Take, repeat, Cloned};
92 use core::iter::{self, FromIterator, IntoIterator};
96 use core::{u8, u32, usize};
97 use bitv_set; //so meta
101 type Blocks<'a> = Cloned<slice::Iter<'a, u32>>;
102 type MutBlocks<'a> = slice::IterMut<'a, u32>;
103 type MatchWords<'a> = Chain<Enumerate<Blocks<'a>>, Skip<Take<Enumerate<Repeat<u32>>>>>;
105 fn reverse_bits(byte: u8) -> u8 {
107 for i in 0..u8::BITS {
108 result |= ((byte >> i) & 1) << (u8::BITS - 1 - i);
113 // Take two BitV's, and return iterators of their words, where the shorter one
114 // has been padded with 0's
115 fn match_words <'a,'b>(a: &'a Bitv, b: &'b Bitv) -> (MatchWords<'a>, MatchWords<'b>) {
116 let a_len = a.storage.len();
117 let b_len = b.storage.len();
119 // have to uselessly pretend to pad the longer one for type matching
121 (a.blocks().enumerate().chain(iter::repeat(0u32).enumerate().take(b_len).skip(a_len)),
122 b.blocks().enumerate().chain(iter::repeat(0u32).enumerate().take(0).skip(0)))
124 (a.blocks().enumerate().chain(iter::repeat(0u32).enumerate().take(0).skip(0)),
125 b.blocks().enumerate().chain(iter::repeat(0u32).enumerate().take(a_len).skip(b_len)))
129 static TRUE: bool = true;
130 static FALSE: bool = false;
132 /// The bitvector type.
137 /// use std::collections::Bitv;
139 /// let mut bv = Bitv::from_elem(10, false);
141 /// // insert all primes less than 10
146 /// println!("{:?}", bv);
147 /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
149 /// // flip all values in bitvector, producing non-primes less than 10
151 /// println!("{:?}", bv);
152 /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
154 /// // reset bitvector to empty
156 /// println!("{:?}", bv);
157 /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
159 #[unstable(feature = "collections",
162 /// Internal representation of the bit vector
164 /// The number of valid bits in the internal representation
168 // FIXME(Gankro): NopeNopeNopeNopeNope (wait for IndexGet to be a thing)
169 impl Index<usize> for Bitv {
173 fn index(&self, i: &usize) -> &bool {
174 if self.get(*i).expect("index out of bounds") {
182 /// Computes how many blocks are needed to store that many bits
183 fn blocks_for_bits(bits: usize) -> usize {
184 // If we want 17 bits, dividing by 32 will produce 0. So we add 1 to make sure we
185 // reserve enough. But if we want exactly a multiple of 32, this will actually allocate
186 // one too many. So we need to check if that's the case. We can do that by computing if
187 // bitwise AND by `32 - 1` is 0. But LLVM should be able to optimize the semantically
188 // superior modulo operator on a power of two to this.
190 // Note that we can technically avoid this branch with the expression
191 // `(nbits + u32::BITS - 1) / 32::BITS`, but if nbits is almost usize::MAX this will overflow.
192 if bits % u32::BITS == 0 {
199 /// Computes the bitmask for the final word of the vector
200 fn mask_for_bits(bits: usize) -> u32 {
201 // Note especially that a perfect multiple of u32::BITS should mask all 1s.
202 !0u32 >> (u32::BITS - bits % u32::BITS) % u32::BITS
206 /// Applies the given operation to the blocks of self and other, and sets
207 /// self to be the result. This relies on the caller not to corrupt the
210 fn process<F>(&mut self, other: &Bitv, mut op: F) -> bool where F: FnMut(u32, u32) -> u32 {
211 assert_eq!(self.len(), other.len());
212 // This could theoretically be a `debug_assert!`.
213 assert_eq!(self.storage.len(), other.storage.len());
214 let mut changed = false;
215 for (a, b) in self.blocks_mut().zip(other.blocks()) {
225 /// Iterator over mutable refs to the underlying blocks of data.
226 fn blocks_mut(&mut self) -> MutBlocks {
228 self.storage.iter_mut()
231 /// Iterator over the underlying blocks of data
232 fn blocks(&self) -> Blocks {
234 self.storage.iter().cloned()
237 /// An operation might screw up the unused bits in the last block of the
238 /// `Bitv`. As per (3), it's assumed to be all 0s. This method fixes it up.
239 fn fix_last_block(&mut self) {
240 let extra_bits = self.len() % u32::BITS;
242 let mask = (1 << extra_bits) - 1;
243 let storage_len = self.storage.len();
244 self.storage[storage_len - 1] &= mask;
248 /// Creates an empty `Bitv`.
253 /// use std::collections::Bitv;
254 /// let mut bv = Bitv::new();
256 #[stable(feature = "rust1", since = "1.0.0")]
257 pub fn new() -> Bitv {
258 Bitv { storage: Vec::new(), nbits: 0 }
261 /// Creates a `Bitv` that holds `nbits` elements, setting each element
267 /// use std::collections::Bitv;
269 /// let mut bv = Bitv::from_elem(10, false);
270 /// assert_eq!(bv.len(), 10);
271 /// for x in bv.iter() {
272 /// assert_eq!(x, false);
275 pub fn from_elem(nbits: usize, bit: bool) -> Bitv {
276 let nblocks = blocks_for_bits(nbits);
277 let mut bitv = Bitv {
278 storage: repeat(if bit { !0u32 } else { 0u32 }).take(nblocks).collect(),
281 bitv.fix_last_block();
285 /// Constructs a new, empty `Bitv` with the specified capacity.
287 /// The bitvector will be able to hold at least `capacity` bits without
288 /// reallocating. If `capacity` is 0, it will not allocate.
290 /// It is important to note that this function does not specify the
291 /// *length* of the returned bitvector, but only the *capacity*.
292 #[stable(feature = "rust1", since = "1.0.0")]
293 pub fn with_capacity(nbits: usize) -> Bitv {
295 storage: Vec::with_capacity(blocks_for_bits(nbits)),
300 /// Transforms a byte-vector into a `Bitv`. Each byte becomes eight bits,
301 /// with the most significant bits of each byte coming first. Each
302 /// bit becomes `true` if equal to 1 or `false` if equal to 0.
307 /// use std::collections::Bitv;
309 /// let bv = Bitv::from_bytes(&[0b10100000, 0b00010010]);
310 /// assert!(bv.eq_vec(&[true, false, true, false,
311 /// false, false, false, false,
312 /// false, false, false, true,
313 /// false, false, true, false]));
315 pub fn from_bytes(bytes: &[u8]) -> Bitv {
316 let len = bytes.len().checked_mul(u8::BITS).expect("capacity overflow");
317 let mut bitv = Bitv::with_capacity(len);
318 let complete_words = bytes.len() / 4;
319 let extra_bytes = bytes.len() % 4;
323 for i in 0..complete_words {
325 ((reverse_bits(bytes[i * 4 + 0]) as u32) << 0) |
326 ((reverse_bits(bytes[i * 4 + 1]) as u32) << 8) |
327 ((reverse_bits(bytes[i * 4 + 2]) as u32) << 16) |
328 ((reverse_bits(bytes[i * 4 + 3]) as u32) << 24)
333 let mut last_word = 0u32;
334 for (i, &byte) in bytes[complete_words*4..].iter().enumerate() {
335 last_word |= (reverse_bits(byte) as u32) << (i * 8);
337 bitv.storage.push(last_word);
343 /// Creates a `Bitv` of the specified length where the value at each index
349 /// use std::collections::Bitv;
351 /// let bv = Bitv::from_fn(5, |i| { i % 2 == 0 });
352 /// assert!(bv.eq_vec(&[true, false, true, false, true]));
354 pub fn from_fn<F>(len: usize, mut f: F) -> Bitv where F: FnMut(usize) -> bool {
355 let mut bitv = Bitv::from_elem(len, false);
362 /// Retrieves the value at index `i`, or `None` if the index is out of bounds.
367 /// use std::collections::Bitv;
369 /// let bv = Bitv::from_bytes(&[0b01100000]);
370 /// assert_eq!(bv.get(0), Some(false));
371 /// assert_eq!(bv.get(1), Some(true));
372 /// assert_eq!(bv.get(100), None);
374 /// // Can also use array indexing
375 /// assert_eq!(bv[1], true);
378 #[stable(feature = "rust1", since = "1.0.0")]
379 pub fn get(&self, i: usize) -> Option<bool> {
383 let w = i / u32::BITS;
384 let b = i % u32::BITS;
385 self.storage.get(w).map(|&block|
386 (block & (1 << b)) != 0
390 /// Sets the value of a bit at an index `i`.
394 /// Panics if `i` is out of bounds.
399 /// use std::collections::Bitv;
401 /// let mut bv = Bitv::from_elem(5, false);
403 /// assert_eq!(bv[3], true);
406 #[unstable(feature = "collections",
407 reason = "panic semantics are likely to change in the future")]
408 pub fn set(&mut self, i: usize, x: bool) {
409 assert!(i < self.nbits);
410 let w = i / u32::BITS;
411 let b = i % u32::BITS;
413 let val = if x { self.storage[w] | flag }
414 else { self.storage[w] & !flag };
415 self.storage[w] = val;
418 /// Sets all bits to 1.
423 /// use std::collections::Bitv;
425 /// let before = 0b01100000;
426 /// let after = 0b11111111;
428 /// let mut bv = Bitv::from_bytes(&[before]);
430 /// assert_eq!(bv, Bitv::from_bytes(&[after]));
433 pub fn set_all(&mut self) {
434 for w in &mut self.storage { *w = !0u32; }
435 self.fix_last_block();
443 /// use std::collections::Bitv;
445 /// let before = 0b01100000;
446 /// let after = 0b10011111;
448 /// let mut bv = Bitv::from_bytes(&[before]);
450 /// assert_eq!(bv, Bitv::from_bytes(&[after]));
453 pub fn negate(&mut self) {
454 for w in &mut self.storage { *w = !*w; }
455 self.fix_last_block();
458 /// Calculates the union of two bitvectors. This acts like the bitwise `or`
461 /// Sets `self` to the union of `self` and `other`. Both bitvectors must be
462 /// the same length. Returns `true` if `self` changed.
466 /// Panics if the bitvectors are of different lengths.
471 /// use std::collections::Bitv;
473 /// let a = 0b01100100;
474 /// let b = 0b01011010;
475 /// let res = 0b01111110;
477 /// let mut a = Bitv::from_bytes(&[a]);
478 /// let b = Bitv::from_bytes(&[b]);
480 /// assert!(a.union(&b));
481 /// assert_eq!(a, Bitv::from_bytes(&[res]));
484 pub fn union(&mut self, other: &Bitv) -> bool {
485 self.process(other, |w1, w2| w1 | w2)
488 /// Calculates the intersection of two bitvectors. This acts like the
489 /// bitwise `and` function.
491 /// Sets `self` to the intersection of `self` and `other`. Both bitvectors
492 /// must be the same length. Returns `true` if `self` changed.
496 /// Panics if the bitvectors are of different lengths.
501 /// use std::collections::Bitv;
503 /// let a = 0b01100100;
504 /// let b = 0b01011010;
505 /// let res = 0b01000000;
507 /// let mut a = Bitv::from_bytes(&[a]);
508 /// let b = Bitv::from_bytes(&[b]);
510 /// assert!(a.intersect(&b));
511 /// assert_eq!(a, Bitv::from_bytes(&[res]));
514 pub fn intersect(&mut self, other: &Bitv) -> bool {
515 self.process(other, |w1, w2| w1 & w2)
518 /// Calculates the difference between two bitvectors.
520 /// Sets each element of `self` to the value of that element minus the
521 /// element of `other` at the same index. Both bitvectors must be the same
522 /// length. Returns `true` if `self` changed.
526 /// Panics if the bitvectors are of different length.
531 /// use std::collections::Bitv;
533 /// let a = 0b01100100;
534 /// let b = 0b01011010;
535 /// let a_b = 0b00100100; // a - b
536 /// let b_a = 0b00011010; // b - a
538 /// let mut bva = Bitv::from_bytes(&[a]);
539 /// let bvb = Bitv::from_bytes(&[b]);
541 /// assert!(bva.difference(&bvb));
542 /// assert_eq!(bva, Bitv::from_bytes(&[a_b]));
544 /// let bva = Bitv::from_bytes(&[a]);
545 /// let mut bvb = Bitv::from_bytes(&[b]);
547 /// assert!(bvb.difference(&bva));
548 /// assert_eq!(bvb, Bitv::from_bytes(&[b_a]));
551 pub fn difference(&mut self, other: &Bitv) -> bool {
552 self.process(other, |w1, w2| w1 & !w2)
555 /// Returns `true` if all bits are 1.
560 /// use std::collections::Bitv;
562 /// let mut bv = Bitv::from_elem(5, true);
563 /// assert_eq!(bv.all(), true);
565 /// bv.set(1, false);
566 /// assert_eq!(bv.all(), false);
568 pub fn all(&self) -> bool {
569 let mut last_word = !0u32;
570 // Check that every block but the last is all-ones...
571 self.blocks().all(|elem| {
575 // and then check the last one has enough ones
576 }) && (last_word == mask_for_bits(self.nbits))
579 /// Returns an iterator over the elements of the vector in order.
584 /// use std::collections::Bitv;
586 /// let bv = Bitv::from_bytes(&[0b01110100, 0b10010010]);
587 /// assert_eq!(bv.iter().filter(|x| *x).count(), 7);
590 #[stable(feature = "rust1", since = "1.0.0")]
591 pub fn iter(&self) -> Iter {
592 Iter { bitv: self, next_idx: 0, end_idx: self.nbits }
595 /// Returns `true` if all bits are 0.
600 /// use std::collections::Bitv;
602 /// let mut bv = Bitv::from_elem(10, false);
603 /// assert_eq!(bv.none(), true);
606 /// assert_eq!(bv.none(), false);
608 pub fn none(&self) -> bool {
609 self.blocks().all(|w| w == 0)
612 /// Returns `true` if any bit is 1.
617 /// use std::collections::Bitv;
619 /// let mut bv = Bitv::from_elem(10, false);
620 /// assert_eq!(bv.any(), false);
623 /// assert_eq!(bv.any(), true);
626 pub fn any(&self) -> bool {
630 /// Organises the bits into bytes, such that the first bit in the
631 /// `Bitv` becomes the high-order bit of the first byte. If the
632 /// size of the `Bitv` is not a multiple of eight then trailing bits
633 /// will be filled-in with `false`.
638 /// use std::collections::Bitv;
640 /// let mut bv = Bitv::from_elem(3, true);
641 /// bv.set(1, false);
643 /// assert_eq!(bv.to_bytes(), vec!(0b10100000));
645 /// let mut bv = Bitv::from_elem(9, false);
649 /// assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000));
651 pub fn to_bytes(&self) -> Vec<u8> {
652 fn bit(bitv: &Bitv, byte: usize, bit: usize) -> u8 {
653 let offset = byte * 8 + bit;
654 if offset >= bitv.nbits {
657 (bitv[offset] as u8) << (7 - bit)
661 let len = self.nbits/8 +
662 if self.nbits % 8 == 0 { 0 } else { 1 };
675 /// Compares a `Bitv` to a slice of `bool`s.
676 /// Both the `Bitv` and slice must have the same length.
680 /// Panics if the `Bitv` and slice are of different length.
685 /// use std::collections::Bitv;
687 /// let bv = Bitv::from_bytes(&[0b10100000]);
689 /// assert!(bv.eq_vec(&[true, false, true, false,
690 /// false, false, false, false]));
692 pub fn eq_vec(&self, v: &[bool]) -> bool {
693 assert_eq!(self.nbits, v.len());
694 iter::order::eq(self.iter(), v.iter().cloned())
697 /// Shortens a `Bitv`, dropping excess elements.
699 /// If `len` is greater than the vector's current length, this has no
705 /// use std::collections::Bitv;
707 /// let mut bv = Bitv::from_bytes(&[0b01001011]);
709 /// assert!(bv.eq_vec(&[false, true]));
711 #[stable(feature = "rust1", since = "1.0.0")]
712 pub fn truncate(&mut self, len: usize) {
713 if len < self.len() {
716 self.storage.truncate(blocks_for_bits(len));
717 self.fix_last_block();
721 /// Reserves capacity for at least `additional` more bits to be inserted in the given
722 /// `Bitv`. The collection may reserve more space to avoid frequent reallocations.
726 /// Panics if the new capacity overflows `usize`.
731 /// use std::collections::Bitv;
733 /// let mut bv = Bitv::from_elem(3, false);
735 /// assert_eq!(bv.len(), 3);
736 /// assert!(bv.capacity() >= 13);
738 #[stable(feature = "rust1", since = "1.0.0")]
739 pub fn reserve(&mut self, additional: usize) {
740 let desired_cap = self.len().checked_add(additional).expect("capacity overflow");
741 let storage_len = self.storage.len();
742 if desired_cap > self.capacity() {
743 self.storage.reserve(blocks_for_bits(desired_cap) - storage_len);
747 /// Reserves the minimum capacity for exactly `additional` more bits to be inserted in the
748 /// given `Bitv`. Does nothing if the capacity is already sufficient.
750 /// Note that the allocator may give the collection more space than it requests. Therefore
751 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
752 /// insertions are expected.
756 /// Panics if the new capacity overflows `usize`.
761 /// use std::collections::Bitv;
763 /// let mut bv = Bitv::from_elem(3, false);
765 /// assert_eq!(bv.len(), 3);
766 /// assert!(bv.capacity() >= 13);
768 #[stable(feature = "rust1", since = "1.0.0")]
769 pub fn reserve_exact(&mut self, additional: usize) {
770 let desired_cap = self.len().checked_add(additional).expect("capacity overflow");
771 let storage_len = self.storage.len();
772 if desired_cap > self.capacity() {
773 self.storage.reserve_exact(blocks_for_bits(desired_cap) - storage_len);
777 /// Returns the capacity in bits for this bit vector. Inserting any
778 /// element less than this amount will not trigger a resizing.
783 /// use std::collections::Bitv;
785 /// let mut bv = Bitv::new();
787 /// assert!(bv.capacity() >= 10);
790 #[stable(feature = "rust1", since = "1.0.0")]
791 pub fn capacity(&self) -> usize {
792 self.storage.capacity().checked_mul(u32::BITS).unwrap_or(usize::MAX)
795 /// Grows the `Bitv` in-place, adding `n` copies of `value` to the `Bitv`.
799 /// Panics if the new len overflows a `usize`.
804 /// use std::collections::Bitv;
806 /// let mut bv = Bitv::from_bytes(&[0b01001011]);
807 /// bv.grow(2, true);
808 /// assert_eq!(bv.len(), 10);
809 /// assert_eq!(bv.to_bytes(), vec!(0b01001011, 0b11000000));
811 pub fn grow(&mut self, n: usize, value: bool) {
812 // Note: we just bulk set all the bits in the last word in this fn in multiple places
813 // which is technically wrong if not all of these bits are to be used. However, at the end
814 // of this fn we call `fix_last_block` at the end of this fn, which should fix this.
816 let new_nbits = self.nbits.checked_add(n).expect("capacity overflow");
817 let new_nblocks = blocks_for_bits(new_nbits);
818 let full_value = if value { !0 } else { 0 };
820 // Correct the old tail word, setting or clearing formerly unused bits
821 let old_last_word = blocks_for_bits(self.nbits) - 1;
822 if self.nbits % u32::BITS > 0 {
823 let mask = mask_for_bits(self.nbits);
825 self.storage[old_last_word] |= !mask;
827 // Extra bits are already zero by invariant.
831 // Fill in words after the old tail word
832 let stop_idx = cmp::min(self.storage.len(), new_nblocks);
833 for idx in old_last_word + 1..stop_idx {
834 self.storage[idx] = full_value;
837 // Allocate new words, if needed
838 if new_nblocks > self.storage.len() {
839 let to_add = new_nblocks - self.storage.len();
840 self.storage.extend(repeat(full_value).take(to_add));
843 // Adjust internal bit count
844 self.nbits = new_nbits;
846 self.fix_last_block();
849 /// Removes the last bit from the Bitv, and returns it. Returns None if the Bitv is empty.
854 /// use std::collections::Bitv;
856 /// let mut bv = Bitv::from_bytes(&[0b01001001]);
857 /// assert_eq!(bv.pop(), Some(true));
858 /// assert_eq!(bv.pop(), Some(false));
859 /// assert_eq!(bv.len(), 6);
861 #[stable(feature = "rust1", since = "1.0.0")]
862 pub fn pop(&mut self) -> Option<bool> {
866 let i = self.nbits - 1;
871 if self.nbits % u32::BITS == 0 {
879 /// Pushes a `bool` onto the end.
884 /// use std::collections::Bitv;
886 /// let mut bv = Bitv::new();
889 /// assert!(bv.eq_vec(&[true, false]));
891 #[stable(feature = "rust1", since = "1.0.0")]
892 pub fn push(&mut self, elem: bool) {
893 if self.nbits % u32::BITS == 0 {
894 self.storage.push(0);
896 let insert_pos = self.nbits;
897 self.nbits = self.nbits.checked_add(1).expect("Capacity overflow");
898 self.set(insert_pos, elem);
901 /// Return the total number of bits in this vector
903 #[stable(feature = "rust1", since = "1.0.0")]
904 pub fn len(&self) -> usize { self.nbits }
906 /// Returns true if there are no bits in this vector
908 #[stable(feature = "rust1", since = "1.0.0")]
909 pub fn is_empty(&self) -> bool { self.len() == 0 }
911 /// Clears all bits in this vector.
913 #[stable(feature = "rust1", since = "1.0.0")]
914 pub fn clear(&mut self) {
915 for w in &mut self.storage { *w = 0u32; }
919 #[stable(feature = "rust1", since = "1.0.0")]
920 impl Default for Bitv {
922 fn default() -> Bitv { Bitv::new() }
925 #[stable(feature = "rust1", since = "1.0.0")]
926 impl FromIterator<bool> for Bitv {
927 fn from_iter<I:Iterator<Item=bool>>(iterator: I) -> Bitv {
928 let mut ret = Bitv::new();
929 ret.extend(iterator);
934 #[stable(feature = "rust1", since = "1.0.0")]
935 impl Extend<bool> for Bitv {
937 fn extend<I: Iterator<Item=bool>>(&mut self, iterator: I) {
938 let (min, _) = iterator.size_hint();
940 for element in iterator {
946 #[stable(feature = "rust1", since = "1.0.0")]
947 impl Clone for Bitv {
949 fn clone(&self) -> Bitv {
950 Bitv { storage: self.storage.clone(), nbits: self.nbits }
954 fn clone_from(&mut self, source: &Bitv) {
955 self.nbits = source.nbits;
956 self.storage.clone_from(&source.storage);
960 #[stable(feature = "rust1", since = "1.0.0")]
961 impl PartialOrd for Bitv {
963 fn partial_cmp(&self, other: &Bitv) -> Option<Ordering> {
964 iter::order::partial_cmp(self.iter(), other.iter())
968 #[stable(feature = "rust1", since = "1.0.0")]
971 fn cmp(&self, other: &Bitv) -> Ordering {
972 iter::order::cmp(self.iter(), other.iter())
976 #[stable(feature = "rust1", since = "1.0.0")]
977 impl fmt::Debug for Bitv {
978 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
980 try!(write!(fmt, "{}", if bit { 1u32 } else { 0u32 }));
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for Bitv {
988 fn hash(&self, state: &mut S) {
989 self.nbits.hash(state);
990 for elem in self.blocks() {
996 #[stable(feature = "rust1", since = "1.0.0")]
997 impl cmp::PartialEq for Bitv {
999 fn eq(&self, other: &Bitv) -> bool {
1000 if self.nbits != other.nbits {
1003 self.blocks().zip(other.blocks()).all(|(w1, w2)| w1 == w2)
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 impl cmp::Eq for Bitv {}
1010 /// An iterator for `Bitv`.
1011 #[stable(feature = "rust1", since = "1.0.0")]
1013 pub struct Iter<'a> {
1019 #[stable(feature = "rust1", since = "1.0.0")]
1020 impl<'a> Iterator for Iter<'a> {
1024 fn next(&mut self) -> Option<bool> {
1025 if self.next_idx != self.end_idx {
1026 let idx = self.next_idx;
1028 Some(self.bitv[idx])
1034 fn size_hint(&self) -> (usize, Option<usize>) {
1035 let rem = self.end_idx - self.next_idx;
1040 #[stable(feature = "rust1", since = "1.0.0")]
1041 impl<'a> DoubleEndedIterator for Iter<'a> {
1043 fn next_back(&mut self) -> Option<bool> {
1044 if self.next_idx != self.end_idx {
1046 Some(self.bitv[self.end_idx])
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 impl<'a> ExactSizeIterator for Iter<'a> {}
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 impl<'a> RandomAccessIterator for Iter<'a> {
1059 fn indexable(&self) -> usize {
1060 self.end_idx - self.next_idx
1064 fn idx(&mut self, index: usize) -> Option<bool> {
1065 if index >= self.indexable() {
1068 Some(self.bitv[index])
1073 #[stable(feature = "rust1", since = "1.0.0")]
1074 impl<'a> IntoIterator for &'a Bitv {
1076 type IntoIter = Iter<'a>;
1078 fn into_iter(self) -> Iter<'a> {
1083 /// An implementation of a set using a bit vector as an underlying
1084 /// representation for holding unsigned numerical elements.
1086 /// It should also be noted that the amount of storage necessary for holding a
1087 /// set of objects is proportional to the maximum of the objects when viewed
1093 /// use std::collections::{BitvSet, Bitv};
1095 /// // It's a regular set
1096 /// let mut s = BitvSet::new();
1103 /// if !s.contains(&7) {
1104 /// println!("There is no 7");
1107 /// // Can initialize from a `Bitv`
1108 /// let other = BitvSet::from_bitv(Bitv::from_bytes(&[0b11010000]));
1110 /// s.union_with(&other);
1112 /// // Print 0, 1, 3 in some order
1113 /// for x in s.iter() {
1114 /// println!("{}", x);
1117 /// // Can convert back to a `Bitv`
1118 /// let bv: Bitv = s.into_bitv();
1122 #[unstable(feature = "collections",
1123 reason = "RFC 509")]
1124 pub struct BitvSet {
1128 #[stable(feature = "rust1", since = "1.0.0")]
1129 impl Default for BitvSet {
1131 fn default() -> BitvSet { BitvSet::new() }
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 impl FromIterator<usize> for BitvSet {
1136 fn from_iter<I:Iterator<Item=usize>>(iterator: I) -> BitvSet {
1137 let mut ret = BitvSet::new();
1138 ret.extend(iterator);
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 impl Extend<usize> for BitvSet {
1146 fn extend<I: Iterator<Item=usize>>(&mut self, iterator: I) {
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 impl PartialOrd for BitvSet {
1156 fn partial_cmp(&self, other: &BitvSet) -> Option<Ordering> {
1157 let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1158 iter::order::partial_cmp(a_iter, b_iter)
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 impl Ord for BitvSet {
1165 fn cmp(&self, other: &BitvSet) -> Ordering {
1166 let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1167 iter::order::cmp(a_iter, b_iter)
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl cmp::PartialEq for BitvSet {
1174 fn eq(&self, other: &BitvSet) -> bool {
1175 let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1176 iter::order::eq(a_iter, b_iter)
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 impl cmp::Eq for BitvSet {}
1184 /// Creates a new empty `BitvSet`.
1189 /// use std::collections::BitvSet;
1191 /// let mut s = BitvSet::new();
1194 #[stable(feature = "rust1", since = "1.0.0")]
1195 pub fn new() -> BitvSet {
1196 BitvSet { bitv: Bitv::new() }
1199 /// Creates a new `BitvSet` with initially no contents, able to
1200 /// hold `nbits` elements without resizing.
1205 /// use std::collections::BitvSet;
1207 /// let mut s = BitvSet::with_capacity(100);
1208 /// assert!(s.capacity() >= 100);
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 pub fn with_capacity(nbits: usize) -> BitvSet {
1213 let bitv = Bitv::from_elem(nbits, false);
1214 BitvSet::from_bitv(bitv)
1217 /// Creates a new `BitvSet` from the given bit vector.
1222 /// use std::collections::{Bitv, BitvSet};
1224 /// let bv = Bitv::from_bytes(&[0b01100000]);
1225 /// let s = BitvSet::from_bitv(bv);
1227 /// // Print 1, 2 in arbitrary order
1228 /// for x in s.iter() {
1229 /// println!("{}", x);
1233 pub fn from_bitv(bitv: Bitv) -> BitvSet {
1234 BitvSet { bitv: bitv }
1237 /// Returns the capacity in bits for this bit vector. Inserting any
1238 /// element less than this amount will not trigger a resizing.
1243 /// use std::collections::BitvSet;
1245 /// let mut s = BitvSet::with_capacity(100);
1246 /// assert!(s.capacity() >= 100);
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 pub fn capacity(&self) -> usize {
1251 self.bitv.capacity()
1254 /// Reserves capacity for the given `BitvSet` to contain `len` distinct elements. In the case
1255 /// of `BitvSet` this means reallocations will not occur as long as all inserted elements
1256 /// are less than `len`.
1258 /// The collection may reserve more space to avoid frequent reallocations.
1264 /// use std::collections::BitvSet;
1266 /// let mut s = BitvSet::new();
1267 /// s.reserve_len(10);
1268 /// assert!(s.capacity() >= 10);
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 pub fn reserve_len(&mut self, len: usize) {
1272 let cur_len = self.bitv.len();
1274 self.bitv.reserve(len - cur_len);
1278 /// Reserves the minimum capacity for the given `BitvSet` to contain `len` distinct elements.
1279 /// In the case of `BitvSet` this means reallocations will not occur as long as all inserted
1280 /// elements are less than `len`.
1282 /// Note that the allocator may give the collection more space than it requests. Therefore
1283 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve_len` if future
1284 /// insertions are expected.
1290 /// use std::collections::BitvSet;
1292 /// let mut s = BitvSet::new();
1293 /// s.reserve_len_exact(10);
1294 /// assert!(s.capacity() >= 10);
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 pub fn reserve_len_exact(&mut self, len: usize) {
1298 let cur_len = self.bitv.len();
1300 self.bitv.reserve_exact(len - cur_len);
1305 /// Consumes this set to return the underlying bit vector.
1310 /// use std::collections::BitvSet;
1312 /// let mut s = BitvSet::new();
1316 /// let bv = s.into_bitv();
1321 pub fn into_bitv(self) -> Bitv {
1325 /// Returns a reference to the underlying bit vector.
1330 /// use std::collections::BitvSet;
1332 /// let mut s = BitvSet::new();
1335 /// let bv = s.get_ref();
1336 /// assert_eq!(bv[0], true);
1339 pub fn get_ref(&self) -> &Bitv {
1344 fn other_op<F>(&mut self, other: &BitvSet, mut f: F) where F: FnMut(u32, u32) -> u32 {
1346 let self_bitv = &mut self.bitv;
1347 let other_bitv = &other.bitv;
1349 let self_len = self_bitv.len();
1350 let other_len = other_bitv.len();
1352 // Expand the vector if necessary
1353 if self_len < other_len {
1354 self_bitv.grow(other_len - self_len, false);
1357 // virtually pad other with 0's for equal lengths
1359 let (_, result) = match_words(self_bitv, other_bitv);
1363 // Apply values found in other
1364 for (i, w) in other_words {
1365 let old = self_bitv.storage[i];
1366 let new = f(old, w);
1367 self_bitv.storage[i] = new;
1371 /// Truncates the underlying vector to the least length required.
1376 /// use std::collections::BitvSet;
1378 /// let mut s = BitvSet::new();
1379 /// s.insert(32183231);
1380 /// s.remove(&32183231);
1382 /// // Internal storage will probably be bigger than necessary
1383 /// println!("old capacity: {}", s.capacity());
1385 /// // Now should be smaller
1386 /// s.shrink_to_fit();
1387 /// println!("new capacity: {}", s.capacity());
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 pub fn shrink_to_fit(&mut self) {
1392 let bitv = &mut self.bitv;
1393 // Obtain original length
1394 let old_len = bitv.storage.len();
1395 // Obtain coarse trailing zero length
1396 let n = bitv.storage.iter().rev().take_while(|&&n| n == 0).count();
1398 let trunc_len = cmp::max(old_len - n, 1);
1399 bitv.storage.truncate(trunc_len);
1400 bitv.nbits = trunc_len * u32::BITS;
1403 /// Iterator over each u32 stored in the `BitvSet`.
1408 /// use std::collections::{Bitv, BitvSet};
1410 /// let s = BitvSet::from_bitv(Bitv::from_bytes(&[0b01001010]));
1412 /// // Print 1, 4, 6 in arbitrary order
1413 /// for x in s.iter() {
1414 /// println!("{}", x);
1418 #[stable(feature = "rust1", since = "1.0.0")]
1419 pub fn iter(&self) -> bitv_set::Iter {
1420 SetIter {set: self, next_idx: 0}
1423 /// Iterator over each u32 stored in `self` union `other`.
1424 /// See [union_with](#method.union_with) for an efficient in-place version.
1429 /// use std::collections::{Bitv, BitvSet};
1431 /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
1432 /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
1434 /// // Print 0, 1, 2, 4 in arbitrary order
1435 /// for x in a.union(&b) {
1436 /// println!("{}", x);
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 pub fn union<'a>(&'a self, other: &'a BitvSet) -> Union<'a> {
1442 fn or(w1: u32, w2: u32) -> u32 { w1 | w2 }
1444 Union(TwoBitPositions {
1453 /// Iterator over each usize stored in `self` intersect `other`.
1454 /// See [intersect_with](#method.intersect_with) for an efficient in-place version.
1459 /// use std::collections::{Bitv, BitvSet};
1461 /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
1462 /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
1465 /// for x in a.intersection(&b) {
1466 /// println!("{}", x);
1470 #[stable(feature = "rust1", since = "1.0.0")]
1471 pub fn intersection<'a>(&'a self, other: &'a BitvSet) -> Intersection<'a> {
1472 fn bitand(w1: u32, w2: u32) -> u32 { w1 & w2 }
1473 let min = cmp::min(self.bitv.len(), other.bitv.len());
1474 Intersection(TwoBitPositions {
1483 /// Iterator over each usize stored in the `self` setminus `other`.
1484 /// See [difference_with](#method.difference_with) for an efficient in-place version.
1489 /// use std::collections::{BitvSet, Bitv};
1491 /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
1492 /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
1494 /// // Print 1, 4 in arbitrary order
1495 /// for x in a.difference(&b) {
1496 /// println!("{}", x);
1499 /// // Note that difference is not symmetric,
1500 /// // and `b - a` means something else.
1501 /// // This prints 0
1502 /// for x in b.difference(&a) {
1503 /// println!("{}", x);
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 pub fn difference<'a>(&'a self, other: &'a BitvSet) -> Difference<'a> {
1509 fn diff(w1: u32, w2: u32) -> u32 { w1 & !w2 }
1511 Difference(TwoBitPositions {
1520 /// Iterator over each u32 stored in the symmetric difference of `self` and `other`.
1521 /// See [symmetric_difference_with](#method.symmetric_difference_with) for
1522 /// an efficient in-place version.
1527 /// use std::collections::{BitvSet, Bitv};
1529 /// let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101000]));
1530 /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100000]));
1532 /// // Print 0, 1, 4 in arbitrary order
1533 /// for x in a.symmetric_difference(&b) {
1534 /// println!("{}", x);
1538 #[stable(feature = "rust1", since = "1.0.0")]
1539 pub fn symmetric_difference<'a>(&'a self, other: &'a BitvSet) -> SymmetricDifference<'a> {
1540 fn bitxor(w1: u32, w2: u32) -> u32 { w1 ^ w2 }
1542 SymmetricDifference(TwoBitPositions {
1551 /// Unions in-place with the specified other bit vector.
1556 /// use std::collections::{BitvSet, Bitv};
1558 /// let a = 0b01101000;
1559 /// let b = 0b10100000;
1560 /// let res = 0b11101000;
1562 /// let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
1563 /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
1564 /// let res = BitvSet::from_bitv(Bitv::from_bytes(&[res]));
1566 /// a.union_with(&b);
1567 /// assert_eq!(a, res);
1570 pub fn union_with(&mut self, other: &BitvSet) {
1571 self.other_op(other, |w1, w2| w1 | w2);
1574 /// Intersects in-place with the specified other bit vector.
1579 /// use std::collections::{BitvSet, Bitv};
1581 /// let a = 0b01101000;
1582 /// let b = 0b10100000;
1583 /// let res = 0b00100000;
1585 /// let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
1586 /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
1587 /// let res = BitvSet::from_bitv(Bitv::from_bytes(&[res]));
1589 /// a.intersect_with(&b);
1590 /// assert_eq!(a, res);
1593 pub fn intersect_with(&mut self, other: &BitvSet) {
1594 self.other_op(other, |w1, w2| w1 & w2);
1597 /// Makes this bit vector the difference with the specified other bit vector
1603 /// use std::collections::{BitvSet, Bitv};
1605 /// let a = 0b01101000;
1606 /// let b = 0b10100000;
1607 /// let a_b = 0b01001000; // a - b
1608 /// let b_a = 0b10000000; // b - a
1610 /// let mut bva = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
1611 /// let bvb = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
1612 /// let bva_b = BitvSet::from_bitv(Bitv::from_bytes(&[a_b]));
1613 /// let bvb_a = BitvSet::from_bitv(Bitv::from_bytes(&[b_a]));
1615 /// bva.difference_with(&bvb);
1616 /// assert_eq!(bva, bva_b);
1618 /// let bva = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
1619 /// let mut bvb = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
1621 /// bvb.difference_with(&bva);
1622 /// assert_eq!(bvb, bvb_a);
1625 pub fn difference_with(&mut self, other: &BitvSet) {
1626 self.other_op(other, |w1, w2| w1 & !w2);
1629 /// Makes this bit vector the symmetric difference with the specified other
1630 /// bit vector in-place.
1635 /// use std::collections::{BitvSet, Bitv};
1637 /// let a = 0b01101000;
1638 /// let b = 0b10100000;
1639 /// let res = 0b11001000;
1641 /// let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[a]));
1642 /// let b = BitvSet::from_bitv(Bitv::from_bytes(&[b]));
1643 /// let res = BitvSet::from_bitv(Bitv::from_bytes(&[res]));
1645 /// a.symmetric_difference_with(&b);
1646 /// assert_eq!(a, res);
1649 pub fn symmetric_difference_with(&mut self, other: &BitvSet) {
1650 self.other_op(other, |w1, w2| w1 ^ w2);
1653 /// Return the number of set bits in this set.
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 pub fn len(&self) -> usize {
1657 self.bitv.blocks().fold(0, |acc, n| acc + n.count_ones())
1660 /// Returns whether there are no bits set in this set
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 pub fn is_empty(&self) -> bool {
1667 /// Clears all bits in this set
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 pub fn clear(&mut self) {
1674 /// Returns `true` if this set contains the specified integer.
1676 #[stable(feature = "rust1", since = "1.0.0")]
1677 pub fn contains(&self, value: &usize) -> bool {
1678 let bitv = &self.bitv;
1679 *value < bitv.nbits && bitv[*value]
1682 /// Returns `true` if the set has no elements in common with `other`.
1683 /// This is equivalent to checking for an empty intersection.
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 pub fn is_disjoint(&self, other: &BitvSet) -> bool {
1687 self.intersection(other).next().is_none()
1690 /// Returns `true` if the set is a subset of another.
1692 #[stable(feature = "rust1", since = "1.0.0")]
1693 pub fn is_subset(&self, other: &BitvSet) -> bool {
1694 let self_bitv = &self.bitv;
1695 let other_bitv = &other.bitv;
1696 let other_blocks = blocks_for_bits(other_bitv.len());
1698 // Check that `self` intersect `other` is self
1699 self_bitv.blocks().zip(other_bitv.blocks()).all(|(w1, w2)| w1 & w2 == w1) &&
1700 // Make sure if `self` has any more blocks than `other`, they're all 0
1701 self_bitv.blocks().skip(other_blocks).all(|w| w == 0)
1704 /// Returns `true` if the set is a superset of another.
1706 #[stable(feature = "rust1", since = "1.0.0")]
1707 pub fn is_superset(&self, other: &BitvSet) -> bool {
1708 other.is_subset(self)
1711 /// Adds a value to the set. Returns `true` if the value was not already
1712 /// present in the set.
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 pub fn insert(&mut self, value: usize) -> bool {
1715 if self.contains(&value) {
1719 // Ensure we have enough space to hold the new element
1720 let len = self.bitv.len();
1722 self.bitv.grow(value - len + 1, false)
1725 self.bitv.set(value, true);
1729 /// Removes a value from the set. Returns `true` if the value was
1730 /// present in the set.
1731 #[stable(feature = "rust1", since = "1.0.0")]
1732 pub fn remove(&mut self, value: &usize) -> bool {
1733 if !self.contains(value) {
1737 self.bitv.set(*value, false);
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 impl fmt::Debug for BitvSet {
1745 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1746 try!(write!(fmt, "BitvSet {{"));
1747 let mut first = true;
1750 try!(write!(fmt, ", "));
1752 try!(write!(fmt, "{:?}", n));
1759 impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for BitvSet {
1760 fn hash(&self, state: &mut S) {
1767 /// An iterator for `BitvSet`.
1769 #[stable(feature = "rust1", since = "1.0.0")]
1770 pub struct SetIter<'a> {
1775 /// An iterator combining two `BitvSet` iterators.
1777 struct TwoBitPositions<'a> {
1780 merge: fn(u32, u32) -> u32,
1785 #[stable(feature = "rust1", since = "1.0.0")]
1786 pub struct Union<'a>(TwoBitPositions<'a>);
1787 #[stable(feature = "rust1", since = "1.0.0")]
1788 pub struct Intersection<'a>(Take<TwoBitPositions<'a>>);
1789 #[stable(feature = "rust1", since = "1.0.0")]
1790 pub struct Difference<'a>(TwoBitPositions<'a>);
1791 #[stable(feature = "rust1", since = "1.0.0")]
1792 pub struct SymmetricDifference<'a>(TwoBitPositions<'a>);
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 impl<'a> Iterator for SetIter<'a> {
1798 fn next(&mut self) -> Option<usize> {
1799 while self.next_idx < self.set.bitv.len() {
1800 let idx = self.next_idx;
1803 if self.set.contains(&idx) {
1812 fn size_hint(&self) -> (usize, Option<usize>) {
1813 (0, Some(self.set.bitv.len() - self.next_idx))
1817 #[stable(feature = "rust1", since = "1.0.0")]
1818 impl<'a> Iterator for TwoBitPositions<'a> {
1821 fn next(&mut self) -> Option<usize> {
1822 while self.next_idx < self.set.bitv.len() ||
1823 self.next_idx < self.other.bitv.len() {
1824 let bit_idx = self.next_idx % u32::BITS;
1826 let s_bitv = &self.set.bitv;
1827 let o_bitv = &self.other.bitv;
1828 // Merging the two words is a bit of an awkward dance since
1829 // one Bitv might be longer than the other
1830 let word_idx = self.next_idx / u32::BITS;
1831 let w1 = if word_idx < s_bitv.storage.len() {
1832 s_bitv.storage[word_idx]
1834 let w2 = if word_idx < o_bitv.storage.len() {
1835 o_bitv.storage[word_idx]
1837 self.current_word = (self.merge)(w1, w2);
1841 if self.current_word & (1 << bit_idx) != 0 {
1842 return Some(self.next_idx - 1);
1849 fn size_hint(&self) -> (usize, Option<usize>) {
1850 let cap = cmp::max(self.set.bitv.len(), self.other.bitv.len());
1851 (0, Some(cap - self.next_idx))
1855 #[stable(feature = "rust1", since = "1.0.0")]
1856 impl<'a> Iterator for Union<'a> {
1859 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
1860 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
1863 #[stable(feature = "rust1", since = "1.0.0")]
1864 impl<'a> Iterator for Intersection<'a> {
1867 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
1868 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
1871 #[stable(feature = "rust1", since = "1.0.0")]
1872 impl<'a> Iterator for Difference<'a> {
1875 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
1876 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
1879 #[stable(feature = "rust1", since = "1.0.0")]
1880 impl<'a> Iterator for SymmetricDifference<'a> {
1883 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
1884 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
1887 #[stable(feature = "rust1", since = "1.0.0")]
1888 impl<'a> IntoIterator for &'a BitvSet {
1890 type IntoIter = SetIter<'a>;
1892 fn into_iter(self) -> SetIter<'a> {
1906 let zerolen = Bitv::new();
1907 assert_eq!(format!("{:?}", zerolen), "");
1909 let eightbits = Bitv::from_elem(8, false);
1910 assert_eq!(format!("{:?}", eightbits), "00000000")
1914 fn test_0_elements() {
1915 let act = Bitv::new();
1916 let exp = Vec::new();
1917 assert!(act.eq_vec(&exp));
1918 assert!(act.none() && act.all());
1922 fn test_1_element() {
1923 let mut act = Bitv::from_elem(1, false);
1924 assert!(act.eq_vec(&[false]));
1925 assert!(act.none() && !act.all());
1926 act = Bitv::from_elem(1, true);
1927 assert!(act.eq_vec(&[true]));
1928 assert!(!act.none() && act.all());
1932 fn test_2_elements() {
1933 let mut b = Bitv::from_elem(2, false);
1936 assert_eq!(format!("{:?}", b), "10");
1937 assert!(!b.none() && !b.all());
1941 fn test_10_elements() {
1945 act = Bitv::from_elem(10, false);
1946 assert!((act.eq_vec(
1947 &[false, false, false, false, false, false, false, false, false, false])));
1948 assert!(act.none() && !act.all());
1951 act = Bitv::from_elem(10, true);
1952 assert!((act.eq_vec(&[true, true, true, true, true, true, true, true, true, true])));
1953 assert!(!act.none() && act.all());
1956 act = Bitv::from_elem(10, false);
1962 assert!((act.eq_vec(&[true, true, true, true, true, false, false, false, false, false])));
1963 assert!(!act.none() && !act.all());
1966 act = Bitv::from_elem(10, false);
1972 assert!((act.eq_vec(&[false, false, false, false, false, true, true, true, true, true])));
1973 assert!(!act.none() && !act.all());
1976 act = Bitv::from_elem(10, false);
1981 assert!((act.eq_vec(&[true, false, false, true, false, false, true, false, false, true])));
1982 assert!(!act.none() && !act.all());
1986 fn test_31_elements() {
1990 act = Bitv::from_elem(31, false);
1992 &[false, false, false, false, false, false, false, false, false, false, false,
1993 false, false, false, false, false, false, false, false, false, false, false,
1994 false, false, false, false, false, false, false, false, false]));
1995 assert!(act.none() && !act.all());
1998 act = Bitv::from_elem(31, true);
2000 &[true, true, true, true, true, true, true, true, true, true, true, true, true,
2001 true, true, true, true, true, true, true, true, true, true, true, true, true,
2002 true, true, true, true, true]));
2003 assert!(!act.none() && act.all());
2006 act = Bitv::from_elem(31, false);
2016 &[true, true, true, true, true, true, true, true, false, false, false, false, false,
2017 false, false, false, false, false, false, false, false, false, false, false,
2018 false, false, false, false, false, false, false]));
2019 assert!(!act.none() && !act.all());
2022 act = Bitv::from_elem(31, false);
2032 &[false, false, false, false, false, false, false, false, false, false, false,
2033 false, false, false, false, false, true, true, true, true, true, true, true, true,
2034 false, false, false, false, false, false, false]));
2035 assert!(!act.none() && !act.all());
2038 act = Bitv::from_elem(31, false);
2047 &[false, false, false, false, false, false, false, false, false, false, false,
2048 false, false, false, false, false, false, false, false, false, false, false,
2049 false, false, true, true, true, true, true, true, true]));
2050 assert!(!act.none() && !act.all());
2053 act = Bitv::from_elem(31, false);
2058 &[false, false, false, true, false, false, false, false, false, false, false, false,
2059 false, false, false, false, false, true, false, false, false, false, false, false,
2060 false, false, false, false, false, false, true]));
2061 assert!(!act.none() && !act.all());
2065 fn test_32_elements() {
2069 act = Bitv::from_elem(32, false);
2071 &[false, false, false, false, false, false, false, false, false, false, false,
2072 false, false, false, false, false, false, false, false, false, false, false,
2073 false, false, false, false, false, false, false, false, false, false]));
2074 assert!(act.none() && !act.all());
2077 act = Bitv::from_elem(32, true);
2079 &[true, true, true, true, true, true, true, true, true, true, true, true, true,
2080 true, true, true, true, true, true, true, true, true, true, true, true, true,
2081 true, true, true, true, true, true]));
2082 assert!(!act.none() && act.all());
2085 act = Bitv::from_elem(32, false);
2095 &[true, true, true, true, true, true, true, true, false, false, false, false, false,
2096 false, false, false, false, false, false, false, false, false, false, false,
2097 false, false, false, false, false, false, false, false]));
2098 assert!(!act.none() && !act.all());
2101 act = Bitv::from_elem(32, false);
2111 &[false, false, false, false, false, false, false, false, false, false, false,
2112 false, false, false, false, false, true, true, true, true, true, true, true, true,
2113 false, false, false, false, false, false, false, false]));
2114 assert!(!act.none() && !act.all());
2117 act = Bitv::from_elem(32, false);
2127 &[false, false, false, false, false, false, false, false, false, false, false,
2128 false, false, false, false, false, false, false, false, false, false, false,
2129 false, false, true, true, true, true, true, true, true, true]));
2130 assert!(!act.none() && !act.all());
2133 act = Bitv::from_elem(32, false);
2139 &[false, false, false, true, false, false, false, false, false, false, false, false,
2140 false, false, false, false, false, true, false, false, false, false, false, false,
2141 false, false, false, false, false, false, true, true]));
2142 assert!(!act.none() && !act.all());
2146 fn test_33_elements() {
2150 act = Bitv::from_elem(33, false);
2152 &[false, false, false, false, false, false, false, false, false, false, false,
2153 false, false, false, false, false, false, false, false, false, false, false,
2154 false, false, false, false, false, false, false, false, false, false, false]));
2155 assert!(act.none() && !act.all());
2158 act = Bitv::from_elem(33, true);
2160 &[true, true, true, true, true, true, true, true, true, true, true, true, true,
2161 true, true, true, true, true, true, true, true, true, true, true, true, true,
2162 true, true, true, true, true, true, true]));
2163 assert!(!act.none() && act.all());
2166 act = Bitv::from_elem(33, false);
2176 &[true, true, true, true, true, true, true, true, false, false, false, false, false,
2177 false, false, false, false, false, false, false, false, false, false, false,
2178 false, false, false, false, false, false, false, false, false]));
2179 assert!(!act.none() && !act.all());
2182 act = Bitv::from_elem(33, false);
2192 &[false, false, false, false, false, false, false, false, false, false, false,
2193 false, false, false, false, false, true, true, true, true, true, true, true, true,
2194 false, false, false, false, false, false, false, false, false]));
2195 assert!(!act.none() && !act.all());
2198 act = Bitv::from_elem(33, false);
2208 &[false, false, false, false, false, false, false, false, false, false, false,
2209 false, false, false, false, false, false, false, false, false, false, false,
2210 false, false, true, true, true, true, true, true, true, true, false]));
2211 assert!(!act.none() && !act.all());
2214 act = Bitv::from_elem(33, false);
2221 &[false, false, false, true, false, false, false, false, false, false, false, false,
2222 false, false, false, false, false, true, false, false, false, false, false, false,
2223 false, false, false, false, false, false, true, true, true]));
2224 assert!(!act.none() && !act.all());
2228 fn test_equal_differing_sizes() {
2229 let v0 = Bitv::from_elem(10, false);
2230 let v1 = Bitv::from_elem(11, false);
2235 fn test_equal_greatly_differing_sizes() {
2236 let v0 = Bitv::from_elem(10, false);
2237 let v1 = Bitv::from_elem(110, false);
2242 fn test_equal_sneaky_small() {
2243 let mut a = Bitv::from_elem(1, false);
2246 let mut b = Bitv::from_elem(1, true);
2253 fn test_equal_sneaky_big() {
2254 let mut a = Bitv::from_elem(100, false);
2259 let mut b = Bitv::from_elem(100, true);
2268 fn test_from_bytes() {
2269 let bitv = Bitv::from_bytes(&[0b10110110, 0b00000000, 0b11111111]);
2270 let str = concat!("10110110", "00000000", "11111111");
2271 assert_eq!(format!("{:?}", bitv), str);
2275 fn test_to_bytes() {
2276 let mut bv = Bitv::from_elem(3, true);
2278 assert_eq!(bv.to_bytes(), vec!(0b10100000));
2280 let mut bv = Bitv::from_elem(9, false);
2283 assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000));
2287 fn test_from_bools() {
2288 let bools = vec![true, false, true, true];
2289 let bitv: Bitv = bools.iter().map(|n| *n).collect();
2290 assert_eq!(format!("{:?}", bitv), "1011");
2294 fn test_to_bools() {
2295 let bools = vec![false, false, true, false, false, true, true, false];
2296 assert_eq!(Bitv::from_bytes(&[0b00100110]).iter().collect::<Vec<bool>>(), bools);
2300 fn test_bitv_iterator() {
2301 let bools = vec![true, false, true, true];
2302 let bitv: Bitv = bools.iter().map(|n| *n).collect();
2304 assert_eq!(bitv.iter().collect::<Vec<bool>>(), bools);
2306 let long: Vec<_> = (0i32..10000).map(|i| i % 2 == 0).collect();
2307 let bitv: Bitv = long.iter().map(|n| *n).collect();
2308 assert_eq!(bitv.iter().collect::<Vec<bool>>(), long)
2312 fn test_small_difference() {
2313 let mut b1 = Bitv::from_elem(3, false);
2314 let mut b2 = Bitv::from_elem(3, false);
2319 assert!(b1.difference(&b2));
2326 fn test_big_difference() {
2327 let mut b1 = Bitv::from_elem(100, false);
2328 let mut b2 = Bitv::from_elem(100, false);
2333 assert!(b1.difference(&b2));
2340 fn test_small_clear() {
2341 let mut b = Bitv::from_elem(14, true);
2342 assert!(!b.none() && b.all());
2344 assert!(b.none() && !b.all());
2348 fn test_big_clear() {
2349 let mut b = Bitv::from_elem(140, true);
2350 assert!(!b.none() && b.all());
2352 assert!(b.none() && !b.all());
2357 let mut a = Bitv::from_elem(5, false);
2358 let mut b = Bitv::from_elem(5, false);
2360 assert!(!(a < b) && !(b < a));
2366 assert!(!(a < b) && b < a);
2373 let mut a = Bitv::from_elem(5, false);
2374 let mut b = Bitv::from_elem(5, false);
2376 assert!(a <= b && a >= b);
2378 assert!(a > b && a >= b);
2379 assert!(b < a && b <= a);
2382 assert!(b > a && b >= a);
2383 assert!(a < b && a <= b);
2388 fn test_small_bitv_tests() {
2389 let v = Bitv::from_bytes(&[0]);
2394 let v = Bitv::from_bytes(&[0b00010100]);
2399 let v = Bitv::from_bytes(&[0xFF]);
2406 fn test_big_bitv_tests() {
2407 let v = Bitv::from_bytes(&[ // 88 bits
2415 let v = Bitv::from_bytes(&[ // 88 bits
2416 0, 0, 0b00010100, 0,
2417 0, 0, 0, 0b00110100,
2423 let v = Bitv::from_bytes(&[ // 88 bits
2424 0xFF, 0xFF, 0xFF, 0xFF,
2425 0xFF, 0xFF, 0xFF, 0xFF,
2433 fn test_bitv_push_pop() {
2434 let mut s = Bitv::from_elem(5 * u32::BITS - 2, false);
2435 assert_eq!(s.len(), 5 * u32::BITS - 2);
2436 assert_eq!(s[5 * u32::BITS - 3], false);
2439 assert_eq!(s[5 * u32::BITS - 2], true);
2440 assert_eq!(s[5 * u32::BITS - 1], true);
2441 // Here the internal vector will need to be extended
2443 assert_eq!(s[5 * u32::BITS], false);
2445 assert_eq!(s[5 * u32::BITS + 1], false);
2446 assert_eq!(s.len(), 5 * u32::BITS + 2);
2448 assert_eq!(s.pop(), Some(false));
2449 assert_eq!(s.pop(), Some(false));
2450 assert_eq!(s.pop(), Some(true));
2451 assert_eq!(s.pop(), Some(true));
2452 assert_eq!(s.len(), 5 * u32::BITS - 2);
2456 fn test_bitv_truncate() {
2457 let mut s = Bitv::from_elem(5 * u32::BITS, true);
2459 assert_eq!(s, Bitv::from_elem(5 * u32::BITS, true));
2460 assert_eq!(s.len(), 5 * u32::BITS);
2461 s.truncate(4 * u32::BITS);
2462 assert_eq!(s, Bitv::from_elem(4 * u32::BITS, true));
2463 assert_eq!(s.len(), 4 * u32::BITS);
2464 // Truncating to a size > s.len() should be a noop
2465 s.truncate(5 * u32::BITS);
2466 assert_eq!(s, Bitv::from_elem(4 * u32::BITS, true));
2467 assert_eq!(s.len(), 4 * u32::BITS);
2468 s.truncate(3 * u32::BITS - 10);
2469 assert_eq!(s, Bitv::from_elem(3 * u32::BITS - 10, true));
2470 assert_eq!(s.len(), 3 * u32::BITS - 10);
2472 assert_eq!(s, Bitv::from_elem(0, true));
2473 assert_eq!(s.len(), 0);
2477 fn test_bitv_reserve() {
2478 let mut s = Bitv::from_elem(5 * u32::BITS, true);
2480 assert!(s.capacity() >= 5 * u32::BITS);
2481 s.reserve(2 * u32::BITS);
2482 assert!(s.capacity() >= 7 * u32::BITS);
2483 s.reserve(7 * u32::BITS);
2484 assert!(s.capacity() >= 12 * u32::BITS);
2485 s.reserve_exact(7 * u32::BITS);
2486 assert!(s.capacity() >= 12 * u32::BITS);
2487 s.reserve(7 * u32::BITS + 1);
2488 assert!(s.capacity() >= 12 * u32::BITS + 1);
2489 // Check that length hasn't changed
2490 assert_eq!(s.len(), 5 * u32::BITS);
2494 assert_eq!(s[5 * u32::BITS - 1], true);
2495 assert_eq!(s[5 * u32::BITS - 0], true);
2496 assert_eq!(s[5 * u32::BITS + 1], false);
2497 assert_eq!(s[5 * u32::BITS + 2], true);
2501 fn test_bitv_grow() {
2502 let mut bitv = Bitv::from_bytes(&[0b10110110, 0b00000000, 0b10101010]);
2503 bitv.grow(32, true);
2504 assert_eq!(bitv, Bitv::from_bytes(&[0b10110110, 0b00000000, 0b10101010,
2505 0xFF, 0xFF, 0xFF, 0xFF]));
2506 bitv.grow(64, false);
2507 assert_eq!(bitv, Bitv::from_bytes(&[0b10110110, 0b00000000, 0b10101010,
2508 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0]));
2509 bitv.grow(16, true);
2510 assert_eq!(bitv, Bitv::from_bytes(&[0b10110110, 0b00000000, 0b10101010,
2511 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]));
2515 fn test_bitv_extend() {
2516 let mut bitv = Bitv::from_bytes(&[0b10110110, 0b00000000, 0b11111111]);
2517 let ext = Bitv::from_bytes(&[0b01001001, 0b10010010, 0b10111101]);
2518 bitv.extend(ext.iter());
2519 assert_eq!(bitv, Bitv::from_bytes(&[0b10110110, 0b00000000, 0b11111111,
2520 0b01001001, 0b10010010, 0b10111101]));
2529 use std::prelude::v1::*;
2533 use test::{Bencher, black_box};
2537 static BENCH_BITS : usize = 1 << 14;
2539 fn rng() -> rand::IsaacRng {
2540 let seed: &[_] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
2541 rand::SeedableRng::from_seed(seed)
2545 fn bench_usize_small(b: &mut Bencher) {
2547 let mut bitv = 0 as usize;
2550 bitv |= 1 << ((r.next_u32() as usize) % u32::BITS);
2557 fn bench_bitv_set_big_fixed(b: &mut Bencher) {
2559 let mut bitv = Bitv::from_elem(BENCH_BITS, false);
2562 bitv.set((r.next_u32() as usize) % BENCH_BITS, true);
2569 fn bench_bitv_set_big_variable(b: &mut Bencher) {
2571 let mut bitv = Bitv::from_elem(BENCH_BITS, false);
2574 bitv.set((r.next_u32() as usize) % BENCH_BITS, r.gen());
2581 fn bench_bitv_set_small(b: &mut Bencher) {
2583 let mut bitv = Bitv::from_elem(u32::BITS, false);
2586 bitv.set((r.next_u32() as usize) % u32::BITS, true);
2593 fn bench_bitv_big_union(b: &mut Bencher) {
2594 let mut b1 = Bitv::from_elem(BENCH_BITS, false);
2595 let b2 = Bitv::from_elem(BENCH_BITS, false);
2602 fn bench_bitv_small_iter(b: &mut Bencher) {
2603 let bitv = Bitv::from_elem(u32::BITS, false);
2608 sum += pres as usize;
2616 fn bench_bitv_big_iter(b: &mut Bencher) {
2617 let bitv = Bitv::from_elem(BENCH_BITS, false);
2621 sum += pres as usize;
2637 use std::iter::range_step;
2639 use super::{Bitv, BitvSet};
2642 fn test_bitv_set_show() {
2643 let mut s = BitvSet::new();
2648 assert_eq!("BitvSet {1, 2, 10, 50}", format!("{:?}", s));
2652 fn test_bitv_set_from_usizes() {
2653 let usizes = vec![0, 2, 2, 3];
2654 let a: BitvSet = usizes.into_iter().collect();
2655 let mut b = BitvSet::new();
2663 fn test_bitv_set_iterator() {
2664 let usizes = vec![0, 2, 2, 3];
2665 let bitv: BitvSet = usizes.into_iter().collect();
2667 let idxs: Vec<_> = bitv.iter().collect();
2668 assert_eq!(idxs, vec![0, 2, 3]);
2670 let long: BitvSet = (0..10000).filter(|&n| n % 2 == 0).collect();
2671 let real: Vec<_> = range_step(0, 10000, 2).collect();
2673 let idxs: Vec<_> = long.iter().collect();
2674 assert_eq!(idxs, real);
2678 fn test_bitv_set_frombitv_init() {
2679 let bools = [true, false];
2680 let lengths = [10, 64, 100];
2682 for &l in &lengths {
2683 let bitset = BitvSet::from_bitv(Bitv::from_elem(l, b));
2684 assert_eq!(bitset.contains(&1), b);
2685 assert_eq!(bitset.contains(&(l-1)), b);
2686 assert!(!bitset.contains(&l));
2692 fn test_bitv_masking() {
2693 let b = Bitv::from_elem(140, true);
2694 let mut bs = BitvSet::from_bitv(b);
2695 assert!(bs.contains(&139));
2696 assert!(!bs.contains(&140));
2697 assert!(bs.insert(150));
2698 assert!(!bs.contains(&140));
2699 assert!(!bs.contains(&149));
2700 assert!(bs.contains(&150));
2701 assert!(!bs.contains(&151));
2705 fn test_bitv_set_basic() {
2706 let mut b = BitvSet::new();
2707 assert!(b.insert(3));
2708 assert!(!b.insert(3));
2709 assert!(b.contains(&3));
2710 assert!(b.insert(4));
2711 assert!(!b.insert(4));
2712 assert!(b.contains(&3));
2713 assert!(b.insert(400));
2714 assert!(!b.insert(400));
2715 assert!(b.contains(&400));
2716 assert_eq!(b.len(), 3);
2720 fn test_bitv_set_intersection() {
2721 let mut a = BitvSet::new();
2722 let mut b = BitvSet::new();
2724 assert!(a.insert(11));
2725 assert!(a.insert(1));
2726 assert!(a.insert(3));
2727 assert!(a.insert(77));
2728 assert!(a.insert(103));
2729 assert!(a.insert(5));
2731 assert!(b.insert(2));
2732 assert!(b.insert(11));
2733 assert!(b.insert(77));
2734 assert!(b.insert(5));
2735 assert!(b.insert(3));
2737 let expected = [3, 5, 11, 77];
2738 let actual: Vec<_> = a.intersection(&b).collect();
2739 assert_eq!(actual, expected);
2743 fn test_bitv_set_difference() {
2744 let mut a = BitvSet::new();
2745 let mut b = BitvSet::new();
2747 assert!(a.insert(1));
2748 assert!(a.insert(3));
2749 assert!(a.insert(5));
2750 assert!(a.insert(200));
2751 assert!(a.insert(500));
2753 assert!(b.insert(3));
2754 assert!(b.insert(200));
2756 let expected = [1, 5, 500];
2757 let actual: Vec<_> = a.difference(&b).collect();
2758 assert_eq!(actual, expected);
2762 fn test_bitv_set_symmetric_difference() {
2763 let mut a = BitvSet::new();
2764 let mut b = BitvSet::new();
2766 assert!(a.insert(1));
2767 assert!(a.insert(3));
2768 assert!(a.insert(5));
2769 assert!(a.insert(9));
2770 assert!(a.insert(11));
2772 assert!(b.insert(3));
2773 assert!(b.insert(9));
2774 assert!(b.insert(14));
2775 assert!(b.insert(220));
2777 let expected = [1, 5, 11, 14, 220];
2778 let actual: Vec<_> = a.symmetric_difference(&b).collect();
2779 assert_eq!(actual, expected);
2783 fn test_bitv_set_union() {
2784 let mut a = BitvSet::new();
2785 let mut b = BitvSet::new();
2786 assert!(a.insert(1));
2787 assert!(a.insert(3));
2788 assert!(a.insert(5));
2789 assert!(a.insert(9));
2790 assert!(a.insert(11));
2791 assert!(a.insert(160));
2792 assert!(a.insert(19));
2793 assert!(a.insert(24));
2794 assert!(a.insert(200));
2796 assert!(b.insert(1));
2797 assert!(b.insert(5));
2798 assert!(b.insert(9));
2799 assert!(b.insert(13));
2800 assert!(b.insert(19));
2802 let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160, 200];
2803 let actual: Vec<_> = a.union(&b).collect();
2804 assert_eq!(actual, expected);
2808 fn test_bitv_set_subset() {
2809 let mut set1 = BitvSet::new();
2810 let mut set2 = BitvSet::new();
2812 assert!(set1.is_subset(&set2)); // {} {}
2814 assert!(set1.is_subset(&set2)); // {} { 1 }
2816 assert!(set1.is_subset(&set2)); // {} { 1, 2 }
2818 assert!(set1.is_subset(&set2)); // { 2 } { 1, 2 }
2820 assert!(!set1.is_subset(&set2)); // { 2, 3 } { 1, 2 }
2822 assert!(set1.is_subset(&set2)); // { 2, 3 } { 1, 2, 3 }
2824 assert!(set1.is_subset(&set2)); // { 2, 3 } { 1, 2, 3, 4 }
2826 assert!(set1.is_subset(&set2)); // { 2, 3 } { 2, 3, 4 }
2828 assert!(!set1.is_subset(&set2)); // { 2, 3 } { 2, 4 }
2830 assert!(set1.is_subset(&set2)); // { 2 } { 2, 4 }
2834 fn test_bitv_set_is_disjoint() {
2835 let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2836 let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01000000]));
2837 let c = BitvSet::new();
2838 let d = BitvSet::from_bitv(Bitv::from_bytes(&[0b00110000]));
2840 assert!(!a.is_disjoint(&d));
2841 assert!(!d.is_disjoint(&a));
2843 assert!(a.is_disjoint(&b));
2844 assert!(a.is_disjoint(&c));
2845 assert!(b.is_disjoint(&a));
2846 assert!(b.is_disjoint(&c));
2847 assert!(c.is_disjoint(&a));
2848 assert!(c.is_disjoint(&b));
2852 fn test_bitv_set_union_with() {
2853 //a should grow to include larger elements
2854 let mut a = BitvSet::new();
2856 let mut b = BitvSet::new();
2858 let expected = BitvSet::from_bitv(Bitv::from_bytes(&[0b10000100]));
2860 assert_eq!(a, expected);
2863 let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2864 let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01100010]));
2868 assert_eq!(a.len(), 4);
2869 assert_eq!(b.len(), 4);
2873 fn test_bitv_set_intersect_with() {
2874 // Explicitly 0'ed bits
2875 let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2876 let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
2878 a.intersect_with(&b);
2879 b.intersect_with(&c);
2880 assert!(a.is_empty());
2881 assert!(b.is_empty());
2883 // Uninitialized bits should behave like 0's
2884 let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2885 let mut b = BitvSet::new();
2887 a.intersect_with(&b);
2888 b.intersect_with(&c);
2889 assert!(a.is_empty());
2890 assert!(b.is_empty());
2893 let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2894 let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01100010]));
2896 a.intersect_with(&b);
2897 b.intersect_with(&c);
2898 assert_eq!(a.len(), 2);
2899 assert_eq!(b.len(), 2);
2903 fn test_bitv_set_difference_with() {
2904 // Explicitly 0'ed bits
2905 let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
2906 let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2907 a.difference_with(&b);
2908 assert!(a.is_empty());
2910 // Uninitialized bits should behave like 0's
2911 let mut a = BitvSet::new();
2912 let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b11111111]));
2913 a.difference_with(&b);
2914 assert!(a.is_empty());
2917 let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2918 let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01100010]));
2920 a.difference_with(&b);
2921 b.difference_with(&c);
2922 assert_eq!(a.len(), 1);
2923 assert_eq!(b.len(), 1);
2927 fn test_bitv_set_symmetric_difference_with() {
2928 //a should grow to include larger elements
2929 let mut a = BitvSet::new();
2932 let mut b = BitvSet::new();
2935 let expected = BitvSet::from_bitv(Bitv::from_bytes(&[0b10000100]));
2936 a.symmetric_difference_with(&b);
2937 assert_eq!(a, expected);
2939 let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2940 let b = BitvSet::new();
2942 a.symmetric_difference_with(&b);
2946 let mut a = BitvSet::from_bitv(Bitv::from_bytes(&[0b11100010]));
2947 let mut b = BitvSet::from_bitv(Bitv::from_bytes(&[0b01101010]));
2949 a.symmetric_difference_with(&b);
2950 b.symmetric_difference_with(&c);
2951 assert_eq!(a.len(), 2);
2952 assert_eq!(b.len(), 2);
2956 fn test_bitv_set_eq() {
2957 let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2958 let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
2959 let c = BitvSet::new();
2970 fn test_bitv_set_cmp() {
2971 let a = BitvSet::from_bitv(Bitv::from_bytes(&[0b10100010]));
2972 let b = BitvSet::from_bitv(Bitv::from_bytes(&[0b00000000]));
2973 let c = BitvSet::new();
2975 assert_eq!(a.cmp(&b), Greater);
2976 assert_eq!(a.cmp(&c), Greater);
2977 assert_eq!(b.cmp(&a), Less);
2978 assert_eq!(b.cmp(&c), Equal);
2979 assert_eq!(c.cmp(&a), Less);
2980 assert_eq!(c.cmp(&b), Equal);
2984 fn test_bitv_remove() {
2985 let mut a = BitvSet::new();
2987 assert!(a.insert(1));
2988 assert!(a.remove(&1));
2990 assert!(a.insert(100));
2991 assert!(a.remove(&100));
2993 assert!(a.insert(1000));
2994 assert!(a.remove(&1000));
2999 fn test_bitv_clone() {
3000 let mut a = BitvSet::new();
3002 assert!(a.insert(1));
3003 assert!(a.insert(100));
3004 assert!(a.insert(1000));
3006 let mut b = a.clone();
3010 assert!(b.remove(&1));
3011 assert!(a.contains(&1));
3013 assert!(a.remove(&1000));
3014 assert!(b.contains(&1000));
3023 mod bitv_set_bench {
3024 use std::prelude::v1::*;
3028 use test::{Bencher, black_box};
3030 use super::{Bitv, BitvSet};
3032 static BENCH_BITS : usize = 1 << 14;
3034 fn rng() -> rand::IsaacRng {
3035 let seed: &[_] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
3036 rand::SeedableRng::from_seed(seed)
3040 fn bench_bitvset_small(b: &mut Bencher) {
3042 let mut bitv = BitvSet::new();
3045 bitv.insert((r.next_u32() as usize) % u32::BITS);
3052 fn bench_bitvset_big(b: &mut Bencher) {
3054 let mut bitv = BitvSet::new();
3057 bitv.insert((r.next_u32() as usize) % BENCH_BITS);
3064 fn bench_bitvset_iter(b: &mut Bencher) {
3065 let bitv = BitvSet::from_bitv(Bitv::from_fn(BENCH_BITS,
3066 |idx| {idx % 3 == 0}));
3070 sum += idx as usize;