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