Debian Codegraph @

third_party/rust/bit-vec/src/lib.rs

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