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): BitVec and BitSet are very tightly coupled. Ideally (for
12 // maintenance), they should be in separate files/modules, with BitSet only
13 // using BitVec's public API. This will be hard for performance though, because
14 // `BitVec` 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-): `BitVec`'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) `BitSet` is tightly coupled with `BitVec`, so any changes you make in
29 // `BitVec` will need to be reflected in `BitSet`.
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 //! # #![feature(collections, core)]
42 //! use std::collections::{BitSet, BitVec};
43 //! use std::num::Float;
46 //! let max_prime = 10000;
48 //! // Store the primes as a BitSet
50 //! // Assume all numbers are prime to begin, and then we
51 //! // cross off non-primes progressively
52 //! let mut bv = BitVec::from_elem(max_prime, true);
54 //! // Neither 0 nor 1 are prime
58 //! for i in iter::range_inclusive(2, (max_prime as f64).sqrt() as usize) {
59 //! // if i is a prime
61 //! // Mark all multiples of i as non-prime (any multiples below i * i
62 //! // will have been marked as non-prime previously)
63 //! for j in iter::range_step(i * i, max_prime, i) { bv.set(j, false) }
66 //! BitSet::from_bit_vec(bv)
69 //! // Simple primality tests below our max bound
70 //! let print_primes = 20;
71 //! print!("The primes below {} are: ", print_primes);
72 //! for x in 0..print_primes {
73 //! if primes.contains(&x) {
79 //! // We can manipulate the internal BitVec
80 //! let num_primes = primes.get_ref().iter().filter(|x| *x).count();
81 //! println!("There are {} primes below {}", num_primes, max_prime);
86 use core::cmp::Ordering;
88 use core::default::Default;
91 use core::iter::RandomAccessIterator;
92 use core::iter::{Chain, Enumerate, Repeat, Skip, Take, repeat, Cloned};
93 use core::iter::{self, FromIterator, IntoIterator};
96 use core::{u8, u32, usize};
97 use bit_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 BitVec'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 BitVec, b: &'b BitVec) -> (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(0).enumerate().take(b_len).skip(a_len)),
122 b.blocks().enumerate().chain(iter::repeat(0).enumerate().take(0).skip(0)))
124 (a.blocks().enumerate().chain(iter::repeat(0).enumerate().take(0).skip(0)),
125 b.blocks().enumerate().chain(iter::repeat(0).enumerate().take(a_len).skip(b_len)))
129 static TRUE: bool = true;
130 static FALSE: bool = false;
132 /// The bitvector type.
137 /// # #![feature(collections)]
138 /// use std::collections::BitVec;
140 /// let mut bv = BitVec::from_elem(10, false);
142 /// // insert all primes less than 10
147 /// println!("{:?}", bv);
148 /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
150 /// // flip all values in bitvector, producing non-primes less than 10
152 /// println!("{:?}", bv);
153 /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
155 /// // reset bitvector to empty
157 /// println!("{:?}", bv);
158 /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
160 #[unstable(feature = "collections",
163 /// Internal representation of the bit vector
165 /// The number of valid bits in the internal representation
169 // FIXME(Gankro): NopeNopeNopeNopeNope (wait for IndexGet to be a thing)
170 impl Index<usize> for BitVec {
174 fn index(&self, i: usize) -> &bool {
175 if self.get(i).expect("index out of bounds") {
183 /// Computes how many blocks are needed to store that many bits
184 fn blocks_for_bits(bits: usize) -> usize {
185 // If we want 17 bits, dividing by 32 will produce 0. So we add 1 to make sure we
186 // reserve enough. But if we want exactly a multiple of 32, this will actually allocate
187 // one too many. So we need to check if that's the case. We can do that by computing if
188 // bitwise AND by `32 - 1` is 0. But LLVM should be able to optimize the semantically
189 // superior modulo operator on a power of two to this.
191 // Note that we can technically avoid this branch with the expression
192 // `(nbits + u32::BITS - 1) / 32::BITS`, but if nbits is almost usize::MAX this will overflow.
193 if bits % u32::BITS as usize == 0 {
194 bits / u32::BITS as usize
196 bits / u32::BITS as usize + 1
200 /// Computes the bitmask for the final word of the vector
201 fn mask_for_bits(bits: usize) -> u32 {
202 // Note especially that a perfect multiple of u32::BITS should mask all 1s.
203 !0 >> (u32::BITS as usize - bits % u32::BITS as usize) % u32::BITS as usize
207 /// Applies the given operation to the blocks of self and other, and sets
208 /// self to be the result. This relies on the caller not to corrupt the
211 fn process<F>(&mut self, other: &BitVec, mut op: F) -> bool where F: FnMut(u32, u32) -> u32 {
212 assert_eq!(self.len(), other.len());
213 // This could theoretically be a `debug_assert!`.
214 assert_eq!(self.storage.len(), other.storage.len());
215 let mut changed = false;
216 for (a, b) in self.blocks_mut().zip(other.blocks()) {
226 /// Iterator over mutable refs to the underlying blocks of data.
227 fn blocks_mut(&mut self) -> MutBlocks {
229 self.storage.iter_mut()
232 /// Iterator over the underlying blocks of data
233 fn blocks(&self) -> Blocks {
235 self.storage.iter().cloned()
238 /// An operation might screw up the unused bits in the last block of the
239 /// `BitVec`. As per (3), it's assumed to be all 0s. This method fixes it up.
240 fn fix_last_block(&mut self) {
241 let extra_bits = self.len() % u32::BITS as usize;
243 let mask = (1 << extra_bits) - 1;
244 let storage_len = self.storage.len();
245 self.storage[storage_len - 1] &= mask;
249 /// Creates an empty `BitVec`.
254 /// # #![feature(collections)]
255 /// use std::collections::BitVec;
256 /// let mut bv = BitVec::new();
258 #[stable(feature = "rust1", since = "1.0.0")]
259 pub fn new() -> BitVec {
260 BitVec { storage: Vec::new(), nbits: 0 }
263 /// Creates a `BitVec` that holds `nbits` elements, setting each element
269 /// # #![feature(collections)]
270 /// use std::collections::BitVec;
272 /// let mut bv = BitVec::from_elem(10, false);
273 /// assert_eq!(bv.len(), 10);
274 /// for x in bv.iter() {
275 /// assert_eq!(x, false);
278 pub fn from_elem(nbits: usize, bit: bool) -> BitVec {
279 let nblocks = blocks_for_bits(nbits);
280 let mut bit_vec = BitVec {
281 storage: repeat(if bit { !0 } else { 0 }).take(nblocks).collect(),
284 bit_vec.fix_last_block();
288 /// Constructs a new, empty `BitVec` with the specified capacity.
290 /// The bitvector will be able to hold at least `capacity` bits without
291 /// reallocating. If `capacity` is 0, it will not allocate.
293 /// It is important to note that this function does not specify the
294 /// *length* of the returned bitvector, but only the *capacity*.
295 #[stable(feature = "rust1", since = "1.0.0")]
296 pub fn with_capacity(nbits: usize) -> BitVec {
298 storage: Vec::with_capacity(blocks_for_bits(nbits)),
303 /// Transforms a byte-vector into a `BitVec`. Each byte becomes eight bits,
304 /// with the most significant bits of each byte coming first. Each
305 /// bit becomes `true` if equal to 1 or `false` if equal to 0.
310 /// # #![feature(collections)]
311 /// use std::collections::BitVec;
313 /// let bv = BitVec::from_bytes(&[0b10100000, 0b00010010]);
314 /// assert!(bv.eq_vec(&[true, false, true, false,
315 /// false, false, false, false,
316 /// false, false, false, true,
317 /// false, false, true, false]));
319 pub fn from_bytes(bytes: &[u8]) -> BitVec {
320 let len = bytes.len().checked_mul(u8::BITS as usize).expect("capacity overflow");
321 let mut bit_vec = BitVec::with_capacity(len);
322 let complete_words = bytes.len() / 4;
323 let extra_bytes = bytes.len() % 4;
327 for i in 0..complete_words {
328 bit_vec.storage.push(
329 ((reverse_bits(bytes[i * 4 + 0]) as u32) << 0) |
330 ((reverse_bits(bytes[i * 4 + 1]) as u32) << 8) |
331 ((reverse_bits(bytes[i * 4 + 2]) as u32) << 16) |
332 ((reverse_bits(bytes[i * 4 + 3]) as u32) << 24)
337 let mut last_word = 0;
338 for (i, &byte) in bytes[complete_words*4..].iter().enumerate() {
339 last_word |= (reverse_bits(byte) as u32) << (i * 8);
341 bit_vec.storage.push(last_word);
347 /// Creates a `BitVec` of the specified length where the value at each index
353 /// # #![feature(collections)]
354 /// use std::collections::BitVec;
356 /// let bv = BitVec::from_fn(5, |i| { i % 2 == 0 });
357 /// assert!(bv.eq_vec(&[true, false, true, false, true]));
359 pub fn from_fn<F>(len: usize, mut f: F) -> BitVec where F: FnMut(usize) -> bool {
360 let mut bit_vec = BitVec::from_elem(len, false);
362 bit_vec.set(i, f(i));
367 /// Retrieves the value at index `i`, or `None` if the index is out of bounds.
372 /// # #![feature(collections)]
373 /// use std::collections::BitVec;
375 /// let bv = BitVec::from_bytes(&[0b01100000]);
376 /// assert_eq!(bv.get(0), Some(false));
377 /// assert_eq!(bv.get(1), Some(true));
378 /// assert_eq!(bv.get(100), None);
380 /// // Can also use array indexing
381 /// assert_eq!(bv[1], true);
384 #[stable(feature = "rust1", since = "1.0.0")]
385 pub fn get(&self, i: usize) -> Option<bool> {
389 let w = i / u32::BITS as usize;
390 let b = i % u32::BITS as usize;
391 self.storage.get(w).map(|&block|
392 (block & (1 << b)) != 0
396 /// Sets the value of a bit at an index `i`.
400 /// Panics if `i` is out of bounds.
405 /// # #![feature(collections)]
406 /// use std::collections::BitVec;
408 /// let mut bv = BitVec::from_elem(5, false);
410 /// assert_eq!(bv[3], true);
413 #[unstable(feature = "collections",
414 reason = "panic semantics are likely to change in the future")]
415 pub fn set(&mut self, i: usize, x: bool) {
416 assert!(i < self.nbits);
417 let w = i / u32::BITS as usize;
418 let b = i % u32::BITS as usize;
420 let val = if x { self.storage[w] | flag }
421 else { self.storage[w] & !flag };
422 self.storage[w] = val;
425 /// Sets all bits to 1.
430 /// # #![feature(collections)]
431 /// use std::collections::BitVec;
433 /// let before = 0b01100000;
434 /// let after = 0b11111111;
436 /// let mut bv = BitVec::from_bytes(&[before]);
438 /// assert_eq!(bv, BitVec::from_bytes(&[after]));
441 pub fn set_all(&mut self) {
442 for w in &mut self.storage { *w = !0; }
443 self.fix_last_block();
451 /// # #![feature(collections)]
452 /// use std::collections::BitVec;
454 /// let before = 0b01100000;
455 /// let after = 0b10011111;
457 /// let mut bv = BitVec::from_bytes(&[before]);
459 /// assert_eq!(bv, BitVec::from_bytes(&[after]));
462 pub fn negate(&mut self) {
463 for w in &mut self.storage { *w = !*w; }
464 self.fix_last_block();
467 /// Calculates the union of two bitvectors. This acts like the bitwise `or`
470 /// Sets `self` to the union of `self` and `other`. Both bitvectors must be
471 /// the same length. Returns `true` if `self` changed.
475 /// Panics if the bitvectors are of different lengths.
480 /// # #![feature(collections)]
481 /// use std::collections::BitVec;
483 /// let a = 0b01100100;
484 /// let b = 0b01011010;
485 /// let res = 0b01111110;
487 /// let mut a = BitVec::from_bytes(&[a]);
488 /// let b = BitVec::from_bytes(&[b]);
490 /// assert!(a.union(&b));
491 /// assert_eq!(a, BitVec::from_bytes(&[res]));
494 pub fn union(&mut self, other: &BitVec) -> bool {
495 self.process(other, |w1, w2| w1 | w2)
498 /// Calculates the intersection of two bitvectors. This acts like the
499 /// bitwise `and` function.
501 /// Sets `self` to the intersection of `self` and `other`. Both bitvectors
502 /// must be the same length. Returns `true` if `self` changed.
506 /// Panics if the bitvectors are of different lengths.
511 /// # #![feature(collections)]
512 /// use std::collections::BitVec;
514 /// let a = 0b01100100;
515 /// let b = 0b01011010;
516 /// let res = 0b01000000;
518 /// let mut a = BitVec::from_bytes(&[a]);
519 /// let b = BitVec::from_bytes(&[b]);
521 /// assert!(a.intersect(&b));
522 /// assert_eq!(a, BitVec::from_bytes(&[res]));
525 pub fn intersect(&mut self, other: &BitVec) -> bool {
526 self.process(other, |w1, w2| w1 & w2)
529 /// Calculates the difference between two bitvectors.
531 /// Sets each element of `self` to the value of that element minus the
532 /// element of `other` at the same index. Both bitvectors must be the same
533 /// length. Returns `true` if `self` changed.
537 /// Panics if the bitvectors are of different length.
542 /// # #![feature(collections)]
543 /// use std::collections::BitVec;
545 /// let a = 0b01100100;
546 /// let b = 0b01011010;
547 /// let a_b = 0b00100100; // a - b
548 /// let b_a = 0b00011010; // b - a
550 /// let mut bva = BitVec::from_bytes(&[a]);
551 /// let bvb = BitVec::from_bytes(&[b]);
553 /// assert!(bva.difference(&bvb));
554 /// assert_eq!(bva, BitVec::from_bytes(&[a_b]));
556 /// let bva = BitVec::from_bytes(&[a]);
557 /// let mut bvb = BitVec::from_bytes(&[b]);
559 /// assert!(bvb.difference(&bva));
560 /// assert_eq!(bvb, BitVec::from_bytes(&[b_a]));
563 pub fn difference(&mut self, other: &BitVec) -> bool {
564 self.process(other, |w1, w2| w1 & !w2)
567 /// Returns `true` if all bits are 1.
572 /// # #![feature(collections)]
573 /// use std::collections::BitVec;
575 /// let mut bv = BitVec::from_elem(5, true);
576 /// assert_eq!(bv.all(), true);
578 /// bv.set(1, false);
579 /// assert_eq!(bv.all(), false);
581 pub fn all(&self) -> bool {
582 let mut last_word = !0;
583 // Check that every block but the last is all-ones...
584 self.blocks().all(|elem| {
588 // and then check the last one has enough ones
589 }) && (last_word == mask_for_bits(self.nbits))
592 /// Returns an iterator over the elements of the vector in order.
597 /// # #![feature(collections)]
598 /// use std::collections::BitVec;
600 /// let bv = BitVec::from_bytes(&[0b01110100, 0b10010010]);
601 /// assert_eq!(bv.iter().filter(|x| *x).count(), 7);
604 #[stable(feature = "rust1", since = "1.0.0")]
605 pub fn iter(&self) -> Iter {
606 Iter { bit_vec: self, next_idx: 0, end_idx: self.nbits }
609 /// Returns `true` if all bits are 0.
614 /// # #![feature(collections)]
615 /// use std::collections::BitVec;
617 /// let mut bv = BitVec::from_elem(10, false);
618 /// assert_eq!(bv.none(), true);
621 /// assert_eq!(bv.none(), false);
623 pub fn none(&self) -> bool {
624 self.blocks().all(|w| w == 0)
627 /// Returns `true` if any bit is 1.
632 /// # #![feature(collections)]
633 /// use std::collections::BitVec;
635 /// let mut bv = BitVec::from_elem(10, false);
636 /// assert_eq!(bv.any(), false);
639 /// assert_eq!(bv.any(), true);
642 pub fn any(&self) -> bool {
646 /// Organises the bits into bytes, such that the first bit in the
647 /// `BitVec` becomes the high-order bit of the first byte. If the
648 /// size of the `BitVec` is not a multiple of eight then trailing bits
649 /// will be filled-in with `false`.
654 /// # #![feature(collections)]
655 /// use std::collections::BitVec;
657 /// let mut bv = BitVec::from_elem(3, true);
658 /// bv.set(1, false);
660 /// assert_eq!(bv.to_bytes(), [0b10100000]);
662 /// let mut bv = BitVec::from_elem(9, false);
666 /// assert_eq!(bv.to_bytes(), [0b00100000, 0b10000000]);
668 pub fn to_bytes(&self) -> Vec<u8> {
669 fn bit(bit_vec: &BitVec, byte: usize, bit: usize) -> u8 {
670 let offset = byte * 8 + bit;
671 if offset >= bit_vec.nbits {
674 (bit_vec[offset] as u8) << (7 - bit)
678 let len = self.nbits/8 +
679 if self.nbits % 8 == 0 { 0 } else { 1 };
692 /// Compares a `BitVec` to a slice of `bool`s.
693 /// Both the `BitVec` and slice must have the same length.
697 /// Panics if the `BitVec` and slice are of different length.
702 /// # #![feature(collections)]
703 /// use std::collections::BitVec;
705 /// let bv = BitVec::from_bytes(&[0b10100000]);
707 /// assert!(bv.eq_vec(&[true, false, true, false,
708 /// false, false, false, false]));
710 pub fn eq_vec(&self, v: &[bool]) -> bool {
711 assert_eq!(self.nbits, v.len());
712 iter::order::eq(self.iter(), v.iter().cloned())
715 /// Shortens a `BitVec`, dropping excess elements.
717 /// If `len` is greater than the vector's current length, this has no
723 /// # #![feature(collections)]
724 /// use std::collections::BitVec;
726 /// let mut bv = BitVec::from_bytes(&[0b01001011]);
728 /// assert!(bv.eq_vec(&[false, true]));
730 #[stable(feature = "rust1", since = "1.0.0")]
731 pub fn truncate(&mut self, len: usize) {
732 if len < self.len() {
735 self.storage.truncate(blocks_for_bits(len));
736 self.fix_last_block();
740 /// Reserves capacity for at least `additional` more bits to be inserted in the given
741 /// `BitVec`. The collection may reserve more space to avoid frequent reallocations.
745 /// Panics if the new capacity overflows `usize`.
750 /// # #![feature(collections)]
751 /// use std::collections::BitVec;
753 /// let mut bv = BitVec::from_elem(3, false);
755 /// assert_eq!(bv.len(), 3);
756 /// assert!(bv.capacity() >= 13);
758 #[stable(feature = "rust1", since = "1.0.0")]
759 pub fn reserve(&mut self, additional: usize) {
760 let desired_cap = self.len().checked_add(additional).expect("capacity overflow");
761 let storage_len = self.storage.len();
762 if desired_cap > self.capacity() {
763 self.storage.reserve(blocks_for_bits(desired_cap) - storage_len);
767 /// Reserves the minimum capacity for exactly `additional` more bits to be inserted in the
768 /// given `BitVec`. Does nothing if the capacity is already sufficient.
770 /// Note that the allocator may give the collection more space than it requests. Therefore
771 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
772 /// insertions are expected.
776 /// Panics if the new capacity overflows `usize`.
781 /// # #![feature(collections)]
782 /// use std::collections::BitVec;
784 /// let mut bv = BitVec::from_elem(3, false);
786 /// assert_eq!(bv.len(), 3);
787 /// assert!(bv.capacity() >= 13);
789 #[stable(feature = "rust1", since = "1.0.0")]
790 pub fn reserve_exact(&mut self, additional: usize) {
791 let desired_cap = self.len().checked_add(additional).expect("capacity overflow");
792 let storage_len = self.storage.len();
793 if desired_cap > self.capacity() {
794 self.storage.reserve_exact(blocks_for_bits(desired_cap) - storage_len);
798 /// Returns the capacity in bits for this bit vector. Inserting any
799 /// element less than this amount will not trigger a resizing.
804 /// # #![feature(collections)]
805 /// use std::collections::BitVec;
807 /// let mut bv = BitVec::new();
809 /// assert!(bv.capacity() >= 10);
812 #[stable(feature = "rust1", since = "1.0.0")]
813 pub fn capacity(&self) -> usize {
814 self.storage.capacity().checked_mul(u32::BITS as usize).unwrap_or(usize::MAX)
817 /// Grows the `BitVec` in-place, adding `n` copies of `value` to the `BitVec`.
821 /// Panics if the new len overflows a `usize`.
826 /// # #![feature(collections)]
827 /// use std::collections::BitVec;
829 /// let mut bv = BitVec::from_bytes(&[0b01001011]);
830 /// bv.grow(2, true);
831 /// assert_eq!(bv.len(), 10);
832 /// assert_eq!(bv.to_bytes(), [0b01001011, 0b11000000]);
834 pub fn grow(&mut self, n: usize, value: bool) {
835 // Note: we just bulk set all the bits in the last word in this fn in multiple places
836 // which is technically wrong if not all of these bits are to be used. However, at the end
837 // of this fn we call `fix_last_block` at the end of this fn, which should fix this.
839 let new_nbits = self.nbits.checked_add(n).expect("capacity overflow");
840 let new_nblocks = blocks_for_bits(new_nbits);
841 let full_value = if value { !0 } else { 0 };
843 // Correct the old tail word, setting or clearing formerly unused bits
844 let num_cur_blocks = blocks_for_bits(self.nbits);
845 if self.nbits % u32::BITS as usize > 0 {
846 let mask = mask_for_bits(self.nbits);
848 self.storage[num_cur_blocks - 1] |= !mask;
850 // Extra bits are already zero by invariant.
854 // Fill in words after the old tail word
855 let stop_idx = cmp::min(self.storage.len(), new_nblocks);
856 for idx in num_cur_blocks..stop_idx {
857 self.storage[idx] = full_value;
860 // Allocate new words, if needed
861 if new_nblocks > self.storage.len() {
862 let to_add = new_nblocks - self.storage.len();
863 self.storage.extend(repeat(full_value).take(to_add));
866 // Adjust internal bit count
867 self.nbits = new_nbits;
869 self.fix_last_block();
872 /// Removes the last bit from the BitVec, and returns it. Returns None if the BitVec is empty.
877 /// # #![feature(collections)]
878 /// use std::collections::BitVec;
880 /// let mut bv = BitVec::from_bytes(&[0b01001001]);
881 /// assert_eq!(bv.pop(), Some(true));
882 /// assert_eq!(bv.pop(), Some(false));
883 /// assert_eq!(bv.len(), 6);
885 #[stable(feature = "rust1", since = "1.0.0")]
886 pub fn pop(&mut self) -> Option<bool> {
890 let i = self.nbits - 1;
895 if self.nbits % u32::BITS as usize == 0 {
903 /// Pushes a `bool` onto the end.
908 /// # #![feature(collections)]
909 /// use std::collections::BitVec;
911 /// let mut bv = BitVec::new();
914 /// assert!(bv.eq_vec(&[true, false]));
916 #[stable(feature = "rust1", since = "1.0.0")]
917 pub fn push(&mut self, elem: bool) {
918 if self.nbits % u32::BITS as usize == 0 {
919 self.storage.push(0);
921 let insert_pos = self.nbits;
922 self.nbits = self.nbits.checked_add(1).expect("Capacity overflow");
923 self.set(insert_pos, elem);
926 /// Return the total number of bits in this vector
928 #[stable(feature = "rust1", since = "1.0.0")]
929 pub fn len(&self) -> usize { self.nbits }
931 /// Returns true if there are no bits in this vector
933 #[stable(feature = "rust1", since = "1.0.0")]
934 pub fn is_empty(&self) -> bool { self.len() == 0 }
936 /// Clears all bits in this vector.
938 #[stable(feature = "rust1", since = "1.0.0")]
939 pub fn clear(&mut self) {
940 for w in &mut self.storage { *w = 0; }
944 #[stable(feature = "rust1", since = "1.0.0")]
945 impl Default for BitVec {
947 fn default() -> BitVec { BitVec::new() }
950 #[stable(feature = "rust1", since = "1.0.0")]
951 impl FromIterator<bool> for BitVec {
952 fn from_iter<I: IntoIterator<Item=bool>>(iter: I) -> BitVec {
953 let mut ret = BitVec::new();
959 #[stable(feature = "rust1", since = "1.0.0")]
960 impl Extend<bool> for BitVec {
962 fn extend<I: IntoIterator<Item=bool>>(&mut self, iterable: I) {
963 let iterator = iterable.into_iter();
964 let (min, _) = iterator.size_hint();
966 for element in iterator {
972 #[stable(feature = "rust1", since = "1.0.0")]
973 impl Clone for BitVec {
975 fn clone(&self) -> BitVec {
976 BitVec { storage: self.storage.clone(), nbits: self.nbits }
980 fn clone_from(&mut self, source: &BitVec) {
981 self.nbits = source.nbits;
982 self.storage.clone_from(&source.storage);
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl PartialOrd for BitVec {
989 fn partial_cmp(&self, other: &BitVec) -> Option<Ordering> {
990 iter::order::partial_cmp(self.iter(), other.iter())
994 #[stable(feature = "rust1", since = "1.0.0")]
995 impl Ord for BitVec {
997 fn cmp(&self, other: &BitVec) -> Ordering {
998 iter::order::cmp(self.iter(), other.iter())
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 impl fmt::Debug for BitVec {
1004 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1006 try!(write!(fmt, "{}", if bit { 1 } else { 0 }));
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 impl hash::Hash for BitVec {
1014 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1015 self.nbits.hash(state);
1016 for elem in self.blocks() {
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 impl cmp::PartialEq for BitVec {
1025 fn eq(&self, other: &BitVec) -> bool {
1026 if self.nbits != other.nbits {
1029 self.blocks().zip(other.blocks()).all(|(w1, w2)| w1 == w2)
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl cmp::Eq for BitVec {}
1036 /// An iterator for `BitVec`.
1037 #[stable(feature = "rust1", since = "1.0.0")]
1039 pub struct Iter<'a> {
1040 bit_vec: &'a BitVec,
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 impl<'a> Iterator for Iter<'a> {
1050 fn next(&mut self) -> Option<bool> {
1051 if self.next_idx != self.end_idx {
1052 let idx = self.next_idx;
1054 Some(self.bit_vec[idx])
1060 fn size_hint(&self) -> (usize, Option<usize>) {
1061 let rem = self.end_idx - self.next_idx;
1066 #[stable(feature = "rust1", since = "1.0.0")]
1067 impl<'a> DoubleEndedIterator for Iter<'a> {
1069 fn next_back(&mut self) -> Option<bool> {
1070 if self.next_idx != self.end_idx {
1072 Some(self.bit_vec[self.end_idx])
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 impl<'a> ExactSizeIterator for Iter<'a> {}
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 impl<'a> RandomAccessIterator for Iter<'a> {
1085 fn indexable(&self) -> usize {
1086 self.end_idx - self.next_idx
1090 fn idx(&mut self, index: usize) -> Option<bool> {
1091 if index >= self.indexable() {
1094 Some(self.bit_vec[index])
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 impl<'a> IntoIterator for &'a BitVec {
1102 type IntoIter = Iter<'a>;
1104 fn into_iter(self) -> Iter<'a> {
1109 /// An implementation of a set using a bit vector as an underlying
1110 /// representation for holding unsigned numerical elements.
1112 /// It should also be noted that the amount of storage necessary for holding a
1113 /// set of objects is proportional to the maximum of the objects when viewed
1119 /// # #![feature(collections)]
1120 /// use std::collections::{BitSet, BitVec};
1122 /// // It's a regular set
1123 /// let mut s = BitSet::new();
1130 /// if !s.contains(&7) {
1131 /// println!("There is no 7");
1134 /// // Can initialize from a `BitVec`
1135 /// let other = BitSet::from_bit_vec(BitVec::from_bytes(&[0b11010000]));
1137 /// s.union_with(&other);
1139 /// // Print 0, 1, 3 in some order
1140 /// for x in s.iter() {
1141 /// println!("{}", x);
1144 /// // Can convert back to a `BitVec`
1145 /// let bv: BitVec = s.into_bit_vec();
1149 #[unstable(feature = "collections",
1150 reason = "RFC 509")]
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 impl Default for BitSet {
1158 fn default() -> BitSet { BitSet::new() }
1161 #[stable(feature = "rust1", since = "1.0.0")]
1162 impl FromIterator<usize> for BitSet {
1163 fn from_iter<I: IntoIterator<Item=usize>>(iter: I) -> BitSet {
1164 let mut ret = BitSet::new();
1170 #[stable(feature = "rust1", since = "1.0.0")]
1171 impl Extend<usize> for BitSet {
1173 fn extend<I: IntoIterator<Item=usize>>(&mut self, iter: I) {
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 impl PartialOrd for BitSet {
1183 fn partial_cmp(&self, other: &BitSet) -> Option<Ordering> {
1184 let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1185 iter::order::partial_cmp(a_iter, b_iter)
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 impl Ord for BitSet {
1192 fn cmp(&self, other: &BitSet) -> Ordering {
1193 let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1194 iter::order::cmp(a_iter, b_iter)
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 impl cmp::PartialEq for BitSet {
1201 fn eq(&self, other: &BitSet) -> bool {
1202 let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
1203 iter::order::eq(a_iter, b_iter)
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 impl cmp::Eq for BitSet {}
1211 /// Creates a new empty `BitSet`.
1216 /// # #![feature(collections)]
1217 /// use std::collections::BitSet;
1219 /// let mut s = BitSet::new();
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 pub fn new() -> BitSet {
1224 BitSet { bit_vec: BitVec::new() }
1227 /// Creates a new `BitSet` with initially no contents, able to
1228 /// hold `nbits` elements without resizing.
1233 /// # #![feature(collections)]
1234 /// use std::collections::BitSet;
1236 /// let mut s = BitSet::with_capacity(100);
1237 /// assert!(s.capacity() >= 100);
1240 #[stable(feature = "rust1", since = "1.0.0")]
1241 pub fn with_capacity(nbits: usize) -> BitSet {
1242 let bit_vec = BitVec::from_elem(nbits, false);
1243 BitSet::from_bit_vec(bit_vec)
1246 /// Creates a new `BitSet` from the given bit vector.
1251 /// # #![feature(collections)]
1252 /// use std::collections::{BitVec, BitSet};
1254 /// let bv = BitVec::from_bytes(&[0b01100000]);
1255 /// let s = BitSet::from_bit_vec(bv);
1257 /// // Print 1, 2 in arbitrary order
1258 /// for x in s.iter() {
1259 /// println!("{}", x);
1263 pub fn from_bit_vec(bit_vec: BitVec) -> BitSet {
1264 BitSet { bit_vec: bit_vec }
1267 /// Deprecated: use `from_bit_vec`.
1269 #[deprecated(since = "1.0.0", reason = "renamed to from_bit_vec")]
1270 #[unstable(feature = "collections")]
1271 pub fn from_bitv(bit_vec: BitVec) -> BitSet {
1272 BitSet { bit_vec: bit_vec }
1275 /// Returns the capacity in bits for this bit vector. Inserting any
1276 /// element less than this amount will not trigger a resizing.
1281 /// # #![feature(collections)]
1282 /// use std::collections::BitSet;
1284 /// let mut s = BitSet::with_capacity(100);
1285 /// assert!(s.capacity() >= 100);
1288 #[stable(feature = "rust1", since = "1.0.0")]
1289 pub fn capacity(&self) -> usize {
1290 self.bit_vec.capacity()
1293 /// Reserves capacity for the given `BitSet` to contain `len` distinct elements. In the case
1294 /// of `BitSet` this means reallocations will not occur as long as all inserted elements
1295 /// are less than `len`.
1297 /// The collection may reserve more space to avoid frequent reallocations.
1303 /// # #![feature(collections)]
1304 /// use std::collections::BitSet;
1306 /// let mut s = BitSet::new();
1307 /// s.reserve_len(10);
1308 /// assert!(s.capacity() >= 10);
1310 #[stable(feature = "rust1", since = "1.0.0")]
1311 pub fn reserve_len(&mut self, len: usize) {
1312 let cur_len = self.bit_vec.len();
1314 self.bit_vec.reserve(len - cur_len);
1318 /// Reserves the minimum capacity for the given `BitSet` to contain `len` distinct elements.
1319 /// In the case of `BitSet` this means reallocations will not occur as long as all inserted
1320 /// elements are less than `len`.
1322 /// Note that the allocator may give the collection more space than it requests. Therefore
1323 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve_len` if future
1324 /// insertions are expected.
1330 /// # #![feature(collections)]
1331 /// use std::collections::BitSet;
1333 /// let mut s = BitSet::new();
1334 /// s.reserve_len_exact(10);
1335 /// assert!(s.capacity() >= 10);
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 pub fn reserve_len_exact(&mut self, len: usize) {
1339 let cur_len = self.bit_vec.len();
1341 self.bit_vec.reserve_exact(len - cur_len);
1346 /// Consumes this set to return the underlying bit vector.
1351 /// # #![feature(collections)]
1352 /// use std::collections::BitSet;
1354 /// let mut s = BitSet::new();
1358 /// let bv = s.into_bit_vec();
1363 pub fn into_bit_vec(self) -> BitVec {
1367 /// Returns a reference to the underlying bit vector.
1372 /// # #![feature(collections)]
1373 /// use std::collections::BitSet;
1375 /// let mut s = BitSet::new();
1378 /// let bv = s.get_ref();
1379 /// assert_eq!(bv[0], true);
1382 pub fn get_ref(&self) -> &BitVec {
1387 fn other_op<F>(&mut self, other: &BitSet, mut f: F) where F: FnMut(u32, u32) -> u32 {
1389 let self_bit_vec = &mut self.bit_vec;
1390 let other_bit_vec = &other.bit_vec;
1392 let self_len = self_bit_vec.len();
1393 let other_len = other_bit_vec.len();
1395 // Expand the vector if necessary
1396 if self_len < other_len {
1397 self_bit_vec.grow(other_len - self_len, false);
1400 // virtually pad other with 0's for equal lengths
1402 let (_, result) = match_words(self_bit_vec, other_bit_vec);
1406 // Apply values found in other
1407 for (i, w) in other_words {
1408 let old = self_bit_vec.storage[i];
1409 let new = f(old, w);
1410 self_bit_vec.storage[i] = new;
1414 /// Truncates the underlying vector to the least length required.
1419 /// # #![feature(collections)]
1420 /// use std::collections::BitSet;
1422 /// let mut s = BitSet::new();
1423 /// s.insert(32183231);
1424 /// s.remove(&32183231);
1426 /// // Internal storage will probably be bigger than necessary
1427 /// println!("old capacity: {}", s.capacity());
1429 /// // Now should be smaller
1430 /// s.shrink_to_fit();
1431 /// println!("new capacity: {}", s.capacity());
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 pub fn shrink_to_fit(&mut self) {
1436 let bit_vec = &mut self.bit_vec;
1437 // Obtain original length
1438 let old_len = bit_vec.storage.len();
1439 // Obtain coarse trailing zero length
1440 let n = bit_vec.storage.iter().rev().take_while(|&&n| n == 0).count();
1442 let trunc_len = cmp::max(old_len - n, 1);
1443 bit_vec.storage.truncate(trunc_len);
1444 bit_vec.nbits = trunc_len * u32::BITS as usize;
1447 /// Iterator over each u32 stored in the `BitSet`.
1452 /// # #![feature(collections)]
1453 /// use std::collections::{BitVec, BitSet};
1455 /// let s = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01001010]));
1457 /// // Print 1, 4, 6 in arbitrary order
1458 /// for x in s.iter() {
1459 /// println!("{}", x);
1463 #[stable(feature = "rust1", since = "1.0.0")]
1464 pub fn iter(&self) -> bit_set::Iter {
1465 SetIter {set: self, next_idx: 0}
1468 /// Iterator over each u32 stored in `self` union `other`.
1469 /// See [union_with](#method.union_with) for an efficient in-place version.
1474 /// # #![feature(collections)]
1475 /// use std::collections::{BitVec, BitSet};
1477 /// let a = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01101000]));
1478 /// let b = BitSet::from_bit_vec(BitVec::from_bytes(&[0b10100000]));
1480 /// // Print 0, 1, 2, 4 in arbitrary order
1481 /// for x in a.union(&b) {
1482 /// println!("{}", x);
1486 #[stable(feature = "rust1", since = "1.0.0")]
1487 pub fn union<'a>(&'a self, other: &'a BitSet) -> Union<'a> {
1488 fn or(w1: u32, w2: u32) -> u32 { w1 | w2 }
1490 Union(TwoBitPositions {
1499 /// Iterator over each usize stored in `self` intersect `other`.
1500 /// See [intersect_with](#method.intersect_with) for an efficient in-place version.
1505 /// # #![feature(collections)]
1506 /// use std::collections::{BitVec, BitSet};
1508 /// let a = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01101000]));
1509 /// let b = BitSet::from_bit_vec(BitVec::from_bytes(&[0b10100000]));
1512 /// for x in a.intersection(&b) {
1513 /// println!("{}", x);
1517 #[stable(feature = "rust1", since = "1.0.0")]
1518 pub fn intersection<'a>(&'a self, other: &'a BitSet) -> Intersection<'a> {
1519 fn bitand(w1: u32, w2: u32) -> u32 { w1 & w2 }
1520 let min = cmp::min(self.bit_vec.len(), other.bit_vec.len());
1521 Intersection(TwoBitPositions {
1530 /// Iterator over each usize stored in the `self` setminus `other`.
1531 /// See [difference_with](#method.difference_with) for an efficient in-place version.
1536 /// # #![feature(collections)]
1537 /// use std::collections::{BitSet, BitVec};
1539 /// let a = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01101000]));
1540 /// let b = BitSet::from_bit_vec(BitVec::from_bytes(&[0b10100000]));
1542 /// // Print 1, 4 in arbitrary order
1543 /// for x in a.difference(&b) {
1544 /// println!("{}", x);
1547 /// // Note that difference is not symmetric,
1548 /// // and `b - a` means something else.
1549 /// // This prints 0
1550 /// for x in b.difference(&a) {
1551 /// println!("{}", x);
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 pub fn difference<'a>(&'a self, other: &'a BitSet) -> Difference<'a> {
1557 fn diff(w1: u32, w2: u32) -> u32 { w1 & !w2 }
1559 Difference(TwoBitPositions {
1568 /// Iterator over each u32 stored in the symmetric difference of `self` and `other`.
1569 /// See [symmetric_difference_with](#method.symmetric_difference_with) for
1570 /// an efficient in-place version.
1575 /// # #![feature(collections)]
1576 /// use std::collections::{BitSet, BitVec};
1578 /// let a = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01101000]));
1579 /// let b = BitSet::from_bit_vec(BitVec::from_bytes(&[0b10100000]));
1581 /// // Print 0, 1, 4 in arbitrary order
1582 /// for x in a.symmetric_difference(&b) {
1583 /// println!("{}", x);
1587 #[stable(feature = "rust1", since = "1.0.0")]
1588 pub fn symmetric_difference<'a>(&'a self, other: &'a BitSet) -> SymmetricDifference<'a> {
1589 fn bitxor(w1: u32, w2: u32) -> u32 { w1 ^ w2 }
1591 SymmetricDifference(TwoBitPositions {
1600 /// Unions in-place with the specified other bit vector.
1605 /// # #![feature(collections)]
1606 /// use std::collections::{BitSet, BitVec};
1608 /// let a = 0b01101000;
1609 /// let b = 0b10100000;
1610 /// let res = 0b11101000;
1612 /// let mut a = BitSet::from_bit_vec(BitVec::from_bytes(&[a]));
1613 /// let b = BitSet::from_bit_vec(BitVec::from_bytes(&[b]));
1614 /// let res = BitSet::from_bit_vec(BitVec::from_bytes(&[res]));
1616 /// a.union_with(&b);
1617 /// assert_eq!(a, res);
1620 pub fn union_with(&mut self, other: &BitSet) {
1621 self.other_op(other, |w1, w2| w1 | w2);
1624 /// Intersects in-place with the specified other bit vector.
1629 /// # #![feature(collections)]
1630 /// use std::collections::{BitSet, BitVec};
1632 /// let a = 0b01101000;
1633 /// let b = 0b10100000;
1634 /// let res = 0b00100000;
1636 /// let mut a = BitSet::from_bit_vec(BitVec::from_bytes(&[a]));
1637 /// let b = BitSet::from_bit_vec(BitVec::from_bytes(&[b]));
1638 /// let res = BitSet::from_bit_vec(BitVec::from_bytes(&[res]));
1640 /// a.intersect_with(&b);
1641 /// assert_eq!(a, res);
1644 pub fn intersect_with(&mut self, other: &BitSet) {
1645 self.other_op(other, |w1, w2| w1 & w2);
1648 /// Makes this bit vector the difference with the specified other bit vector
1654 /// # #![feature(collections)]
1655 /// use std::collections::{BitSet, BitVec};
1657 /// let a = 0b01101000;
1658 /// let b = 0b10100000;
1659 /// let a_b = 0b01001000; // a - b
1660 /// let b_a = 0b10000000; // b - a
1662 /// let mut bva = BitSet::from_bit_vec(BitVec::from_bytes(&[a]));
1663 /// let bvb = BitSet::from_bit_vec(BitVec::from_bytes(&[b]));
1664 /// let bva_b = BitSet::from_bit_vec(BitVec::from_bytes(&[a_b]));
1665 /// let bvb_a = BitSet::from_bit_vec(BitVec::from_bytes(&[b_a]));
1667 /// bva.difference_with(&bvb);
1668 /// assert_eq!(bva, bva_b);
1670 /// let bva = BitSet::from_bit_vec(BitVec::from_bytes(&[a]));
1671 /// let mut bvb = BitSet::from_bit_vec(BitVec::from_bytes(&[b]));
1673 /// bvb.difference_with(&bva);
1674 /// assert_eq!(bvb, bvb_a);
1677 pub fn difference_with(&mut self, other: &BitSet) {
1678 self.other_op(other, |w1, w2| w1 & !w2);
1681 /// Makes this bit vector the symmetric difference with the specified other
1682 /// bit vector in-place.
1687 /// # #![feature(collections)]
1688 /// use std::collections::{BitSet, BitVec};
1690 /// let a = 0b01101000;
1691 /// let b = 0b10100000;
1692 /// let res = 0b11001000;
1694 /// let mut a = BitSet::from_bit_vec(BitVec::from_bytes(&[a]));
1695 /// let b = BitSet::from_bit_vec(BitVec::from_bytes(&[b]));
1696 /// let res = BitSet::from_bit_vec(BitVec::from_bytes(&[res]));
1698 /// a.symmetric_difference_with(&b);
1699 /// assert_eq!(a, res);
1702 pub fn symmetric_difference_with(&mut self, other: &BitSet) {
1703 self.other_op(other, |w1, w2| w1 ^ w2);
1706 /// Return the number of set bits in this set.
1708 #[stable(feature = "rust1", since = "1.0.0")]
1709 pub fn len(&self) -> usize {
1710 self.bit_vec.blocks().fold(0, |acc, n| acc + n.count_ones() as usize)
1713 /// Returns whether there are no bits set in this set
1715 #[stable(feature = "rust1", since = "1.0.0")]
1716 pub fn is_empty(&self) -> bool {
1720 /// Clears all bits in this set
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 pub fn clear(&mut self) {
1724 self.bit_vec.clear();
1727 /// Returns `true` if this set contains the specified integer.
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 pub fn contains(&self, value: &usize) -> bool {
1731 let bit_vec = &self.bit_vec;
1732 *value < bit_vec.nbits && bit_vec[*value]
1735 /// Returns `true` if the set has no elements in common with `other`.
1736 /// This is equivalent to checking for an empty intersection.
1738 #[stable(feature = "rust1", since = "1.0.0")]
1739 pub fn is_disjoint(&self, other: &BitSet) -> bool {
1740 self.intersection(other).next().is_none()
1743 /// Returns `true` if the set is a subset of another.
1745 #[stable(feature = "rust1", since = "1.0.0")]
1746 pub fn is_subset(&self, other: &BitSet) -> bool {
1747 let self_bit_vec = &self.bit_vec;
1748 let other_bit_vec = &other.bit_vec;
1749 let other_blocks = blocks_for_bits(other_bit_vec.len());
1751 // Check that `self` intersect `other` is self
1752 self_bit_vec.blocks().zip(other_bit_vec.blocks()).all(|(w1, w2)| w1 & w2 == w1) &&
1753 // Make sure if `self` has any more blocks than `other`, they're all 0
1754 self_bit_vec.blocks().skip(other_blocks).all(|w| w == 0)
1757 /// Returns `true` if the set is a superset of another.
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 pub fn is_superset(&self, other: &BitSet) -> bool {
1761 other.is_subset(self)
1764 /// Adds a value to the set. Returns `true` if the value was not already
1765 /// present in the set.
1766 #[stable(feature = "rust1", since = "1.0.0")]
1767 pub fn insert(&mut self, value: usize) -> bool {
1768 if self.contains(&value) {
1772 // Ensure we have enough space to hold the new element
1773 let len = self.bit_vec.len();
1775 self.bit_vec.grow(value - len + 1, false)
1778 self.bit_vec.set(value, true);
1782 /// Removes a value from the set. Returns `true` if the value was
1783 /// present in the set.
1784 #[stable(feature = "rust1", since = "1.0.0")]
1785 pub fn remove(&mut self, value: &usize) -> bool {
1786 if !self.contains(value) {
1790 self.bit_vec.set(*value, false);
1796 #[stable(feature = "rust1", since = "1.0.0")]
1797 impl fmt::Debug for BitSet {
1798 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1799 try!(write!(fmt, "{{"));
1800 let mut first = true;
1803 try!(write!(fmt, ", "));
1805 try!(write!(fmt, "{:?}", n));
1812 #[stable(feature = "rust1", since = "1.0.0")]
1813 impl hash::Hash for BitSet {
1814 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1821 /// An iterator for `BitSet`.
1823 #[stable(feature = "rust1", since = "1.0.0")]
1824 pub struct SetIter<'a> {
1829 /// An iterator combining two `BitSet` iterators.
1831 struct TwoBitPositions<'a> {
1834 merge: fn(u32, u32) -> u32,
1840 #[stable(feature = "rust1", since = "1.0.0")]
1841 pub struct Union<'a>(TwoBitPositions<'a>);
1843 #[stable(feature = "rust1", since = "1.0.0")]
1844 pub struct Intersection<'a>(Take<TwoBitPositions<'a>>);
1846 #[stable(feature = "rust1", since = "1.0.0")]
1847 pub struct Difference<'a>(TwoBitPositions<'a>);
1849 #[stable(feature = "rust1", since = "1.0.0")]
1850 pub struct SymmetricDifference<'a>(TwoBitPositions<'a>);
1852 #[stable(feature = "rust1", since = "1.0.0")]
1853 impl<'a> Iterator for SetIter<'a> {
1856 fn next(&mut self) -> Option<usize> {
1857 while self.next_idx < self.set.bit_vec.len() {
1858 let idx = self.next_idx;
1861 if self.set.contains(&idx) {
1870 fn size_hint(&self) -> (usize, Option<usize>) {
1871 (0, Some(self.set.bit_vec.len() - self.next_idx))
1875 #[stable(feature = "rust1", since = "1.0.0")]
1876 impl<'a> Iterator for TwoBitPositions<'a> {
1879 fn next(&mut self) -> Option<usize> {
1880 while self.next_idx < self.set.bit_vec.len() ||
1881 self.next_idx < self.other.bit_vec.len() {
1882 let bit_idx = self.next_idx % u32::BITS as usize;
1884 let s_bit_vec = &self.set.bit_vec;
1885 let o_bit_vec = &self.other.bit_vec;
1886 // Merging the two words is a bit of an awkward dance since
1887 // one BitVec might be longer than the other
1888 let word_idx = self.next_idx / u32::BITS as usize;
1889 let w1 = if word_idx < s_bit_vec.storage.len() {
1890 s_bit_vec.storage[word_idx]
1892 let w2 = if word_idx < o_bit_vec.storage.len() {
1893 o_bit_vec.storage[word_idx]
1895 self.current_word = (self.merge)(w1, w2);
1899 if self.current_word & (1 << bit_idx) != 0 {
1900 return Some(self.next_idx - 1);
1907 fn size_hint(&self) -> (usize, Option<usize>) {
1908 let cap = cmp::max(self.set.bit_vec.len(), self.other.bit_vec.len());
1909 (0, Some(cap - self.next_idx))
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 impl<'a> Iterator for Union<'a> {
1917 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
1918 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 impl<'a> Iterator for Intersection<'a> {
1925 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
1926 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
1929 #[stable(feature = "rust1", since = "1.0.0")]
1930 impl<'a> Iterator for Difference<'a> {
1933 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
1934 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
1937 #[stable(feature = "rust1", since = "1.0.0")]
1938 impl<'a> Iterator for SymmetricDifference<'a> {
1941 #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
1942 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
1945 #[stable(feature = "rust1", since = "1.0.0")]
1946 impl<'a> IntoIterator for &'a BitSet {
1948 type IntoIter = SetIter<'a>;
1950 fn into_iter(self) -> SetIter<'a> {