bit_vec_omnitool/
lib.rs

1// Copyright 2012-2023 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.
4//
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.
10
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.
16
17// (1) Be careful, most things can overflow here because the amount of bits in
18//     memory can overflow `usize`.
19// (2) Make sure that the underlying vector has no excess length:
20//     E. g. `nbits == 16`, `storage.len() == 2` would be excess length,
21//     because the last word isn't used at all. This is important because some
22//     methods rely on it (for *CORRECTNESS*).
23// (3) Make sure that the unused bits in the last word are zeroed out, again
24//     other methods rely on it for *CORRECTNESS*.
25// (4) `BitSet` is tightly coupled with `BitVec`, so any changes you make in
26// `BitVec` will need to be reflected in `BitSet`.
27
28//! # Description
29//!
30//! Dynamic collections implemented with compact bit vectors.
31//!
32//! # Examples
33//!
34//! This is a simple example of the [Sieve of Eratosthenes][sieve]
35//! which calculates prime numbers up to a given limit.
36//!
37//! [sieve]: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
38//!
39//! ```
40//! use bit_vec::BitVec;
41//!
42//! let max_prime = 10000;
43//!
44//! // Store the primes as a BitVec
45//! let primes = {
46//!     // Assume all numbers are prime to begin, and then we
47//!     // cross off non-primes progressively
48//!     let mut bv = BitVec::from_elem(max_prime, true);
49//!
50//!     // Neither 0 nor 1 are prime
51//!     bv.set(0, false);
52//!     bv.set(1, false);
53//!
54//!     for i in 2.. 1 + (max_prime as f64).sqrt() as usize {
55//!         // if i is a prime
56//!         if bv[i] {
57//!             // Mark all multiples of i as non-prime (any multiples below i * i
58//!             // will have been marked as non-prime previously)
59//!             for j in i.. {
60//!                 if i * j >= max_prime {
61//!                     break;
62//!                 }
63//!                 bv.set(i * j, false)
64//!             }
65//!         }
66//!     }
67//!     bv
68//! };
69//!
70//! // Simple primality tests below our max bound
71//! let print_primes = 20;
72//! print!("The primes below {} are: ", print_primes);
73//! for x in 0..print_primes {
74//!     if primes.get(x).unwrap_or(false) {
75//!         print!("{} ", x);
76//!     }
77//! }
78//! println!();
79//!
80//! let num_primes = primes.iter().filter(|x| *x).count();
81//! println!("There are {} primes below {}", num_primes, max_prime);
82//! assert_eq!(num_primes, 1_229);
83//! ```
84
85#![doc(html_root_url = "https://docs.rs/bit-vec/0.7.0")]
86#![no_std]
87
88#[cfg(any(test, feature = "std"))]
89#[macro_use]
90extern crate std;
91#[cfg(feature = "std")]
92use std::rc::Rc;
93#[cfg(feature = "std")]
94use std::string::String;
95#[cfg(feature = "std")]
96use std::vec::Vec;
97
98#[cfg(feature = "serde")]
99extern crate serde;
100#[cfg(feature = "serde")]
101use serde::{Deserialize, Serialize};
102#[cfg(feature = "borsh")]
103extern crate borsh;
104#[cfg(feature = "miniserde")]
105extern crate miniserde;
106#[cfg(feature = "nanoserde")]
107extern crate nanoserde;
108#[cfg(feature = "nanoserde")]
109use nanoserde::{DeBin, DeJson, DeRon, SerBin, SerJson, SerRon};
110
111#[cfg(not(feature = "std"))]
112#[macro_use]
113extern crate alloc;
114#[cfg(not(feature = "std"))]
115use alloc::rc::Rc;
116#[cfg(not(feature = "std"))]
117use alloc::string::String;
118#[cfg(not(feature = "std"))]
119use alloc::vec::Vec;
120
121use core::cell::RefCell;
122use core::cmp;
123use core::cmp::Ordering;
124use core::fmt::{self, Write};
125use core::hash;
126use core::iter::repeat;
127use core::iter::FromIterator;
128use core::mem;
129use core::ops::*;
130use core::slice;
131
132type MutBlocks<'a, B> = slice::IterMut<'a, B>;
133
134/// Abstracts over a pile of bits (basically unsigned primitives)
135pub trait BitBlock:
136    Copy
137    + Add<Self, Output = Self>
138    + Sub<Self, Output = Self>
139    + Shl<usize, Output = Self>
140    + Shr<usize, Output = Self>
141    + Not<Output = Self>
142    + BitAnd<Self, Output = Self>
143    + BitOr<Self, Output = Self>
144    + BitXor<Self, Output = Self>
145    + Rem<Self, Output = Self>
146    + Eq
147    + Ord
148    + hash::Hash
149{
150    /// How many bits it has
151    fn bits() -> usize;
152    /// How many bytes it has
153    #[inline]
154    fn bytes() -> usize {
155        Self::bits() / 8
156    }
157    /// Convert a byte into this type (lowest-order bits set)
158    fn from_byte(byte: u8) -> Self;
159    /// Count the number of 1's in the bitwise repr
160    fn count_ones(self) -> usize;
161    /// Count the number of 0's in the bitwise repr
162    fn count_zeros(self) -> usize {
163        Self::bits() - self.count_ones()
164    }
165    /// Get `0`
166    fn zero() -> Self;
167    /// Get `1`
168    fn one() -> Self;
169}
170
171macro_rules! bit_block_impl {
172    ($(($t: ident, $size: expr)),*) => ($(
173        impl BitBlock for $t {
174            #[inline]
175            fn bits() -> usize { $size }
176            #[inline]
177            fn from_byte(byte: u8) -> Self { $t::from(byte) }
178            #[inline]
179            fn count_ones(self) -> usize { self.count_ones() as usize }
180            #[inline]
181            fn count_zeros(self) -> usize { self.count_zeros() as usize }
182            #[inline]
183            fn one() -> Self { 1 }
184            #[inline]
185            fn zero() -> Self { 0 }
186        }
187    )*)
188}
189
190bit_block_impl! {
191    (u8, 8),
192    (u16, 16),
193    (u32, 32),
194    (u64, 64),
195    (usize, core::mem::size_of::<usize>() * 8)
196}
197
198fn reverse_bits(byte: u8) -> u8 {
199    let mut result = 0;
200    for i in 0..u8::bits() {
201        result |= ((byte >> i) & 1) << (u8::bits() - 1 - i);
202    }
203    result
204}
205
206static TRUE: bool = true;
207static FALSE: bool = false;
208
209/// The bitvector type.
210///
211/// # Examples
212///
213/// ```
214/// use bit_vec::BitVec;
215///
216/// let mut bv = BitVec::from_elem(10, false);
217///
218/// // insert all primes less than 10
219/// bv.set(2, true);
220/// bv.set(3, true);
221/// bv.set(5, true);
222/// bv.set(7, true);
223/// println!("{:?}", bv);
224/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
225///
226/// // flip all values in bitvector, producing non-primes less than 10
227/// bv.negate();
228/// println!("{:?}", bv);
229/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
230///
231/// // reset bitvector to empty
232/// bv.clear();
233/// println!("{:?}", bv);
234/// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count());
235/// ```
236#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
237#[cfg_attr(
238    feature = "borsh",
239    derive(borsh::BorshDeserialize, borsh::BorshSerialize)
240)]
241#[cfg_attr(
242    feature = "miniserde",
243    derive(miniserde::Deserialize, miniserde::Serialize)
244)]
245#[cfg_attr(
246    feature = "nanoserde",
247    derive(DeBin, DeJson, DeRon, SerBin, SerJson, SerRon)
248)]
249pub struct BitVec<B = u32> {
250    /// Internal representation of the bit vector
251    storage: Vec<B>,
252    /// The number of valid bits in the internal representation
253    nbits: usize,
254}
255
256// FIXME(Gankro): NopeNopeNopeNopeNope (wait for IndexGet to be a thing)
257impl<B: BitBlock> Index<usize> for BitVec<B> {
258    type Output = bool;
259
260    #[inline]
261    fn index(&self, i: usize) -> &bool {
262        if self.get(i).expect("index out of bounds") {
263            &TRUE
264        } else {
265            &FALSE
266        }
267    }
268}
269
270/// Computes how many blocks are needed to store that many bits
271fn blocks_for_bits<B: BitBlock>(bits: usize) -> usize {
272    // If we want 17 bits, dividing by 32 will produce 0. So we add 1 to make sure we
273    // reserve enough. But if we want exactly a multiple of 32, this will actually allocate
274    // one too many. So we need to check if that's the case. We can do that by computing if
275    // bitwise AND by `32 - 1` is 0. But LLVM should be able to optimize the semantically
276    // superior modulo operator on a power of two to this.
277    //
278    // Note that we can technically avoid this branch with the expression
279    // `(nbits + U32_BITS - 1) / 32::BITS`, but if nbits is almost usize::MAX this will overflow.
280    if bits % B::bits() == 0 {
281        bits / B::bits()
282    } else {
283        bits / B::bits() + 1
284    }
285}
286
287/// Computes the bitmask for the final word of the vector
288fn mask_for_bits<B: BitBlock>(bits: usize) -> B {
289    // Note especially that a perfect multiple of U32_BITS should mask all 1s.
290    (!B::zero()) >> ((B::bits() - bits % B::bits()) % B::bits())
291}
292
293type B = u32;
294
295impl BitVec<u32> {
296    /// Creates an empty `BitVec`.
297    ///
298    /// # Examples
299    ///
300    /// ```
301    /// use bit_vec::BitVec;
302    /// let mut bv = BitVec::new();
303    /// ```
304    #[inline]
305    pub fn new() -> Self {
306        Default::default()
307    }
308
309    /// Creates a `BitVec` that holds `nbits` elements, setting each element
310    /// to `bit`.
311    ///
312    /// # Examples
313    ///
314    /// ```
315    /// use bit_vec::BitVec;
316    ///
317    /// let mut bv = BitVec::from_elem(10, false);
318    /// assert_eq!(bv.len(), 10);
319    /// for x in bv.iter() {
320    ///     assert_eq!(x, false);
321    /// }
322    /// ```
323    #[inline]
324    pub fn from_elem(nbits: usize, bit: bool) -> Self {
325        let nblocks = blocks_for_bits::<B>(nbits);
326        let mut bit_vec = BitVec {
327            storage: vec![if bit { !B::zero() } else { B::zero() }; nblocks],
328            nbits,
329        };
330        bit_vec.fix_last_block();
331        bit_vec
332    }
333
334    /// Constructs a new, empty `BitVec` with the specified capacity.
335    ///
336    /// The bitvector will be able to hold at least `capacity` bits without
337    /// reallocating. If `capacity` is 0, it will not allocate.
338    ///
339    /// It is important to note that this function does not specify the
340    /// *length* of the returned bitvector, but only the *capacity*.
341    #[inline]
342    pub fn with_capacity(nbits: usize) -> Self {
343        BitVec {
344            storage: Vec::with_capacity(blocks_for_bits::<B>(nbits)),
345            nbits: 0,
346        }
347    }
348
349    /// Transforms a byte-vector into a `BitVec`. Each byte becomes eight bits,
350    /// with the most significant bits of each byte coming first. Each
351    /// bit becomes `true` if equal to 1 or `false` if equal to 0.
352    ///
353    /// # Examples
354    ///
355    /// ```
356    /// use bit_vec::BitVec;
357    ///
358    /// let bv = BitVec::from_bytes(&[0b10100000, 0b00010010]);
359    /// assert!(bv.eq_vec(&[true, false, true, false,
360    ///                     false, false, false, false,
361    ///                     false, false, false, true,
362    ///                     false, false, true, false]));
363    /// ```
364    pub fn from_bytes(bytes: &[u8]) -> Self {
365        let len = bytes
366            .len()
367            .checked_mul(u8::bits())
368            .expect("capacity overflow");
369        let mut bit_vec = BitVec::with_capacity(len);
370        let complete_words = bytes.len() / B::bytes();
371        let extra_bytes = bytes.len() % B::bytes();
372
373        bit_vec.nbits = len;
374
375        for i in 0..complete_words {
376            let mut accumulator = B::zero();
377            for idx in 0..B::bytes() {
378                accumulator |= B::from_byte(reverse_bits(bytes[i * B::bytes() + idx])) << (idx * 8)
379            }
380            bit_vec.storage.push(accumulator);
381        }
382
383        if extra_bytes > 0 {
384            let mut last_word = B::zero();
385            for (i, &byte) in bytes[complete_words * B::bytes()..].iter().enumerate() {
386                last_word |= B::from_byte(reverse_bits(byte)) << (i * 8);
387            }
388            bit_vec.storage.push(last_word);
389        }
390
391        bit_vec
392    }
393
394    /// Creates a `BitVec` of the specified length where the value at each index
395    /// is `f(index)`.
396    ///
397    /// # Examples
398    ///
399    /// ```
400    /// use bit_vec::BitVec;
401    ///
402    /// let bv = BitVec::from_fn(5, |i| { i % 2 == 0 });
403    /// assert!(bv.eq_vec(&[true, false, true, false, true]));
404    /// ```
405    #[inline]
406    pub fn from_fn<F>(len: usize, mut f: F) -> Self
407    where
408        F: FnMut(usize) -> bool,
409    {
410        let mut bit_vec = BitVec::from_elem(len, false);
411        for i in 0..len {
412            bit_vec.set(i, f(i));
413        }
414        bit_vec
415    }
416}
417
418impl<B: BitBlock> BitVec<B> {
419    /// Applies the given operation to the blocks of self and other, and sets
420    /// self to be the result. This relies on the caller not to corrupt the
421    /// last word.
422    #[inline]
423    fn process<F>(&mut self, other: &BitVec<B>, mut op: F) -> bool
424    where
425        F: FnMut(B, B) -> B,
426    {
427        assert_eq!(self.len(), other.len());
428        debug_assert_eq!(self.storage.len(), other.storage.len());
429        let mut changed_bits = B::zero();
430        for (a, b) in self.blocks_mut().zip(other.blocks()) {
431            let w = op(*a, b);
432            changed_bits = changed_bits | (*a ^ w);
433            *a = w;
434        }
435        changed_bits != B::zero()
436    }
437
438    /// Iterator over mutable refs to the underlying blocks of data.
439    #[inline]
440    fn blocks_mut(&mut self) -> MutBlocks<B> {
441        // (2)
442        self.storage.iter_mut()
443    }
444
445    /// Iterator over the underlying blocks of data
446    #[inline]
447    pub fn blocks(&self) -> Blocks<B> {
448        // (2)
449        Blocks {
450            iter: self.storage.iter(),
451        }
452    }
453
454    /// Exposes the raw block storage of this `BitVec`.
455    ///
456    /// Only really intended for `BitSet`.
457    #[inline]
458    pub fn storage(&self) -> &[B] {
459        &self.storage
460    }
461
462    /// Exposes the raw block storage of this `BitVec`.
463    ///
464    /// # Safety
465    ///
466    /// Can probably cause unsafety. Only really intended for `BitSet`.
467    #[inline]
468    pub unsafe fn storage_mut(&mut self) -> &mut Vec<B> {
469        &mut self.storage
470    }
471
472    /// Helper for procedures involving spare space in the last block.
473    #[inline]
474    fn last_block_with_mask(&self) -> Option<(B, B)> {
475        let extra_bits = self.len() % B::bits();
476        if extra_bits > 0 {
477            let mask = (B::one() << extra_bits) - B::one();
478            let storage_len = self.storage.len();
479            Some((self.storage[storage_len - 1], mask))
480        } else {
481            None
482        }
483    }
484
485    /// Helper for procedures involving spare space in the last block.
486    #[inline]
487    fn last_block_mut_with_mask(&mut self) -> Option<(&mut B, B)> {
488        let extra_bits = self.len() % B::bits();
489        if extra_bits > 0 {
490            let mask = (B::one() << extra_bits) - B::one();
491            let storage_len = self.storage.len();
492            Some((&mut self.storage[storage_len - 1], mask))
493        } else {
494            None
495        }
496    }
497
498    /// An operation might screw up the unused bits in the last block of the
499    /// `BitVec`. As per (3), it's assumed to be all 0s. This method fixes it up.
500    fn fix_last_block(&mut self) {
501        if let Some((last_block, used_bits)) = self.last_block_mut_with_mask() {
502            *last_block = *last_block & used_bits;
503        }
504    }
505
506    /// Operations such as change detection for xnor, nor and nand are easiest
507    /// to implement when unused bits are all set to 1s.
508    fn fix_last_block_with_ones(&mut self) {
509        if let Some((last_block, used_bits)) = self.last_block_mut_with_mask() {
510            *last_block = *last_block | !used_bits;
511        }
512    }
513
514    /// Check whether last block's invariant is fine.
515    fn is_last_block_fixed(&self) -> bool {
516        if let Some((last_block, used_bits)) = self.last_block_with_mask() {
517            last_block & !used_bits == B::zero()
518        } else {
519            true
520        }
521    }
522
523    /// Ensure the invariant for the last block.
524    ///
525    /// An operation might screw up the unused bits in the last block of the
526    /// `BitVec`.
527    ///
528    /// This method fails in case the last block is not fixed. The check
529    /// is skipped outside testing.
530    #[inline]
531    fn ensure_invariant(&self) {
532        if cfg!(test) {
533            debug_assert!(self.is_last_block_fixed());
534        }
535    }
536
537    /// Retrieves the value at index `i`, or `None` if the index is out of bounds.
538    ///
539    /// # Examples
540    ///
541    /// ```
542    /// use bit_vec::BitVec;
543    ///
544    /// let bv = BitVec::from_bytes(&[0b01100000]);
545    /// assert_eq!(bv.get(0), Some(false));
546    /// assert_eq!(bv.get(1), Some(true));
547    /// assert_eq!(bv.get(100), None);
548    ///
549    /// // Can also use array indexing
550    /// assert_eq!(bv[1], true);
551    /// ```
552    #[inline]
553    pub fn get(&self, i: usize) -> Option<bool> {
554        self.ensure_invariant();
555        if i >= self.nbits {
556            return None;
557        }
558        let w = i / B::bits();
559        let b = i % B::bits();
560        self.storage
561            .get(w)
562            .map(|&block| (block & (B::one() << b)) != B::zero())
563    }
564
565    /// Retrieves the value at index `i`, without doing bounds checking.
566    ///
567    /// For a safe alternative, see `get`.
568    ///
569    /// # Safety
570    ///
571    /// Calling this method with an out-of-bounds index is undefined behavior
572    /// even if the resulting reference is not used.
573    ///
574    /// # Examples
575    ///
576    /// ```
577    /// use bit_vec::BitVec;
578    ///
579    /// let bv = BitVec::from_bytes(&[0b01100000]);
580    /// unsafe {
581    ///     assert_eq!(bv.get_unchecked(0), false);
582    ///     assert_eq!(bv.get_unchecked(1), true);
583    /// }
584    /// ```
585    #[inline]
586    pub unsafe fn get_unchecked(&self, i: usize) -> bool {
587        self.ensure_invariant();
588        let w = i / B::bits();
589        let b = i % B::bits();
590        let block = *self.storage.get_unchecked(w);
591        block & (B::one() << b) != B::zero()
592    }
593
594    /// Retrieves a smart pointer to the value at index `i`, or `None` if the index is out of bounds.
595    ///
596    /// # Examples
597    ///
598    /// ```
599    /// use bit_vec::BitVec;
600    ///
601    /// let mut bv = BitVec::from_bytes(&[0b01100000]);
602    /// *bv.get_mut(0).unwrap() = true;
603    /// *bv.get_mut(1).unwrap() = false;
604    /// assert!(bv.get_mut(100).is_none());
605    /// assert_eq!(bv, BitVec::from_bytes(&[0b10100000]));
606    /// ```
607    #[inline]
608    pub fn get_mut(&mut self, index: usize) -> Option<MutBorrowedBit<B>> {
609        self.get(index).map(move |value| MutBorrowedBit {
610            vec: Rc::new(RefCell::new(self)),
611            index,
612            #[cfg(debug_assertions)]
613            old_value: value,
614            new_value: value,
615        })
616    }
617
618    /// Retrieves a smart pointer to the value at index `i`, without doing bounds checking.
619    ///
620    /// # Safety
621    ///
622    /// Calling this method with out-of-bounds `index` may cause undefined behavior even when
623    /// the result is not used.
624    ///
625    /// # Examples
626    ///
627    /// ```
628    /// use bit_vec::BitVec;
629    ///
630    /// let mut bv = BitVec::from_bytes(&[0b01100000]);
631    /// unsafe {
632    ///     *bv.get_unchecked_mut(0) = true;
633    ///     *bv.get_unchecked_mut(1) = false;
634    /// }
635    /// assert_eq!(bv, BitVec::from_bytes(&[0b10100000]));
636    /// ```
637    #[inline]
638    pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> MutBorrowedBit<B> {
639        let value = self.get_unchecked(index);
640        MutBorrowedBit {
641            #[cfg(debug_assertions)]
642            old_value: value,
643            new_value: value,
644            vec: Rc::new(RefCell::new(self)),
645            index,
646        }
647    }
648
649    /// Sets the value of a bit at an index `i`.
650    ///
651    /// # Panics
652    ///
653    /// Panics if `i` is out of bounds.
654    ///
655    /// # Examples
656    ///
657    /// ```
658    /// use bit_vec::BitVec;
659    ///
660    /// let mut bv = BitVec::from_elem(5, false);
661    /// bv.set(3, true);
662    /// assert_eq!(bv[3], true);
663    /// ```
664    #[inline]
665    pub fn set(&mut self, i: usize, x: bool) {
666        self.ensure_invariant();
667        assert!(
668            i < self.nbits,
669            "index out of bounds: {:?} >= {:?}",
670            i,
671            self.nbits
672        );
673        let w = i / B::bits();
674        let b = i % B::bits();
675        let flag = B::one() << b;
676        let val = if x {
677            self.storage[w] | flag
678        } else {
679            self.storage[w] & !flag
680        };
681        self.storage[w] = val;
682    }
683
684    /// Sets all bits to 1.
685    ///
686    /// # Examples
687    ///
688    /// ```
689    /// use bit_vec::BitVec;
690    ///
691    /// let before = 0b01100000;
692    /// let after  = 0b11111111;
693    ///
694    /// let mut bv = BitVec::from_bytes(&[before]);
695    /// bv.set_all();
696    /// assert_eq!(bv, BitVec::from_bytes(&[after]));
697    /// ```
698    #[inline]
699    pub fn set_all(&mut self) {
700        self.ensure_invariant();
701        for w in &mut self.storage {
702            *w = !B::zero();
703        }
704        self.fix_last_block();
705    }
706
707    /// Flips all bits.
708    ///
709    /// # Examples
710    ///
711    /// ```
712    /// use bit_vec::BitVec;
713    ///
714    /// let before = 0b01100000;
715    /// let after  = 0b10011111;
716    ///
717    /// let mut bv = BitVec::from_bytes(&[before]);
718    /// bv.negate();
719    /// assert_eq!(bv, BitVec::from_bytes(&[after]));
720    /// ```
721    #[inline]
722    pub fn negate(&mut self) {
723        self.ensure_invariant();
724        for w in &mut self.storage {
725            *w = !*w;
726        }
727        self.fix_last_block();
728    }
729
730    /// Calculates the union of two bitvectors. This acts like the bitwise `or`
731    /// function.
732    ///
733    /// Sets `self` to the union of `self` and `other`. Both bitvectors must be
734    /// the same length. Returns `true` if `self` changed.
735    ///
736    /// # Panics
737    ///
738    /// Panics if the bitvectors are of different lengths.
739    ///
740    /// # Examples
741    ///
742    /// ```
743    /// use bit_vec::BitVec;
744    ///
745    /// let a   = 0b01100100;
746    /// let b   = 0b01011010;
747    /// let res = 0b01111110;
748    ///
749    /// let mut a = BitVec::from_bytes(&[a]);
750    /// let b = BitVec::from_bytes(&[b]);
751    ///
752    /// assert!(a.union(&b));
753    /// assert_eq!(a, BitVec::from_bytes(&[res]));
754    /// ```
755    #[deprecated(since = "0.7.0", note = "Please use the 'or' function instead")]
756    #[inline]
757    pub fn union(&mut self, other: &Self) -> bool {
758        self.or(other)
759    }
760
761    /// Calculates the intersection of two bitvectors. This acts like the
762    /// bitwise `and` function.
763    ///
764    /// Sets `self` to the intersection of `self` and `other`. Both bitvectors
765    /// must be the same length. Returns `true` if `self` changed.
766    ///
767    /// # Panics
768    ///
769    /// Panics if the bitvectors are of different lengths.
770    ///
771    /// # Examples
772    ///
773    /// ```
774    /// use bit_vec::BitVec;
775    ///
776    /// let a   = 0b01100100;
777    /// let b   = 0b01011010;
778    /// let res = 0b01000000;
779    ///
780    /// let mut a = BitVec::from_bytes(&[a]);
781    /// let b = BitVec::from_bytes(&[b]);
782    ///
783    /// assert!(a.intersect(&b));
784    /// assert_eq!(a, BitVec::from_bytes(&[res]));
785    /// ```
786    #[deprecated(since = "0.7.0", note = "Please use the 'and' function instead")]
787    #[inline]
788    pub fn intersect(&mut self, other: &Self) -> bool {
789        self.and(other)
790    }
791
792    /// Calculates the bitwise `or` of two bitvectors.
793    ///
794    /// Sets `self` to the union of `self` and `other`. Both bitvectors must be
795    /// the same length. Returns `true` if `self` changed.
796    ///
797    /// # Panics
798    ///
799    /// Panics if the bitvectors are of different lengths.
800    ///
801    /// # Examples
802    ///
803    /// ```
804    /// use bit_vec::BitVec;
805    ///
806    /// let a   = 0b01100100;
807    /// let b   = 0b01011010;
808    /// let res = 0b01111110;
809    ///
810    /// let mut a = BitVec::from_bytes(&[a]);
811    /// let b = BitVec::from_bytes(&[b]);
812    ///
813    /// assert!(a.or(&b));
814    /// assert_eq!(a, BitVec::from_bytes(&[res]));
815    /// ```
816    #[inline]
817    pub fn or(&mut self, other: &Self) -> bool {
818        self.ensure_invariant();
819        debug_assert!(other.is_last_block_fixed());
820        self.process(other, |w1, w2| (w1 | w2))
821    }
822
823    /// Calculates the bitwise `and` of two bitvectors.
824    ///
825    /// Sets `self` to the intersection of `self` and `other`. Both bitvectors
826    /// must be the same length. Returns `true` if `self` changed.
827    ///
828    /// # Panics
829    ///
830    /// Panics if the bitvectors are of different lengths.
831    ///
832    /// # Examples
833    ///
834    /// ```
835    /// use bit_vec::BitVec;
836    ///
837    /// let a   = 0b01100100;
838    /// let b   = 0b01011010;
839    /// let res = 0b01000000;
840    ///
841    /// let mut a = BitVec::from_bytes(&[a]);
842    /// let b = BitVec::from_bytes(&[b]);
843    ///
844    /// assert!(a.and(&b));
845    /// assert_eq!(a, BitVec::from_bytes(&[res]));
846    /// ```
847    #[inline]
848    pub fn and(&mut self, other: &Self) -> bool {
849        self.ensure_invariant();
850        debug_assert!(other.is_last_block_fixed());
851        self.process(other, |w1, w2| (w1 & w2))
852    }
853
854    /// Calculates the difference between two bitvectors.
855    ///
856    /// Sets each element of `self` to the value of that element minus the
857    /// element of `other` at the same index. Both bitvectors must be the same
858    /// length. Returns `true` if `self` changed.
859    ///
860    /// # Panics
861    ///
862    /// Panics if the bitvectors are of different length.
863    ///
864    /// # Examples
865    ///
866    /// ```
867    /// use bit_vec::BitVec;
868    ///
869    /// let a   = 0b01100100;
870    /// let b   = 0b01011010;
871    /// let a_b = 0b00100100; // a - b
872    /// let b_a = 0b00011010; // b - a
873    ///
874    /// let mut bva = BitVec::from_bytes(&[a]);
875    /// let bvb = BitVec::from_bytes(&[b]);
876    ///
877    /// assert!(bva.difference(&bvb));
878    /// assert_eq!(bva, BitVec::from_bytes(&[a_b]));
879    ///
880    /// let bva = BitVec::from_bytes(&[a]);
881    /// let mut bvb = BitVec::from_bytes(&[b]);
882    ///
883    /// assert!(bvb.difference(&bva));
884    /// assert_eq!(bvb, BitVec::from_bytes(&[b_a]));
885    /// ```
886    #[inline]
887    pub fn difference(&mut self, other: &Self) -> bool {
888        self.ensure_invariant();
889        debug_assert!(other.is_last_block_fixed());
890        self.process(other, |w1, w2| (w1 & !w2))
891    }
892
893    /// Calculates the xor of two bitvectors.
894    ///
895    /// Sets `self` to the xor of `self` and `other`. Both bitvectors must be
896    /// the same length. Returns `true` if `self` changed.
897    ///
898    /// # Panics
899    ///
900    /// Panics if the bitvectors are of different length.
901    ///
902    /// # Examples
903    ///
904    /// ```
905    /// use bit_vec::BitVec;
906    ///
907    /// let a   = 0b01100110;
908    /// let b   = 0b01010100;
909    /// let res = 0b00110010;
910    ///
911    /// let mut a = BitVec::from_bytes(&[a]);
912    /// let b = BitVec::from_bytes(&[b]);
913    ///
914    /// assert!(a.xor(&b));
915    /// assert_eq!(a, BitVec::from_bytes(&[res]));
916    /// ```
917    #[inline]
918    pub fn xor(&mut self, other: &Self) -> bool {
919        self.ensure_invariant();
920        debug_assert!(other.is_last_block_fixed());
921        self.process(other, |w1, w2| (w1 ^ w2))
922    }
923
924    /// Calculates the nand of two bitvectors.
925    ///
926    /// Sets `self` to the nand of `self` and `other`. Both bitvectors must be
927    /// the same length. Returns `true` if `self` changed.
928    ///
929    /// # Panics
930    ///
931    /// Panics if the bitvectors are of different length.
932    ///
933    /// # Examples
934    ///
935    /// ```
936    /// use bit_vec::BitVec;
937    ///
938    /// let a   = 0b01100110;
939    /// let b   = 0b01010100;
940    /// let res = 0b10111011;
941    ///
942    /// let mut a = BitVec::from_bytes(&[a]);
943    /// let b = BitVec::from_bytes(&[b]);
944    ///
945    /// assert!(a.nand(&b));
946    /// assert_eq!(a, BitVec::from_bytes(&[res]));
947    /// ```
948    #[inline]
949    pub fn nand(&mut self, other: &Self) -> bool {
950        self.ensure_invariant();
951        debug_assert!(other.is_last_block_fixed());
952        self.fix_last_block_with_ones();
953        let result = self.process(other, |w1, w2| !(w1 & w2));
954        self.fix_last_block();
955        result
956    }
957
958    /// Calculates the nor of two bitvectors.
959    ///
960    /// Sets `self` to the nor of `self` and `other`. Both bitvectors must be
961    /// the same length. Returns `true` if `self` changed.
962    ///
963    /// # Panics
964    ///
965    /// Panics if the bitvectors are of different length.
966    ///
967    /// # Examples
968    ///
969    /// ```
970    /// use bit_vec::BitVec;
971    ///
972    /// let a   = 0b01100110;
973    /// let b   = 0b01010100;
974    /// let res = 0b10001001;
975    ///
976    /// let mut a = BitVec::from_bytes(&[a]);
977    /// let b = BitVec::from_bytes(&[b]);
978    ///
979    /// assert!(a.nor(&b));
980    /// assert_eq!(a, BitVec::from_bytes(&[res]));
981    /// ```
982    #[inline]
983    pub fn nor(&mut self, other: &Self) -> bool {
984        self.ensure_invariant();
985        debug_assert!(other.is_last_block_fixed());
986        self.fix_last_block_with_ones();
987        let result = self.process(other, |w1, w2| !(w1 | w2));
988        self.fix_last_block();
989        result
990    }
991
992    /// Calculates the xnor of two bitvectors.
993    ///
994    /// Sets `self` to the xnor of `self` and `other`. Both bitvectors must be
995    /// the same length. Returns `true` if `self` changed.
996    ///
997    /// # Panics
998    ///
999    /// Panics if the bitvectors are of different length.
1000    ///
1001    /// # Examples
1002    ///
1003    /// ```
1004    /// use bit_vec::BitVec;
1005    ///
1006    /// let a   = 0b01100110;
1007    /// let b   = 0b01010100;
1008    /// let res = 0b11001101;
1009    ///
1010    /// let mut a = BitVec::from_bytes(&[a]);
1011    /// let b = BitVec::from_bytes(&[b]);
1012    ///
1013    /// assert!(a.xnor(&b));
1014    /// assert_eq!(a, BitVec::from_bytes(&[res]));
1015    /// ```
1016    #[inline]
1017    pub fn xnor(&mut self, other: &Self) -> bool {
1018        self.ensure_invariant();
1019        debug_assert!(other.is_last_block_fixed());
1020        self.fix_last_block_with_ones();
1021        let result = self.process(other, |w1, w2| !(w1 ^ w2));
1022        self.fix_last_block();
1023        result
1024    }
1025
1026    /// Returns `true` if all bits are 1.
1027    ///
1028    /// # Examples
1029    ///
1030    /// ```
1031    /// use bit_vec::BitVec;
1032    ///
1033    /// let mut bv = BitVec::from_elem(5, true);
1034    /// assert_eq!(bv.all(), true);
1035    ///
1036    /// bv.set(1, false);
1037    /// assert_eq!(bv.all(), false);
1038    /// ```
1039    #[inline]
1040    pub fn all(&self) -> bool {
1041        self.ensure_invariant();
1042        let mut last_word = !B::zero();
1043        // Check that every block but the last is all-ones...
1044        self.blocks().all(|elem| {
1045            let tmp = last_word;
1046            last_word = elem;
1047            tmp == !B::zero()
1048            // and then check the last one has enough ones
1049        }) && (last_word == mask_for_bits(self.nbits))
1050    }
1051
1052    /// Returns the number of ones in the binary representation.
1053    ///
1054    /// Also known as the
1055    /// [Hamming weight](https://en.wikipedia.org/wiki/Hamming_weight).
1056    ///
1057    /// # Examples
1058    ///
1059    /// ```
1060    /// use bit_vec::BitVec;
1061    ///
1062    /// let mut bv = BitVec::from_elem(100, true);
1063    /// assert_eq!(bv.count_ones(), 100);
1064    ///
1065    /// bv.set(50, false);
1066    /// assert_eq!(bv.count_ones(), 99);
1067    /// ```
1068    #[inline]
1069    pub fn count_ones(&self) -> u64 {
1070        self.ensure_invariant();
1071        // Add the number of ones of each block.
1072        self.blocks().map(|elem| elem.count_ones() as u64).sum()
1073    }
1074
1075    /// Returns the number of zeros in the binary representation.
1076    ///
1077    /// Also known as the opposite of
1078    /// [Hamming weight](https://en.wikipedia.org/wiki/Hamming_weight).
1079    ///
1080    /// # Examples
1081    ///
1082    /// ```
1083    /// use bit_vec::BitVec;
1084    ///
1085    /// let mut bv = BitVec::from_elem(100, false);
1086    /// assert_eq!(bv.count_zeros(), 100);
1087    ///
1088    /// bv.set(50, true);
1089    /// assert_eq!(bv.count_zeros(), 99);
1090    /// ```
1091    #[inline]
1092    pub fn count_zeros(&self) -> u64 {
1093        self.ensure_invariant();
1094        // Add the number of zeros of each block.
1095        let extra_zeros = (B::bits() - (self.len() % B::bits())) % B::bits();
1096        self.blocks()
1097            .map(|elem| elem.count_zeros() as u64)
1098            .sum::<u64>()
1099            - extra_zeros as u64
1100    }
1101
1102    /// Returns an iterator over the elements of the vector in order.
1103    ///
1104    /// # Examples
1105    ///
1106    /// ```
1107    /// use bit_vec::BitVec;
1108    ///
1109    /// let bv = BitVec::from_bytes(&[0b01110100, 0b10010010]);
1110    /// assert_eq!(bv.iter().filter(|x| *x).count(), 7);
1111    /// ```
1112    #[inline]
1113    pub fn iter(&self) -> Iter<B> {
1114        self.ensure_invariant();
1115        Iter {
1116            bit_vec: self,
1117            range: 0..self.nbits,
1118        }
1119    }
1120
1121    /// Returns an iterator over mutable smart pointers to the elements of the vector in order.
1122    ///
1123    /// # Examples
1124    ///
1125    /// ```
1126    /// use bit_vec::BitVec;
1127    ///
1128    /// let mut a = BitVec::from_elem(8, false);
1129    /// a.iter_mut().enumerate().for_each(|(index, mut bit)| {
1130    ///     *bit = if index % 2 == 1 { true } else { false };
1131    /// });
1132    /// assert!(a.eq_vec(&[
1133    ///    false, true, false, true, false, true, false, true
1134    /// ]));
1135    /// ```
1136    #[inline]
1137    pub fn iter_mut(&mut self) -> IterMut<B> {
1138        self.ensure_invariant();
1139        let nbits = self.nbits;
1140        IterMut {
1141            vec: Rc::new(RefCell::new(self)),
1142            range: 0..nbits,
1143        }
1144    }
1145
1146    /// Moves all bits from `other` into `Self`, leaving `other` empty.
1147    ///
1148    /// # Examples
1149    ///
1150    /// ```
1151    /// use bit_vec::BitVec;
1152    ///
1153    /// let mut a = BitVec::from_bytes(&[0b10000000]);
1154    /// let mut b = BitVec::from_bytes(&[0b01100001]);
1155    ///
1156    /// a.append(&mut b);
1157    ///
1158    /// assert_eq!(a.len(), 16);
1159    /// assert_eq!(b.len(), 0);
1160    /// assert!(a.eq_vec(&[true, false, false, false, false, false, false, false,
1161    ///                    false, true, true, false, false, false, false, true]));
1162    /// ```
1163    pub fn append(&mut self, other: &mut Self) {
1164        self.ensure_invariant();
1165        debug_assert!(other.is_last_block_fixed());
1166
1167        let b = self.len() % B::bits();
1168        let o = other.len() % B::bits();
1169        let will_overflow = (b + o > B::bits()) || (o == 0 && b != 0);
1170
1171        self.nbits += other.len();
1172        other.nbits = 0;
1173
1174        if b == 0 {
1175            self.storage.append(&mut other.storage);
1176        } else {
1177            self.storage.reserve(other.storage.len());
1178
1179            for block in other.storage.drain(..) {
1180                {
1181                    let last = self.storage.last_mut().unwrap();
1182                    *last = *last | (block << b);
1183                }
1184                self.storage.push(block >> (B::bits() - b));
1185            }
1186
1187            // Remove additional block if the last shift did not overflow
1188            if !will_overflow {
1189                self.storage.pop();
1190            }
1191        }
1192    }
1193
1194    /// Splits the `BitVec` into two at the given bit,
1195    /// retaining the first half in-place and returning the second one.
1196    ///
1197    /// # Panics
1198    ///
1199    /// Panics if `at` is out of bounds.
1200    ///
1201    /// # Examples
1202    ///
1203    /// ```
1204    /// use bit_vec::BitVec;
1205    /// let mut a = BitVec::new();
1206    /// a.push(true);
1207    /// a.push(false);
1208    /// a.push(false);
1209    /// a.push(true);
1210    ///
1211    /// let b = a.split_off(2);
1212    ///
1213    /// assert_eq!(a.len(), 2);
1214    /// assert_eq!(b.len(), 2);
1215    /// assert!(a.eq_vec(&[true, false]));
1216    /// assert!(b.eq_vec(&[false, true]));
1217    /// ```
1218    pub fn split_off(&mut self, at: usize) -> Self {
1219        self.ensure_invariant();
1220        assert!(at <= self.len(), "`at` out of bounds");
1221
1222        let mut other = BitVec::<B>::default();
1223
1224        if at == 0 {
1225            mem::swap(self, &mut other);
1226            return other;
1227        } else if at == self.len() {
1228            return other;
1229        }
1230
1231        let w = at / B::bits();
1232        let b = at % B::bits();
1233        other.nbits = self.nbits - at;
1234        self.nbits = at;
1235        if b == 0 {
1236            // Split at block boundary
1237            other.storage = self.storage.split_off(w);
1238        } else {
1239            other.storage.reserve(self.storage.len() - w);
1240
1241            {
1242                let mut iter = self.storage[w..].iter();
1243                let mut last = *iter.next().unwrap();
1244                for &cur in iter {
1245                    other.storage.push((last >> b) | (cur << (B::bits() - b)));
1246                    last = cur;
1247                }
1248                other.storage.push(last >> b);
1249            }
1250
1251            self.storage.truncate(w + 1);
1252            self.fix_last_block();
1253        }
1254
1255        other
1256    }
1257
1258    /// Returns `true` if all bits are 0.
1259    ///
1260    /// # Examples
1261    ///
1262    /// ```
1263    /// use bit_vec::BitVec;
1264    ///
1265    /// let mut bv = BitVec::from_elem(10, false);
1266    /// assert_eq!(bv.none(), true);
1267    ///
1268    /// bv.set(3, true);
1269    /// assert_eq!(bv.none(), false);
1270    /// ```
1271    #[inline]
1272    pub fn none(&self) -> bool {
1273        self.blocks().all(|w| w == B::zero())
1274    }
1275
1276    /// Returns `true` if any bit is 1.
1277    ///
1278    /// # Examples
1279    ///
1280    /// ```
1281    /// use bit_vec::BitVec;
1282    ///
1283    /// let mut bv = BitVec::from_elem(10, false);
1284    /// assert_eq!(bv.any(), false);
1285    ///
1286    /// bv.set(3, true);
1287    /// assert_eq!(bv.any(), true);
1288    /// ```
1289    #[inline]
1290    pub fn any(&self) -> bool {
1291        !self.none()
1292    }
1293
1294    /// Organises the bits into bytes, such that the first bit in the
1295    /// `BitVec` becomes the high-order bit of the first byte. If the
1296    /// size of the `BitVec` is not a multiple of eight then trailing bits
1297    /// will be filled-in with `false`.
1298    ///
1299    /// # Examples
1300    ///
1301    /// ```
1302    /// use bit_vec::BitVec;
1303    ///
1304    /// let mut bv = BitVec::from_elem(3, true);
1305    /// bv.set(1, false);
1306    ///
1307    /// assert_eq!(bv.to_bytes(), [0b10100000]);
1308    ///
1309    /// let mut bv = BitVec::from_elem(9, false);
1310    /// bv.set(2, true);
1311    /// bv.set(8, true);
1312    ///
1313    /// assert_eq!(bv.to_bytes(), [0b00100000, 0b10000000]);
1314    /// ```
1315    pub fn to_bytes(&self) -> Vec<u8> {
1316        self.ensure_invariant();
1317        // Oh lord, we're mapping this to bytes bit-by-bit!
1318        fn bit<B: BitBlock>(bit_vec: &BitVec<B>, byte: usize, bit: usize) -> u8 {
1319            let offset = byte * 8 + bit;
1320            if offset >= bit_vec.nbits {
1321                0
1322            } else {
1323                (bit_vec[offset] as u8) << (7 - bit)
1324            }
1325        }
1326
1327        let len = self.nbits / 8 + if self.nbits % 8 == 0 { 0 } else { 1 };
1328        (0..len)
1329            .map(|i| {
1330                bit(self, i, 0)
1331                    | bit(self, i, 1)
1332                    | bit(self, i, 2)
1333                    | bit(self, i, 3)
1334                    | bit(self, i, 4)
1335                    | bit(self, i, 5)
1336                    | bit(self, i, 6)
1337                    | bit(self, i, 7)
1338            })
1339            .collect()
1340    }
1341
1342    /// Compares a `BitVec` to a slice of `bool`s.
1343    /// Both the `BitVec` and slice must have the same length.
1344    ///
1345    /// # Panics
1346    ///
1347    /// Panics if the `BitVec` and slice are of different length.
1348    ///
1349    /// # Examples
1350    ///
1351    /// ```
1352    /// use bit_vec::BitVec;
1353    ///
1354    /// let bv = BitVec::from_bytes(&[0b10100000]);
1355    ///
1356    /// assert!(bv.eq_vec(&[true, false, true, false,
1357    ///                     false, false, false, false]));
1358    /// ```
1359    #[inline]
1360    pub fn eq_vec(&self, v: &[bool]) -> bool {
1361        assert_eq!(self.nbits, v.len());
1362        self.iter().zip(v.iter().cloned()).all(|(b1, b2)| b1 == b2)
1363    }
1364
1365    /// Shortens a `BitVec`, dropping excess elements.
1366    ///
1367    /// If `len` is greater than the vector's current length, this has no
1368    /// effect.
1369    ///
1370    /// # Examples
1371    ///
1372    /// ```
1373    /// use bit_vec::BitVec;
1374    ///
1375    /// let mut bv = BitVec::from_bytes(&[0b01001011]);
1376    /// bv.truncate(2);
1377    /// assert!(bv.eq_vec(&[false, true]));
1378    /// ```
1379    #[inline]
1380    pub fn truncate(&mut self, len: usize) {
1381        self.ensure_invariant();
1382        if len < self.len() {
1383            self.nbits = len;
1384            // This fixes (2).
1385            self.storage.truncate(blocks_for_bits::<B>(len));
1386            self.fix_last_block();
1387        }
1388    }
1389
1390    /// Reserves capacity for at least `additional` more bits to be inserted in the given
1391    /// `BitVec`. The collection may reserve more space to avoid frequent reallocations.
1392    ///
1393    /// # Panics
1394    ///
1395    /// Panics if the new capacity overflows `usize`.
1396    ///
1397    /// # Examples
1398    ///
1399    /// ```
1400    /// use bit_vec::BitVec;
1401    ///
1402    /// let mut bv = BitVec::from_elem(3, false);
1403    /// bv.reserve(10);
1404    /// assert_eq!(bv.len(), 3);
1405    /// assert!(bv.capacity() >= 13);
1406    /// ```
1407    #[inline]
1408    pub fn reserve(&mut self, additional: usize) {
1409        let desired_cap = self
1410            .len()
1411            .checked_add(additional)
1412            .expect("capacity overflow");
1413        let storage_len = self.storage.len();
1414        if desired_cap > self.capacity() {
1415            self.storage
1416                .reserve(blocks_for_bits::<B>(desired_cap) - storage_len);
1417        }
1418    }
1419
1420    /// Reserves the minimum capacity for exactly `additional` more bits to be inserted in the
1421    /// given `BitVec`. Does nothing if the capacity is already sufficient.
1422    ///
1423    /// Note that the allocator may give the collection more space than it requests. Therefore
1424    /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
1425    /// insertions are expected.
1426    ///
1427    /// # Panics
1428    ///
1429    /// Panics if the new capacity overflows `usize`.
1430    ///
1431    /// # Examples
1432    ///
1433    /// ```
1434    /// use bit_vec::BitVec;
1435    ///
1436    /// let mut bv = BitVec::from_elem(3, false);
1437    /// bv.reserve(10);
1438    /// assert_eq!(bv.len(), 3);
1439    /// assert!(bv.capacity() >= 13);
1440    /// ```
1441    #[inline]
1442    pub fn reserve_exact(&mut self, additional: usize) {
1443        let desired_cap = self
1444            .len()
1445            .checked_add(additional)
1446            .expect("capacity overflow");
1447        let storage_len = self.storage.len();
1448        if desired_cap > self.capacity() {
1449            self.storage
1450                .reserve_exact(blocks_for_bits::<B>(desired_cap) - storage_len);
1451        }
1452    }
1453
1454    /// Returns the capacity in bits for this bit vector. Inserting any
1455    /// element less than this amount will not trigger a resizing.
1456    ///
1457    /// # Examples
1458    ///
1459    /// ```
1460    /// use bit_vec::BitVec;
1461    ///
1462    /// let mut bv = BitVec::new();
1463    /// bv.reserve(10);
1464    /// assert!(bv.capacity() >= 10);
1465    /// ```
1466    #[inline]
1467    pub fn capacity(&self) -> usize {
1468        self.storage.capacity().saturating_mul(B::bits())
1469    }
1470
1471    /// Grows the `BitVec` in-place, adding `n` copies of `value` to the `BitVec`.
1472    ///
1473    /// # Panics
1474    ///
1475    /// Panics if the new len overflows a `usize`.
1476    ///
1477    /// # Examples
1478    ///
1479    /// ```
1480    /// use bit_vec::BitVec;
1481    ///
1482    /// let mut bv = BitVec::from_bytes(&[0b01001011]);
1483    /// bv.grow(2, true);
1484    /// assert_eq!(bv.len(), 10);
1485    /// assert_eq!(bv.to_bytes(), [0b01001011, 0b11000000]);
1486    /// ```
1487    pub fn grow(&mut self, n: usize, value: bool) {
1488        self.ensure_invariant();
1489
1490        // Note: we just bulk set all the bits in the last word in this fn in multiple places
1491        // which is technically wrong if not all of these bits are to be used. However, at the end
1492        // of this fn we call `fix_last_block` at the end of this fn, which should fix this.
1493
1494        let new_nbits = self.nbits.checked_add(n).expect("capacity overflow");
1495        let new_nblocks = blocks_for_bits::<B>(new_nbits);
1496        let full_value = if value { !B::zero() } else { B::zero() };
1497
1498        // Correct the old tail word, setting or clearing formerly unused bits
1499        let num_cur_blocks = blocks_for_bits::<B>(self.nbits);
1500        if self.nbits % B::bits() > 0 {
1501            let mask = mask_for_bits::<B>(self.nbits);
1502            if value {
1503                let block = &mut self.storage[num_cur_blocks - 1];
1504                *block = *block | !mask;
1505            } else {
1506                // Extra bits are already zero by invariant.
1507            }
1508        }
1509
1510        // Fill in words after the old tail word
1511        let stop_idx = cmp::min(self.storage.len(), new_nblocks);
1512        for idx in num_cur_blocks..stop_idx {
1513            self.storage[idx] = full_value;
1514        }
1515
1516        // Allocate new words, if needed
1517        if new_nblocks > self.storage.len() {
1518            let to_add = new_nblocks - self.storage.len();
1519            self.storage.extend(repeat(full_value).take(to_add));
1520        }
1521
1522        // Adjust internal bit count
1523        self.nbits = new_nbits;
1524
1525        self.fix_last_block();
1526    }
1527
1528    /// Removes the last bit from the `BitVec`, and returns it. Returns `None` if the `BitVec` is empty.
1529    ///
1530    /// # Examples
1531    ///
1532    /// ```
1533    /// use bit_vec::BitVec;
1534    ///
1535    /// let mut bv = BitVec::from_bytes(&[0b01001001]);
1536    /// assert_eq!(bv.pop(), Some(true));
1537    /// assert_eq!(bv.pop(), Some(false));
1538    /// assert_eq!(bv.len(), 6);
1539    /// ```
1540    #[inline]
1541    pub fn pop(&mut self) -> Option<bool> {
1542        self.ensure_invariant();
1543
1544        if self.is_empty() {
1545            None
1546        } else {
1547            let i = self.nbits - 1;
1548            let ret = self[i];
1549            // (3)
1550            self.set(i, false);
1551            self.nbits = i;
1552            if self.nbits % B::bits() == 0 {
1553                // (2)
1554                self.storage.pop();
1555            }
1556            Some(ret)
1557        }
1558    }
1559
1560    /// Pushes a `bool` onto the end.
1561    ///
1562    /// # Examples
1563    ///
1564    /// ```
1565    /// use bit_vec::BitVec;
1566    ///
1567    /// let mut bv = BitVec::new();
1568    /// bv.push(true);
1569    /// bv.push(false);
1570    /// assert!(bv.eq_vec(&[true, false]));
1571    /// ```
1572    #[inline]
1573    pub fn push(&mut self, elem: bool) {
1574        if self.nbits % B::bits() == 0 {
1575            self.storage.push(B::zero());
1576        }
1577        let insert_pos = self.nbits;
1578        self.nbits = self.nbits.checked_add(1).expect("Capacity overflow");
1579        self.set(insert_pos, elem);
1580    }
1581
1582    /// Returns the total number of bits in this vector
1583    #[inline]
1584    pub fn len(&self) -> usize {
1585        self.nbits
1586    }
1587
1588    /// Sets the number of bits that this `BitVec` considers initialized.
1589    ///
1590    /// # Safety
1591    ///
1592    /// Almost certainly can cause bad stuff. Only really intended for `BitSet`.
1593    #[inline]
1594    pub unsafe fn set_len(&mut self, len: usize) {
1595        self.nbits = len;
1596    }
1597
1598    /// Returns true if there are no bits in this vector
1599    #[inline]
1600    pub fn is_empty(&self) -> bool {
1601        self.len() == 0
1602    }
1603
1604    /// Clears all bits in this vector.
1605    #[inline]
1606    pub fn clear(&mut self) {
1607        self.ensure_invariant();
1608        for w in &mut self.storage {
1609            *w = B::zero();
1610        }
1611    }
1612
1613    /// Shrinks the capacity of the underlying storage as much as
1614    /// possible.
1615    ///
1616    /// It will drop down as close as possible to the length but the
1617    /// allocator may still inform the underlying storage that there
1618    /// is space for a few more elements/bits.
1619    pub fn shrink_to_fit(&mut self) {
1620        self.storage.shrink_to_fit();
1621    }
1622}
1623
1624impl<B: BitBlock> Default for BitVec<B> {
1625    #[inline]
1626    fn default() -> Self {
1627        BitVec {
1628            storage: Vec::new(),
1629            nbits: 0,
1630        }
1631    }
1632}
1633
1634impl<B: BitBlock> FromIterator<bool> for BitVec<B> {
1635    #[inline]
1636    fn from_iter<I: IntoIterator<Item = bool>>(iter: I) -> Self {
1637        let mut ret: Self = Default::default();
1638        ret.extend(iter);
1639        ret
1640    }
1641}
1642
1643impl<B: BitBlock> Extend<bool> for BitVec<B> {
1644    #[inline]
1645    fn extend<I: IntoIterator<Item = bool>>(&mut self, iterable: I) {
1646        self.ensure_invariant();
1647        let iterator = iterable.into_iter();
1648        let (min, _) = iterator.size_hint();
1649        self.reserve(min);
1650        for element in iterator {
1651            self.push(element)
1652        }
1653    }
1654}
1655
1656impl<B: BitBlock> Clone for BitVec<B> {
1657    #[inline]
1658    fn clone(&self) -> Self {
1659        self.ensure_invariant();
1660        BitVec {
1661            storage: self.storage.clone(),
1662            nbits: self.nbits,
1663        }
1664    }
1665
1666    #[inline]
1667    fn clone_from(&mut self, source: &Self) {
1668        debug_assert!(source.is_last_block_fixed());
1669        self.nbits = source.nbits;
1670        self.storage.clone_from(&source.storage);
1671    }
1672}
1673
1674impl<B: BitBlock> PartialOrd for BitVec<B> {
1675    #[inline]
1676    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1677        Some(self.cmp(other))
1678    }
1679}
1680
1681impl<B: BitBlock> Ord for BitVec<B> {
1682    #[inline]
1683    fn cmp(&self, other: &Self) -> Ordering {
1684        self.ensure_invariant();
1685        debug_assert!(other.is_last_block_fixed());
1686        let mut a = self.iter();
1687        let mut b = other.iter();
1688        loop {
1689            match (a.next(), b.next()) {
1690                (Some(x), Some(y)) => match x.cmp(&y) {
1691                    Ordering::Equal => {}
1692                    otherwise => return otherwise,
1693                },
1694                (None, None) => return Ordering::Equal,
1695                (None, _) => return Ordering::Less,
1696                (_, None) => return Ordering::Greater,
1697            }
1698        }
1699    }
1700}
1701
1702impl<B: BitBlock> fmt::Display for BitVec<B> {
1703    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1704        self.ensure_invariant();
1705        for bit in self {
1706            fmt.write_char(if bit { '1' } else { '0' })?;
1707        }
1708        Ok(())
1709    }
1710}
1711
1712impl<B: BitBlock> fmt::Debug for BitVec<B> {
1713    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1714        self.ensure_invariant();
1715        let mut storage = String::with_capacity(self.len() + self.len() / B::bits());
1716        for (i, bit) in self.iter().enumerate() {
1717            if i != 0 && i % B::bits() == 0 {
1718                storage.push(' ');
1719            }
1720            storage.push(if bit { '1' } else { '0' });
1721        }
1722        fmt.debug_struct("BitVec")
1723            .field("storage", &storage)
1724            .field("nbits", &self.nbits)
1725            .finish()
1726    }
1727}
1728
1729impl<B: BitBlock> hash::Hash for BitVec<B> {
1730    #[inline]
1731    fn hash<H: hash::Hasher>(&self, state: &mut H) {
1732        self.ensure_invariant();
1733        self.nbits.hash(state);
1734        for elem in self.blocks() {
1735            elem.hash(state);
1736        }
1737    }
1738}
1739
1740impl<B: BitBlock> cmp::PartialEq for BitVec<B> {
1741    #[inline]
1742    fn eq(&self, other: &Self) -> bool {
1743        if self.nbits != other.nbits {
1744            self.ensure_invariant();
1745            other.ensure_invariant();
1746            return false;
1747        }
1748        self.blocks().zip(other.blocks()).all(|(w1, w2)| w1 == w2)
1749    }
1750}
1751
1752impl<B: BitBlock> cmp::Eq for BitVec<B> {}
1753
1754/// An iterator for `BitVec`.
1755#[derive(Clone)]
1756pub struct Iter<'a, B: 'a = u32> {
1757    bit_vec: &'a BitVec<B>,
1758    range: Range<usize>,
1759}
1760
1761#[derive(Debug)]
1762pub struct MutBorrowedBit<'a, B: 'a + BitBlock> {
1763    vec: Rc<RefCell<&'a mut BitVec<B>>>,
1764    index: usize,
1765    #[cfg(debug_assertions)]
1766    old_value: bool,
1767    new_value: bool,
1768}
1769
1770/// An iterator for mutable references to the bits in a `BitVec`.
1771pub struct IterMut<'a, B: 'a + BitBlock = u32> {
1772    vec: Rc<RefCell<&'a mut BitVec<B>>>,
1773    range: Range<usize>,
1774}
1775
1776impl<'a, B: 'a + BitBlock> IterMut<'a, B> {
1777    fn get(&mut self, index: Option<usize>) -> Option<MutBorrowedBit<'a, B>> {
1778        let index = index?;
1779        let value = (*self.vec).borrow().get(index)?;
1780        Some(MutBorrowedBit {
1781            vec: self.vec.clone(),
1782            index,
1783            #[cfg(debug_assertions)]
1784            old_value: value,
1785            new_value: value,
1786        })
1787    }
1788}
1789
1790impl<'a, B: BitBlock> Deref for MutBorrowedBit<'a, B> {
1791    type Target = bool;
1792
1793    fn deref(&self) -> &Self::Target {
1794        &self.new_value
1795    }
1796}
1797
1798impl<'a, B: BitBlock> DerefMut for MutBorrowedBit<'a, B> {
1799    fn deref_mut(&mut self) -> &mut Self::Target {
1800        &mut self.new_value
1801    }
1802}
1803
1804impl<'a, B: BitBlock> Drop for MutBorrowedBit<'a, B> {
1805    fn drop(&mut self) {
1806        let mut vec = (*self.vec).borrow_mut();
1807        #[cfg(debug_assertions)]
1808        debug_assert_eq!(
1809            Some(self.old_value),
1810            vec.get(self.index),
1811            "Mutably-borrowed bit was modified externally!"
1812        );
1813        vec.set(self.index, self.new_value);
1814    }
1815}
1816
1817impl<'a, B: BitBlock> Iterator for Iter<'a, B> {
1818    type Item = bool;
1819
1820    #[inline]
1821    fn next(&mut self) -> Option<bool> {
1822        // NB: indexing is slow for extern crates when it has to go through &TRUE or &FALSE
1823        // variables.  get is more direct, and unwrap is fine since we're sure of the range.
1824        self.range.next().map(|i| self.bit_vec.get(i).unwrap())
1825    }
1826
1827    fn size_hint(&self) -> (usize, Option<usize>) {
1828        self.range.size_hint()
1829    }
1830}
1831
1832impl<'a, B: BitBlock> Iterator for IterMut<'a, B> {
1833    type Item = MutBorrowedBit<'a, B>;
1834
1835    #[inline]
1836    fn next(&mut self) -> Option<Self::Item> {
1837        let index = self.range.next();
1838        self.get(index)
1839    }
1840
1841    fn size_hint(&self) -> (usize, Option<usize>) {
1842        self.range.size_hint()
1843    }
1844}
1845
1846impl<'a, B: BitBlock> DoubleEndedIterator for Iter<'a, B> {
1847    #[inline]
1848    fn next_back(&mut self) -> Option<bool> {
1849        self.range.next_back().map(|i| self.bit_vec.get(i).unwrap())
1850    }
1851}
1852
1853impl<'a, B: BitBlock> DoubleEndedIterator for IterMut<'a, B> {
1854    #[inline]
1855    fn next_back(&mut self) -> Option<Self::Item> {
1856        let index = self.range.next_back();
1857        self.get(index)
1858    }
1859}
1860
1861impl<'a, B: BitBlock> ExactSizeIterator for Iter<'a, B> {}
1862
1863impl<'a, B: BitBlock> ExactSizeIterator for IterMut<'a, B> {}
1864
1865impl<'a, B: BitBlock> IntoIterator for &'a BitVec<B> {
1866    type Item = bool;
1867    type IntoIter = Iter<'a, B>;
1868
1869    #[inline]
1870    fn into_iter(self) -> Iter<'a, B> {
1871        self.iter()
1872    }
1873}
1874
1875pub struct IntoIter<B = u32> {
1876    bit_vec: BitVec<B>,
1877    range: Range<usize>,
1878}
1879
1880impl<B: BitBlock> Iterator for IntoIter<B> {
1881    type Item = bool;
1882
1883    #[inline]
1884    fn next(&mut self) -> Option<bool> {
1885        self.range.next().map(|i| self.bit_vec.get(i).unwrap())
1886    }
1887}
1888
1889impl<B: BitBlock> DoubleEndedIterator for IntoIter<B> {
1890    #[inline]
1891    fn next_back(&mut self) -> Option<bool> {
1892        self.range.next_back().map(|i| self.bit_vec.get(i).unwrap())
1893    }
1894}
1895
1896impl<B: BitBlock> ExactSizeIterator for IntoIter<B> {}
1897
1898impl<B: BitBlock> IntoIterator for BitVec<B> {
1899    type Item = bool;
1900    type IntoIter = IntoIter<B>;
1901
1902    #[inline]
1903    fn into_iter(self) -> IntoIter<B> {
1904        let nbits = self.nbits;
1905        IntoIter {
1906            bit_vec: self,
1907            range: 0..nbits,
1908        }
1909    }
1910}
1911
1912/// An iterator over the blocks of a `BitVec`.
1913#[derive(Clone)]
1914pub struct Blocks<'a, B: 'a> {
1915    iter: slice::Iter<'a, B>,
1916}
1917
1918impl<'a, B: BitBlock> Iterator for Blocks<'a, B> {
1919    type Item = B;
1920
1921    #[inline]
1922    fn next(&mut self) -> Option<B> {
1923        self.iter.next().cloned()
1924    }
1925
1926    #[inline]
1927    fn size_hint(&self) -> (usize, Option<usize>) {
1928        self.iter.size_hint()
1929    }
1930}
1931
1932impl<'a, B: BitBlock> DoubleEndedIterator for Blocks<'a, B> {
1933    #[inline]
1934    fn next_back(&mut self) -> Option<B> {
1935        self.iter.next_back().cloned()
1936    }
1937}
1938
1939impl<'a, B: BitBlock> ExactSizeIterator for Blocks<'a, B> {}
1940
1941#[cfg(test)]
1942mod tests {
1943    use super::{BitVec, Iter, Vec};
1944
1945    // This is stupid, but I want to differentiate from a "random" 32
1946    const U32_BITS: usize = 32;
1947
1948    #[test]
1949    fn test_display_output() {
1950        assert_eq!(format!("{}", BitVec::new()), "");
1951        assert_eq!(format!("{}", BitVec::from_elem(1, true)), "1");
1952        assert_eq!(format!("{}", BitVec::from_elem(8, false)), "00000000")
1953    }
1954
1955    #[test]
1956    fn test_debug_output() {
1957        assert_eq!(
1958            format!("{:?}", BitVec::new()),
1959            "BitVec { storage: \"\", nbits: 0 }"
1960        );
1961        assert_eq!(
1962            format!("{:?}", BitVec::from_elem(1, true)),
1963            "BitVec { storage: \"1\", nbits: 1 }"
1964        );
1965        assert_eq!(
1966            format!("{:?}", BitVec::from_elem(8, false)),
1967            "BitVec { storage: \"00000000\", nbits: 8 }"
1968        );
1969        assert_eq!(
1970            format!("{:?}", BitVec::from_elem(33, true)),
1971            "BitVec { storage: \"11111111111111111111111111111111 1\", nbits: 33 }"
1972        );
1973        assert_eq!(
1974            format!(
1975                "{:?}",
1976                BitVec::from_bytes(&[0b111, 0b000, 0b1110, 0b0001, 0b11111111, 0b00000000])
1977            ),
1978            "BitVec { storage: \"00000111000000000000111000000001 1111111100000000\", nbits: 48 }"
1979        )
1980    }
1981
1982    #[test]
1983    fn test_0_elements() {
1984        let act = BitVec::new();
1985        let exp = Vec::new();
1986        assert!(act.eq_vec(&exp));
1987        assert!(act.none() && act.all());
1988    }
1989
1990    #[test]
1991    fn test_1_element() {
1992        let mut act = BitVec::from_elem(1, false);
1993        assert!(act.eq_vec(&[false]));
1994        assert!(act.none() && !act.all());
1995        act = BitVec::from_elem(1, true);
1996        assert!(act.eq_vec(&[true]));
1997        assert!(!act.none() && act.all());
1998    }
1999
2000    #[test]
2001    fn test_2_elements() {
2002        let mut b = BitVec::from_elem(2, false);
2003        b.set(0, true);
2004        b.set(1, false);
2005        assert_eq!(format!("{}", b), "10");
2006        assert!(!b.none() && !b.all());
2007    }
2008
2009    #[test]
2010    fn test_10_elements() {
2011        // all 0
2012
2013        let mut act = BitVec::from_elem(10, false);
2014        assert!(
2015            (act.eq_vec(&[false, false, false, false, false, false, false, false, false, false]))
2016        );
2017        assert!(act.none() && !act.all());
2018        // all 1
2019
2020        act = BitVec::from_elem(10, true);
2021        assert!((act.eq_vec(&[true, true, true, true, true, true, true, true, true, true])));
2022        assert!(!act.none() && act.all());
2023        // mixed
2024
2025        act = BitVec::from_elem(10, false);
2026        act.set(0, true);
2027        act.set(1, true);
2028        act.set(2, true);
2029        act.set(3, true);
2030        act.set(4, true);
2031        assert!((act.eq_vec(&[true, true, true, true, true, false, false, false, false, false])));
2032        assert!(!act.none() && !act.all());
2033        // mixed
2034
2035        act = BitVec::from_elem(10, false);
2036        act.set(5, true);
2037        act.set(6, true);
2038        act.set(7, true);
2039        act.set(8, true);
2040        act.set(9, true);
2041        assert!((act.eq_vec(&[false, false, false, false, false, true, true, true, true, true])));
2042        assert!(!act.none() && !act.all());
2043        // mixed
2044
2045        act = BitVec::from_elem(10, false);
2046        act.set(0, true);
2047        act.set(3, true);
2048        act.set(6, true);
2049        act.set(9, true);
2050        assert!((act.eq_vec(&[true, false, false, true, false, false, true, false, false, true])));
2051        assert!(!act.none() && !act.all());
2052    }
2053
2054    #[test]
2055    fn test_31_elements() {
2056        // all 0
2057
2058        let mut act = BitVec::from_elem(31, false);
2059        assert!(act.eq_vec(&[
2060            false, false, false, false, false, false, false, false, false, false, false, false,
2061            false, false, false, false, false, false, false, false, false, false, false, false,
2062            false, false, false, false, false, false, false
2063        ]));
2064        assert!(act.none() && !act.all());
2065        // all 1
2066
2067        act = BitVec::from_elem(31, true);
2068        assert!(act.eq_vec(&[
2069            true, true, true, true, true, true, true, true, true, true, true, true, true, true,
2070            true, true, true, true, true, true, true, true, true, true, true, true, true, true,
2071            true, true, true
2072        ]));
2073        assert!(!act.none() && act.all());
2074        // mixed
2075
2076        act = BitVec::from_elem(31, false);
2077        act.set(0, true);
2078        act.set(1, true);
2079        act.set(2, true);
2080        act.set(3, true);
2081        act.set(4, true);
2082        act.set(5, true);
2083        act.set(6, true);
2084        act.set(7, true);
2085        assert!(act.eq_vec(&[
2086            true, true, true, true, true, true, true, true, false, false, false, false, false,
2087            false, false, false, false, false, false, false, false, false, false, false, false,
2088            false, false, false, false, false, false
2089        ]));
2090        assert!(!act.none() && !act.all());
2091        // mixed
2092
2093        act = BitVec::from_elem(31, false);
2094        act.set(16, true);
2095        act.set(17, true);
2096        act.set(18, true);
2097        act.set(19, true);
2098        act.set(20, true);
2099        act.set(21, true);
2100        act.set(22, true);
2101        act.set(23, true);
2102        assert!(act.eq_vec(&[
2103            false, false, false, false, false, false, false, false, false, false, false, false,
2104            false, false, false, false, true, true, true, true, true, true, true, true, false,
2105            false, false, false, false, false, false
2106        ]));
2107        assert!(!act.none() && !act.all());
2108        // mixed
2109
2110        act = BitVec::from_elem(31, false);
2111        act.set(24, true);
2112        act.set(25, true);
2113        act.set(26, true);
2114        act.set(27, true);
2115        act.set(28, true);
2116        act.set(29, true);
2117        act.set(30, true);
2118        assert!(act.eq_vec(&[
2119            false, false, false, false, false, false, false, false, false, false, false, false,
2120            false, false, false, false, false, false, false, false, false, false, false, false,
2121            true, true, true, true, true, true, true
2122        ]));
2123        assert!(!act.none() && !act.all());
2124        // mixed
2125
2126        act = BitVec::from_elem(31, false);
2127        act.set(3, true);
2128        act.set(17, true);
2129        act.set(30, true);
2130        assert!(act.eq_vec(&[
2131            false, false, false, true, false, false, false, false, false, false, false, false,
2132            false, false, false, false, false, true, false, false, false, false, false, false,
2133            false, false, false, false, false, false, true
2134        ]));
2135        assert!(!act.none() && !act.all());
2136    }
2137
2138    #[test]
2139    fn test_32_elements() {
2140        // all 0
2141
2142        let mut act = BitVec::from_elem(32, false);
2143        assert!(act.eq_vec(&[
2144            false, false, false, false, false, false, false, false, false, false, false, false,
2145            false, false, false, false, false, false, false, false, false, false, false, false,
2146            false, false, false, false, false, false, false, false
2147        ]));
2148        assert!(act.none() && !act.all());
2149        // all 1
2150
2151        act = BitVec::from_elem(32, true);
2152        assert!(act.eq_vec(&[
2153            true, true, true, true, true, true, true, true, true, true, true, true, true, true,
2154            true, true, true, true, true, true, true, true, true, true, true, true, true, true,
2155            true, true, true, true
2156        ]));
2157        assert!(!act.none() && act.all());
2158        // mixed
2159
2160        act = BitVec::from_elem(32, false);
2161        act.set(0, true);
2162        act.set(1, true);
2163        act.set(2, true);
2164        act.set(3, true);
2165        act.set(4, true);
2166        act.set(5, true);
2167        act.set(6, true);
2168        act.set(7, true);
2169        assert!(act.eq_vec(&[
2170            true, true, true, true, true, true, true, true, false, false, false, false, false,
2171            false, false, false, false, false, false, false, false, false, false, false, false,
2172            false, false, false, false, false, false, false
2173        ]));
2174        assert!(!act.none() && !act.all());
2175        // mixed
2176
2177        act = BitVec::from_elem(32, false);
2178        act.set(16, true);
2179        act.set(17, true);
2180        act.set(18, true);
2181        act.set(19, true);
2182        act.set(20, true);
2183        act.set(21, true);
2184        act.set(22, true);
2185        act.set(23, true);
2186        assert!(act.eq_vec(&[
2187            false, false, false, false, false, false, false, false, false, false, false, false,
2188            false, false, false, false, true, true, true, true, true, true, true, true, false,
2189            false, false, false, false, false, false, false
2190        ]));
2191        assert!(!act.none() && !act.all());
2192        // mixed
2193
2194        act = BitVec::from_elem(32, false);
2195        act.set(24, true);
2196        act.set(25, true);
2197        act.set(26, true);
2198        act.set(27, true);
2199        act.set(28, true);
2200        act.set(29, true);
2201        act.set(30, true);
2202        act.set(31, true);
2203        assert!(act.eq_vec(&[
2204            false, false, false, false, false, false, false, false, false, false, false, false,
2205            false, false, false, false, false, false, false, false, false, false, false, false,
2206            true, true, true, true, true, true, true, true
2207        ]));
2208        assert!(!act.none() && !act.all());
2209        // mixed
2210
2211        act = BitVec::from_elem(32, false);
2212        act.set(3, true);
2213        act.set(17, true);
2214        act.set(30, true);
2215        act.set(31, true);
2216        assert!(act.eq_vec(&[
2217            false, false, false, true, false, false, false, false, false, false, false, false,
2218            false, false, false, false, false, true, false, false, false, false, false, false,
2219            false, false, false, false, false, false, true, true
2220        ]));
2221        assert!(!act.none() && !act.all());
2222    }
2223
2224    #[test]
2225    fn test_33_elements() {
2226        // all 0
2227
2228        let mut act = BitVec::from_elem(33, false);
2229        assert!(act.eq_vec(&[
2230            false, false, false, false, false, false, false, false, false, false, false, false,
2231            false, false, false, false, false, false, false, false, false, false, false, false,
2232            false, false, false, false, false, false, false, false, false
2233        ]));
2234        assert!(act.none() && !act.all());
2235        // all 1
2236
2237        act = BitVec::from_elem(33, true);
2238        assert!(act.eq_vec(&[
2239            true, true, true, true, true, true, true, true, true, true, true, true, true, true,
2240            true, true, true, true, true, true, true, true, true, true, true, true, true, true,
2241            true, true, true, true, true
2242        ]));
2243        assert!(!act.none() && act.all());
2244        // mixed
2245
2246        act = BitVec::from_elem(33, false);
2247        act.set(0, true);
2248        act.set(1, true);
2249        act.set(2, true);
2250        act.set(3, true);
2251        act.set(4, true);
2252        act.set(5, true);
2253        act.set(6, true);
2254        act.set(7, true);
2255        assert!(act.eq_vec(&[
2256            true, true, true, true, true, true, true, true, false, false, false, false, false,
2257            false, false, false, false, false, false, false, false, false, false, false, false,
2258            false, false, false, false, false, false, false, false
2259        ]));
2260        assert!(!act.none() && !act.all());
2261        // mixed
2262
2263        act = BitVec::from_elem(33, false);
2264        act.set(16, true);
2265        act.set(17, true);
2266        act.set(18, true);
2267        act.set(19, true);
2268        act.set(20, true);
2269        act.set(21, true);
2270        act.set(22, true);
2271        act.set(23, true);
2272        assert!(act.eq_vec(&[
2273            false, false, false, false, false, false, false, false, false, false, false, false,
2274            false, false, false, false, true, true, true, true, true, true, true, true, false,
2275            false, false, false, false, false, false, false, false
2276        ]));
2277        assert!(!act.none() && !act.all());
2278        // mixed
2279
2280        act = BitVec::from_elem(33, false);
2281        act.set(24, true);
2282        act.set(25, true);
2283        act.set(26, true);
2284        act.set(27, true);
2285        act.set(28, true);
2286        act.set(29, true);
2287        act.set(30, true);
2288        act.set(31, true);
2289        assert!(act.eq_vec(&[
2290            false, false, false, false, false, false, false, false, false, false, false, false,
2291            false, false, false, false, false, false, false, false, false, false, false, false,
2292            true, true, true, true, true, true, true, true, false
2293        ]));
2294        assert!(!act.none() && !act.all());
2295        // mixed
2296
2297        act = BitVec::from_elem(33, false);
2298        act.set(3, true);
2299        act.set(17, true);
2300        act.set(30, true);
2301        act.set(31, true);
2302        act.set(32, true);
2303        assert!(act.eq_vec(&[
2304            false, false, false, true, false, false, false, false, false, false, false, false,
2305            false, false, false, false, false, true, false, false, false, false, false, false,
2306            false, false, false, false, false, false, true, true, true
2307        ]));
2308        assert!(!act.none() && !act.all());
2309    }
2310
2311    #[test]
2312    fn test_equal_differing_sizes() {
2313        let v0 = BitVec::from_elem(10, false);
2314        let v1 = BitVec::from_elem(11, false);
2315        assert_ne!(v0, v1);
2316    }
2317
2318    #[test]
2319    fn test_equal_greatly_differing_sizes() {
2320        let v0 = BitVec::from_elem(10, false);
2321        let v1 = BitVec::from_elem(110, false);
2322        assert_ne!(v0, v1);
2323    }
2324
2325    #[test]
2326    fn test_equal_sneaky_small() {
2327        let mut a = BitVec::from_elem(1, false);
2328        a.set(0, true);
2329
2330        let mut b = BitVec::from_elem(1, true);
2331        b.set(0, true);
2332
2333        assert_eq!(a, b);
2334    }
2335
2336    #[test]
2337    fn test_equal_sneaky_big() {
2338        let mut a = BitVec::from_elem(100, false);
2339        for i in 0..100 {
2340            a.set(i, true);
2341        }
2342
2343        let mut b = BitVec::from_elem(100, true);
2344        for i in 0..100 {
2345            b.set(i, true);
2346        }
2347
2348        assert_eq!(a, b);
2349    }
2350
2351    #[test]
2352    fn test_from_bytes() {
2353        let bit_vec = BitVec::from_bytes(&[0b10110110, 0b00000000, 0b11111111]);
2354        let str = concat!("10110110", "00000000", "11111111");
2355        assert_eq!(format!("{}", bit_vec), str);
2356    }
2357
2358    #[test]
2359    fn test_to_bytes() {
2360        let mut bv = BitVec::from_elem(3, true);
2361        bv.set(1, false);
2362        assert_eq!(bv.to_bytes(), [0b10100000]);
2363
2364        let mut bv = BitVec::from_elem(9, false);
2365        bv.set(2, true);
2366        bv.set(8, true);
2367        assert_eq!(bv.to_bytes(), [0b00100000, 0b10000000]);
2368    }
2369
2370    #[test]
2371    fn test_from_bools() {
2372        let bools = [true, false, true, true];
2373        let bit_vec: BitVec = bools.iter().copied().collect();
2374        assert_eq!(format!("{}", bit_vec), "1011");
2375    }
2376
2377    #[test]
2378    fn test_to_bools() {
2379        let bools = vec![false, false, true, false, false, true, true, false];
2380        assert_eq!(
2381            BitVec::from_bytes(&[0b00100110])
2382                .iter()
2383                .collect::<Vec<bool>>(),
2384            bools
2385        );
2386    }
2387
2388    #[test]
2389    fn test_bit_vec_iterator() {
2390        let bools = vec![true, false, true, true];
2391        let bit_vec: BitVec = bools.iter().copied().collect();
2392
2393        assert_eq!(bit_vec.iter().collect::<Vec<bool>>(), bools);
2394
2395        let long: Vec<_> = (0..10000).map(|i| i % 2 == 0).collect();
2396        let bit_vec: BitVec = long.iter().copied().collect();
2397        assert_eq!(bit_vec.iter().collect::<Vec<bool>>(), long)
2398    }
2399
2400    #[test]
2401    fn test_small_difference() {
2402        let mut b1 = BitVec::from_elem(3, false);
2403        let mut b2 = BitVec::from_elem(3, false);
2404        b1.set(0, true);
2405        b1.set(1, true);
2406        b2.set(1, true);
2407        b2.set(2, true);
2408        assert!(b1.difference(&b2));
2409        assert!(b1[0]);
2410        assert!(!b1[1]);
2411        assert!(!b1[2]);
2412    }
2413
2414    #[test]
2415    fn test_big_difference() {
2416        let mut b1 = BitVec::from_elem(100, false);
2417        let mut b2 = BitVec::from_elem(100, false);
2418        b1.set(0, true);
2419        b1.set(40, true);
2420        b2.set(40, true);
2421        b2.set(80, true);
2422        assert!(b1.difference(&b2));
2423        assert!(b1[0]);
2424        assert!(!b1[40]);
2425        assert!(!b1[80]);
2426    }
2427
2428    #[test]
2429    fn test_small_xor() {
2430        let mut a = BitVec::from_bytes(&[0b0011]);
2431        let b = BitVec::from_bytes(&[0b0101]);
2432        let c = BitVec::from_bytes(&[0b0110]);
2433        assert!(a.xor(&b));
2434        assert_eq!(a, c);
2435    }
2436
2437    #[test]
2438    fn test_small_xnor() {
2439        let mut a = BitVec::from_bytes(&[0b0011]);
2440        let b = BitVec::from_bytes(&[0b1111_0101]);
2441        let c = BitVec::from_bytes(&[0b1001]);
2442        assert!(a.xnor(&b));
2443        assert_eq!(a, c);
2444    }
2445
2446    #[test]
2447    fn test_small_nand() {
2448        let mut a = BitVec::from_bytes(&[0b1111_0011]);
2449        let b = BitVec::from_bytes(&[0b1111_0101]);
2450        let c = BitVec::from_bytes(&[0b1110]);
2451        assert!(a.nand(&b));
2452        assert_eq!(a, c);
2453    }
2454
2455    #[test]
2456    fn test_small_nor() {
2457        let mut a = BitVec::from_bytes(&[0b0011]);
2458        let b = BitVec::from_bytes(&[0b1111_0101]);
2459        let c = BitVec::from_bytes(&[0b1000]);
2460        assert!(a.nor(&b));
2461        assert_eq!(a, c);
2462    }
2463
2464    #[test]
2465    fn test_big_xor() {
2466        let mut a = BitVec::from_bytes(&[
2467            // 88 bits
2468            0, 0, 0b00010100, 0, 0, 0, 0, 0b00110100, 0, 0, 0,
2469        ]);
2470        let b = BitVec::from_bytes(&[
2471            // 88 bits
2472            0, 0, 0b00010100, 0, 0, 0, 0, 0, 0, 0, 0b00110100,
2473        ]);
2474        let c = BitVec::from_bytes(&[
2475            // 88 bits
2476            0, 0, 0, 0, 0, 0, 0, 0b00110100, 0, 0, 0b00110100,
2477        ]);
2478        assert!(a.xor(&b));
2479        assert_eq!(a, c);
2480    }
2481
2482    #[test]
2483    fn test_big_xnor() {
2484        let mut a = BitVec::from_bytes(&[
2485            // 88 bits
2486            0, 0, 0b00010100, 0, 0, 0, 0, 0b00110100, 0, 0, 0,
2487        ]);
2488        let b = BitVec::from_bytes(&[
2489            // 88 bits
2490            0, 0, 0b00010100, 0, 0, 0, 0, 0, 0, 0, 0b00110100,
2491        ]);
2492        let c = BitVec::from_bytes(&[
2493            // 88 bits
2494            !0,
2495            !0,
2496            !0,
2497            !0,
2498            !0,
2499            !0,
2500            !0,
2501            !0b00110100,
2502            !0,
2503            !0,
2504            !0b00110100,
2505        ]);
2506        assert!(a.xnor(&b));
2507        assert_eq!(a, c);
2508    }
2509
2510    #[test]
2511    fn test_small_clear() {
2512        let mut b = BitVec::from_elem(14, true);
2513        assert!(!b.none() && b.all());
2514        b.clear();
2515        assert!(b.none() && !b.all());
2516    }
2517
2518    #[test]
2519    fn test_big_clear() {
2520        let mut b = BitVec::from_elem(140, true);
2521        assert!(!b.none() && b.all());
2522        b.clear();
2523        assert!(b.none() && !b.all());
2524    }
2525
2526    #[test]
2527    fn test_bit_vec_lt() {
2528        let mut a = BitVec::from_elem(5, false);
2529        let mut b = BitVec::from_elem(5, false);
2530
2531        assert!(a >= b && b >= a);
2532        b.set(2, true);
2533        assert!(a < b);
2534        a.set(3, true);
2535        assert!(a < b);
2536        a.set(2, true);
2537        assert!(a >= b && b < a);
2538        b.set(0, true);
2539        assert!(a < b);
2540    }
2541
2542    #[test]
2543    fn test_ord() {
2544        let mut a = BitVec::from_elem(5, false);
2545        let mut b = BitVec::from_elem(5, false);
2546
2547        assert!(a == b);
2548        a.set(1, true);
2549        assert!(a > b && a >= b);
2550        assert!(b < a && b <= a);
2551        b.set(1, true);
2552        b.set(2, true);
2553        assert!(b > a && b >= a);
2554        assert!(a < b && a <= b);
2555    }
2556
2557    #[test]
2558    fn test_small_bit_vec_tests() {
2559        let v = BitVec::from_bytes(&[0]);
2560        assert!(!v.all());
2561        assert!(!v.any());
2562        assert!(v.none());
2563
2564        let v = BitVec::from_bytes(&[0b00010100]);
2565        assert!(!v.all());
2566        assert!(v.any());
2567        assert!(!v.none());
2568
2569        let v = BitVec::from_bytes(&[0xFF]);
2570        assert!(v.all());
2571        assert!(v.any());
2572        assert!(!v.none());
2573    }
2574
2575    #[test]
2576    fn test_big_bit_vec_tests() {
2577        let v = BitVec::from_bytes(&[
2578            // 88 bits
2579            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2580        ]);
2581        assert!(!v.all());
2582        assert!(!v.any());
2583        assert!(v.none());
2584
2585        let v = BitVec::from_bytes(&[
2586            // 88 bits
2587            0, 0, 0b00010100, 0, 0, 0, 0, 0b00110100, 0, 0, 0,
2588        ]);
2589        assert!(!v.all());
2590        assert!(v.any());
2591        assert!(!v.none());
2592
2593        let v = BitVec::from_bytes(&[
2594            // 88 bits
2595            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
2596        ]);
2597        assert!(v.all());
2598        assert!(v.any());
2599        assert!(!v.none());
2600    }
2601
2602    #[test]
2603    fn test_bit_vec_push_pop() {
2604        let mut s = BitVec::from_elem(5 * U32_BITS - 2, false);
2605        assert_eq!(s.len(), 5 * U32_BITS - 2);
2606        assert!(!s[5 * U32_BITS - 3]);
2607        s.push(true);
2608        s.push(true);
2609        assert!(s[5 * U32_BITS - 2]);
2610        assert!(s[5 * U32_BITS - 1]);
2611        // Here the internal vector will need to be extended
2612        s.push(false);
2613        assert!(!s[5 * U32_BITS]);
2614        s.push(false);
2615        assert!(!s[5 * U32_BITS + 1]);
2616        assert_eq!(s.len(), 5 * U32_BITS + 2);
2617        // Pop it all off
2618        assert_eq!(s.pop(), Some(false));
2619        assert_eq!(s.pop(), Some(false));
2620        assert_eq!(s.pop(), Some(true));
2621        assert_eq!(s.pop(), Some(true));
2622        assert_eq!(s.len(), 5 * U32_BITS - 2);
2623    }
2624
2625    #[test]
2626    fn test_bit_vec_truncate() {
2627        let mut s = BitVec::from_elem(5 * U32_BITS, true);
2628
2629        assert_eq!(s, BitVec::from_elem(5 * U32_BITS, true));
2630        assert_eq!(s.len(), 5 * U32_BITS);
2631        s.truncate(4 * U32_BITS);
2632        assert_eq!(s, BitVec::from_elem(4 * U32_BITS, true));
2633        assert_eq!(s.len(), 4 * U32_BITS);
2634        // Truncating to a size > s.len() should be a noop
2635        s.truncate(5 * U32_BITS);
2636        assert_eq!(s, BitVec::from_elem(4 * U32_BITS, true));
2637        assert_eq!(s.len(), 4 * U32_BITS);
2638        s.truncate(3 * U32_BITS - 10);
2639        assert_eq!(s, BitVec::from_elem(3 * U32_BITS - 10, true));
2640        assert_eq!(s.len(), 3 * U32_BITS - 10);
2641        s.truncate(0);
2642        assert_eq!(s, BitVec::from_elem(0, true));
2643        assert_eq!(s.len(), 0);
2644    }
2645
2646    #[test]
2647    fn test_bit_vec_reserve() {
2648        let mut s = BitVec::from_elem(5 * U32_BITS, true);
2649        // Check capacity
2650        assert!(s.capacity() >= 5 * U32_BITS);
2651        s.reserve(2 * U32_BITS);
2652        assert!(s.capacity() >= 7 * U32_BITS);
2653        s.reserve(7 * U32_BITS);
2654        assert!(s.capacity() >= 12 * U32_BITS);
2655        s.reserve_exact(7 * U32_BITS);
2656        assert!(s.capacity() >= 12 * U32_BITS);
2657        s.reserve(7 * U32_BITS + 1);
2658        assert!(s.capacity() > 12 * U32_BITS);
2659        // Check that length hasn't changed
2660        assert_eq!(s.len(), 5 * U32_BITS);
2661        s.push(true);
2662        s.push(false);
2663        s.push(true);
2664        assert!(s[5 * U32_BITS - 1]);
2665        assert!(s[5 * U32_BITS]);
2666        assert!(!s[5 * U32_BITS + 1]);
2667        assert!(s[5 * U32_BITS + 2]);
2668    }
2669
2670    #[test]
2671    fn test_bit_vec_grow() {
2672        let mut bit_vec = BitVec::from_bytes(&[0b10110110, 0b00000000, 0b10101010]);
2673        bit_vec.grow(32, true);
2674        assert_eq!(
2675            bit_vec,
2676            BitVec::from_bytes(&[0b10110110, 0b00000000, 0b10101010, 0xFF, 0xFF, 0xFF, 0xFF])
2677        );
2678        bit_vec.grow(64, false);
2679        assert_eq!(
2680            bit_vec,
2681            BitVec::from_bytes(&[
2682                0b10110110, 0b00000000, 0b10101010, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0
2683            ])
2684        );
2685        bit_vec.grow(16, true);
2686        assert_eq!(
2687            bit_vec,
2688            BitVec::from_bytes(&[
2689                0b10110110, 0b00000000, 0b10101010, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0,
2690                0xFF, 0xFF
2691            ])
2692        );
2693    }
2694
2695    #[test]
2696    fn test_bit_vec_extend() {
2697        let mut bit_vec = BitVec::from_bytes(&[0b10110110, 0b00000000, 0b11111111]);
2698        let ext = BitVec::from_bytes(&[0b01001001, 0b10010010, 0b10111101]);
2699        bit_vec.extend(ext.iter());
2700        assert_eq!(
2701            bit_vec,
2702            BitVec::from_bytes(&[
2703                0b10110110, 0b00000000, 0b11111111, 0b01001001, 0b10010010, 0b10111101
2704            ])
2705        );
2706    }
2707
2708    #[test]
2709    fn test_bit_vec_append() {
2710        // Append to BitVec that holds a multiple of U32_BITS bits
2711        let mut a = BitVec::from_bytes(&[0b10100000, 0b00010010, 0b10010010, 0b00110011]);
2712        let mut b = BitVec::new();
2713        b.push(false);
2714        b.push(true);
2715        b.push(true);
2716
2717        a.append(&mut b);
2718
2719        assert_eq!(a.len(), 35);
2720        assert_eq!(b.len(), 0);
2721        assert!(b.capacity() >= 3);
2722
2723        assert!(a.eq_vec(&[
2724            true, false, true, false, false, false, false, false, false, false, false, true, false,
2725            false, true, false, true, false, false, true, false, false, true, false, false, false,
2726            true, true, false, false, true, true, false, true, true
2727        ]));
2728
2729        // Append to arbitrary BitVec
2730        let mut a = BitVec::new();
2731        a.push(true);
2732        a.push(false);
2733
2734        let mut b =
2735            BitVec::from_bytes(&[0b10100000, 0b00010010, 0b10010010, 0b00110011, 0b10010101]);
2736
2737        a.append(&mut b);
2738
2739        assert_eq!(a.len(), 42);
2740        assert_eq!(b.len(), 0);
2741        assert!(b.capacity() >= 40);
2742
2743        assert!(a.eq_vec(&[
2744            true, false, true, false, true, false, false, false, false, false, false, false, false,
2745            true, false, false, true, false, true, false, false, true, false, false, true, false,
2746            false, false, true, true, false, false, true, true, true, false, false, true, false,
2747            true, false, true
2748        ]));
2749
2750        // Append to empty BitVec
2751        let mut a = BitVec::new();
2752        let mut b =
2753            BitVec::from_bytes(&[0b10100000, 0b00010010, 0b10010010, 0b00110011, 0b10010101]);
2754
2755        a.append(&mut b);
2756
2757        assert_eq!(a.len(), 40);
2758        assert_eq!(b.len(), 0);
2759        assert!(b.capacity() >= 40);
2760
2761        assert!(a.eq_vec(&[
2762            true, false, true, false, false, false, false, false, false, false, false, true, false,
2763            false, true, false, true, false, false, true, false, false, true, false, false, false,
2764            true, true, false, false, true, true, true, false, false, true, false, true, false,
2765            true
2766        ]));
2767
2768        // Append empty BitVec
2769        let mut a =
2770            BitVec::from_bytes(&[0b10100000, 0b00010010, 0b10010010, 0b00110011, 0b10010101]);
2771        let mut b = BitVec::new();
2772
2773        a.append(&mut b);
2774
2775        assert_eq!(a.len(), 40);
2776        assert_eq!(b.len(), 0);
2777
2778        assert!(a.eq_vec(&[
2779            true, false, true, false, false, false, false, false, false, false, false, true, false,
2780            false, true, false, true, false, false, true, false, false, true, false, false, false,
2781            true, true, false, false, true, true, true, false, false, true, false, true, false,
2782            true
2783        ]));
2784    }
2785
2786    #[test]
2787    fn test_bit_vec_split_off() {
2788        // Split at 0
2789        let mut a = BitVec::new();
2790        a.push(true);
2791        a.push(false);
2792        a.push(false);
2793        a.push(true);
2794
2795        let b = a.split_off(0);
2796
2797        assert_eq!(a.len(), 0);
2798        assert_eq!(b.len(), 4);
2799
2800        assert!(b.eq_vec(&[true, false, false, true]));
2801
2802        // Split at last bit
2803        a.truncate(0);
2804        a.push(true);
2805        a.push(false);
2806        a.push(false);
2807        a.push(true);
2808
2809        let b = a.split_off(4);
2810
2811        assert_eq!(a.len(), 4);
2812        assert_eq!(b.len(), 0);
2813
2814        assert!(a.eq_vec(&[true, false, false, true]));
2815
2816        // Split at block boundary
2817        let mut a =
2818            BitVec::from_bytes(&[0b10100000, 0b00010010, 0b10010010, 0b00110011, 0b11110011]);
2819
2820        let b = a.split_off(32);
2821
2822        assert_eq!(a.len(), 32);
2823        assert_eq!(b.len(), 8);
2824
2825        assert!(a.eq_vec(&[
2826            true, false, true, false, false, false, false, false, false, false, false, true, false,
2827            false, true, false, true, false, false, true, false, false, true, false, false, false,
2828            true, true, false, false, true, true
2829        ]));
2830        assert!(b.eq_vec(&[true, true, true, true, false, false, true, true]));
2831
2832        // Don't split at block boundary
2833        let mut a = BitVec::from_bytes(&[
2834            0b10100000, 0b00010010, 0b10010010, 0b00110011, 0b01101011, 0b10101101,
2835        ]);
2836
2837        let b = a.split_off(13);
2838
2839        assert_eq!(a.len(), 13);
2840        assert_eq!(b.len(), 35);
2841
2842        assert!(a.eq_vec(&[
2843            true, false, true, false, false, false, false, false, false, false, false, true, false
2844        ]));
2845        assert!(b.eq_vec(&[
2846            false, true, false, true, false, false, true, false, false, true, false, false, false,
2847            true, true, false, false, true, true, false, true, true, false, true, false, true,
2848            true, true, false, true, false, true, true, false, true
2849        ]));
2850    }
2851
2852    #[test]
2853    fn test_into_iter() {
2854        let bools = [true, false, true, true];
2855        let bit_vec: BitVec = bools.iter().copied().collect();
2856        let mut iter = bit_vec.into_iter();
2857        assert_eq!(Some(true), iter.next());
2858        assert_eq!(Some(false), iter.next());
2859        assert_eq!(Some(true), iter.next());
2860        assert_eq!(Some(true), iter.next());
2861        assert_eq!(None, iter.next());
2862        assert_eq!(None, iter.next());
2863
2864        let bit_vec: BitVec = bools.iter().copied().collect();
2865        let mut iter = bit_vec.into_iter();
2866        assert_eq!(Some(true), iter.next_back());
2867        assert_eq!(Some(true), iter.next_back());
2868        assert_eq!(Some(false), iter.next_back());
2869        assert_eq!(Some(true), iter.next_back());
2870        assert_eq!(None, iter.next_back());
2871        assert_eq!(None, iter.next_back());
2872
2873        let bit_vec: BitVec = bools.iter().copied().collect();
2874        let mut iter = bit_vec.into_iter();
2875        assert_eq!(Some(true), iter.next_back());
2876        assert_eq!(Some(true), iter.next());
2877        assert_eq!(Some(false), iter.next());
2878        assert_eq!(Some(true), iter.next_back());
2879        assert_eq!(None, iter.next());
2880        assert_eq!(None, iter.next_back());
2881    }
2882
2883    #[test]
2884    fn iter() {
2885        let b = BitVec::with_capacity(10);
2886        let _a: Iter = b.iter();
2887    }
2888
2889    #[cfg(feature = "serde")]
2890    #[test]
2891    fn test_serialization() {
2892        let bit_vec: BitVec = BitVec::new();
2893        let serialized = serde_json::to_string(&bit_vec).unwrap();
2894        let unserialized: BitVec = serde_json::from_str(&serialized).unwrap();
2895        assert_eq!(bit_vec, unserialized);
2896
2897        let bools = vec![true, false, true, true];
2898        let bit_vec: BitVec = bools.iter().map(|n| *n).collect();
2899        let serialized = serde_json::to_string(&bit_vec).unwrap();
2900        let unserialized = serde_json::from_str(&serialized).unwrap();
2901        assert_eq!(bit_vec, unserialized);
2902    }
2903
2904    #[cfg(feature = "miniserde")]
2905    #[test]
2906    fn test_miniserde_serialization() {
2907        let bit_vec: BitVec = BitVec::new();
2908        let serialized = miniserde::json::to_string(&bit_vec);
2909        let unserialized: BitVec = miniserde::json::from_str(&serialized[..]).unwrap();
2910        assert_eq!(bit_vec, unserialized);
2911
2912        let bools = vec![true, false, true, true];
2913        let bit_vec: BitVec = bools.iter().map(|n| *n).collect();
2914        let serialized = miniserde::json::to_string(&bit_vec);
2915        let unserialized = miniserde::json::from_str(&serialized[..]).unwrap();
2916        assert_eq!(bit_vec, unserialized);
2917    }
2918
2919    #[cfg(feature = "nanoserde")]
2920    #[test]
2921    fn test_nanoserde_json_serialization() {
2922        use nanoserde::{DeJson, SerJson};
2923
2924        let bit_vec: BitVec = BitVec::new();
2925        let serialized = bit_vec.serialize_json();
2926        let unserialized: BitVec = BitVec::deserialize_json(&serialized[..]).unwrap();
2927        assert_eq!(bit_vec, unserialized);
2928
2929        let bools = vec![true, false, true, true];
2930        let bit_vec: BitVec = bools.iter().map(|n| *n).collect();
2931        let serialized = bit_vec.serialize_json();
2932        let unserialized = BitVec::deserialize_json(&serialized[..]).unwrap();
2933        assert_eq!(bit_vec, unserialized);
2934    }
2935
2936    #[cfg(feature = "borsh")]
2937    #[test]
2938    fn test_borsh_serialization() {
2939        let bit_vec: BitVec = BitVec::new();
2940        let serialized = borsh::to_vec(&bit_vec).unwrap();
2941        let unserialized: BitVec = borsh::from_slice(&serialized[..]).unwrap();
2942        assert_eq!(bit_vec, unserialized);
2943
2944        let bools = vec![true, false, true, true];
2945        let bit_vec: BitVec = bools.iter().map(|n| *n).collect();
2946        let serialized = borsh::to_vec(&bit_vec).unwrap();
2947        let unserialized = borsh::from_slice(&serialized[..]).unwrap();
2948        assert_eq!(bit_vec, unserialized);
2949    }
2950
2951    #[test]
2952    fn test_bit_vec_unaligned_small_append() {
2953        let mut a = BitVec::from_elem(8, false);
2954        a.set(7, true);
2955
2956        let mut b = BitVec::from_elem(16, false);
2957        b.set(14, true);
2958
2959        let mut c = BitVec::from_elem(8, false);
2960        c.set(6, true);
2961        c.set(7, true);
2962
2963        a.append(&mut b);
2964        a.append(&mut c);
2965
2966        assert_eq!(&[1, 0, 2, 3][..], &*a.to_bytes());
2967    }
2968
2969    #[test]
2970    fn test_bit_vec_unaligned_large_append() {
2971        let mut a = BitVec::from_elem(48, false);
2972        a.set(47, true);
2973
2974        let mut b = BitVec::from_elem(48, false);
2975        b.set(46, true);
2976
2977        let mut c = BitVec::from_elem(48, false);
2978        c.set(46, true);
2979        c.set(47, true);
2980
2981        a.append(&mut b);
2982        a.append(&mut c);
2983
2984        assert_eq!(
2985            &[
2986                0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00,
2987                0x00, 0x00, 0x00, 0x03
2988            ][..],
2989            &*a.to_bytes()
2990        );
2991    }
2992
2993    #[test]
2994    fn test_bit_vec_append_aligned_to_unaligned() {
2995        let mut a = BitVec::from_elem(2, true);
2996        let mut b = BitVec::from_elem(32, false);
2997        let mut c = BitVec::from_elem(8, true);
2998        a.append(&mut b);
2999        a.append(&mut c);
3000        assert_eq!(&[0xc0, 0x00, 0x00, 0x00, 0x3f, 0xc0][..], &*a.to_bytes());
3001    }
3002
3003    #[test]
3004    fn test_count_ones() {
3005        for i in 0..1000 {
3006            let mut t = BitVec::from_elem(i, true);
3007            let mut f = BitVec::from_elem(i, false);
3008            assert_eq!(i as u64, t.count_ones());
3009            assert_eq!(0_u64, f.count_ones());
3010            if i > 20 {
3011                t.set(10, false);
3012                t.set(i - 10, false);
3013                assert_eq!(i - 2, t.count_ones() as usize);
3014                f.set(10, true);
3015                f.set(i - 10, true);
3016                assert_eq!(2, f.count_ones());
3017            }
3018        }
3019    }
3020
3021    #[test]
3022    fn test_count_zeros() {
3023        for i in 0..1000 {
3024            let mut tbits = BitVec::from_elem(i, true);
3025            let mut fbits = BitVec::from_elem(i, false);
3026            assert_eq!(i as u64, fbits.count_zeros());
3027            assert_eq!(0_u64, tbits.count_zeros());
3028            if i > 20 {
3029                fbits.set(10, true);
3030                fbits.set(i - 10, true);
3031                assert_eq!(i - 2, fbits.count_zeros() as usize);
3032                tbits.set(10, false);
3033                tbits.set(i - 10, false);
3034                assert_eq!(2, tbits.count_zeros());
3035            }
3036        }
3037    }
3038
3039    #[test]
3040    fn test_get_mut() {
3041        let mut a = BitVec::from_elem(3, false);
3042        let mut a_bit_1 = a.get_mut(1).unwrap();
3043        assert!(!*a_bit_1);
3044        *a_bit_1 = true;
3045        drop(a_bit_1);
3046        assert!(a.eq_vec(&[false, true, false]));
3047    }
3048    #[test]
3049    fn test_iter_mut() {
3050        let mut a = BitVec::from_elem(8, false);
3051        a.iter_mut().enumerate().for_each(|(index, mut bit)| {
3052            *bit = index % 2 == 1;
3053        });
3054        assert!(a.eq_vec(&[false, true, false, true, false, true, false, true]));
3055    }
3056}