Skip to main content

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