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