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