A Vec of Bits
at workspace 1862 lines 53 kB view raw
1// Copyright 2012-2014 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//! # Description 12//! 13//! An implementation of a set using a bit vector as an underlying 14//! representation for holding unsigned numerical elements. 15//! 16//! It should also be noted that the amount of storage necessary for holding a 17//! set of objects is proportional to the maximum of the objects when viewed 18//! as a `usize`. 19//! 20//! # Examples 21//! 22//! ``` 23//! use bit_set::BitSet; 24//! 25//! // It's a regular set 26//! let mut s = BitSet::new(); 27//! s.insert(0); 28//! s.insert(3); 29//! s.insert(7); 30//! 31//! s.remove(7); 32//! 33//! if !s.contains(7) { 34//! println!("There is no 7"); 35//! } 36//! 37//! // Can initialize from a `BitVec` 38//! let other = BitSet::from_bytes(&[0b11010000]); 39//! 40//! s.union_with(&other); 41//! 42//! // Print 0, 1, 3 in some order 43//! for x in s.iter() { 44//! println!("{}", x); 45//! } 46//! 47//! // Can convert back to a `BitVec` 48//! let bv = s.into_bit_vec(); 49//! assert!(bv[3]); 50//! ``` 51#![doc(html_root_url = "https://docs.rs/bit-set/0.8.0")] 52#![deny(clippy::shadow_reuse)] 53#![deny(clippy::shadow_same)] 54#![deny(clippy::shadow_unrelated)] 55#![no_std] 56 57#[cfg(any(test, feature = "std"))] 58extern crate std; 59 60use bit_vec::{BitBlock, BitVec, Blocks}; 61use bit_vec::{BitBlockOrStore, BitStore}; 62use core::cmp; 63use core::cmp::Ordering; 64use core::fmt; 65use core::hash; 66use core::iter::{self, Chain, Enumerate, FromIterator, Repeat, Skip, Take}; 67 68#[cfg(feature = "nanoserde")] 69extern crate alloc; 70#[cfg(feature = "nanoserde")] 71use alloc::vec::Vec; 72#[cfg(feature = "nanoserde")] 73use nanoserde::{DeBin, DeJson, DeRon, SerBin, SerJson, SerRon}; 74 75#[allow(type_alias_bounds)] 76type Block<B: BitBlockOrStore> = <B::Store as BitStore>::Block; 77#[allow(type_alias_bounds)] 78type MatchWords<'a, B: BitBlockOrStore> = 79 Chain<Enumerate<Blocks<'a, B>>, Skip<Take<Enumerate<Repeat<Block<B>>>>>>; 80 81/// Computes how many blocks are needed to store that many bits 82fn blocks_for_bits<B: BitBlockOrStore>(bits: usize) -> usize { 83 // If we want 17 bits, dividing by 32 will produce 0. So we add 1 to make sure we 84 // reserve enough. But if we want exactly a multiple of 32, this will actually allocate 85 // one too many. So we need to check if that's the case. We can do that by computing if 86 // bitwise AND by `32 - 1` is 0. But LLVM should be able to optimize the semantically 87 // superior modulo operator on a power of two to this. 88 // 89 // Note that we can technically avoid this branch with the expression 90 // `(nbits + BITS - 1) / 32::BITS`, but if nbits is almost usize::MAX this will overflow. 91 if bits % B::BITS == 0 { 92 bits / B::BITS 93 } else { 94 bits / B::BITS + 1 95 } 96} 97 98#[allow(clippy::iter_skip_zero)] 99// Take two BitVec's, and return iterators of their words, where the shorter one 100// has been padded with 0's 101fn match_words<'a, 'b, B: BitBlockOrStore>( 102 a: &'a BitVec<B>, 103 b: &'b BitVec<B>, 104) -> (MatchWords<'a, B>, MatchWords<'b, B>) { 105 let a_len = a.storage().len(); 106 let b_len = b.storage().len(); 107 108 // have to uselessly pretend to pad the longer one for type matching 109 if a_len < b_len { 110 ( 111 a.blocks() 112 .enumerate() 113 .chain(iter::repeat(B::ZERO).enumerate().take(b_len).skip(a_len)), 114 b.blocks() 115 .enumerate() 116 .chain(iter::repeat(B::ZERO).enumerate().take(0).skip(0)), 117 ) 118 } else { 119 ( 120 a.blocks() 121 .enumerate() 122 .chain(iter::repeat(B::ZERO).enumerate().take(0).skip(0)), 123 b.blocks() 124 .enumerate() 125 .chain(iter::repeat(B::ZERO).enumerate().take(a_len).skip(b_len)), 126 ) 127 } 128} 129 130#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 131#[cfg_attr( 132 feature = "borsh", 133 derive(borsh::BorshDeserialize, borsh::BorshSerialize) 134)] 135#[cfg_attr( 136 feature = "miniserde", 137 derive(miniserde::Deserialize, miniserde::Serialize) 138)] 139#[cfg_attr( 140 feature = "nanoserde", 141 derive(DeBin, DeJson, DeRon, SerBin, SerJson, SerRon) 142)] 143pub struct BitSet<B: BitBlockOrStore = u32> { 144 bit_vec: BitVec<B>, 145} 146 147impl<B: BitBlockOrStore> Clone for BitSet<B> { 148 fn clone(&self) -> Self { 149 BitSet { 150 bit_vec: self.bit_vec.clone(), 151 } 152 } 153 154 fn clone_from(&mut self, other: &Self) { 155 self.bit_vec.clone_from(&other.bit_vec); 156 } 157} 158 159impl<B: BitBlockOrStore> Default for BitSet<B> { 160 #[inline] 161 fn default() -> Self { 162 BitSet { 163 bit_vec: Default::default(), 164 } 165 } 166} 167 168impl<B: BitBlockOrStore> FromIterator<usize> for BitSet<B> { 169 fn from_iter<I: IntoIterator<Item = usize>>(iter: I) -> Self { 170 let mut ret = Self::default(); 171 ret.extend(iter); 172 ret 173 } 174} 175 176impl<B: BitBlockOrStore> Extend<usize> for BitSet<B> { 177 #[inline] 178 fn extend<I: IntoIterator<Item = usize>>(&mut self, iter: I) { 179 for i in iter { 180 self.insert(i); 181 } 182 } 183} 184 185impl<B: BitBlockOrStore> PartialOrd for BitSet<B> { 186 #[inline] 187 fn partial_cmp(&self, other: &Self) -> Option<Ordering> { 188 Some(self.cmp(other)) 189 } 190} 191 192impl<B: BitBlockOrStore> Ord for BitSet<B> { 193 #[inline] 194 fn cmp(&self, other: &Self) -> Ordering { 195 self.iter().cmp(other) 196 } 197} 198 199impl<B: BitBlockOrStore> PartialEq for BitSet<B> { 200 #[inline] 201 fn eq(&self, other: &Self) -> bool { 202 self.iter().eq(other) 203 } 204} 205 206impl<B: BitBlockOrStore> Eq for BitSet<B> {} 207 208impl BitSet<u32> { 209 /// Creates a new empty `BitSet`. 210 /// 211 /// # Examples 212 /// 213 /// ``` 214 /// use bit_set::BitSet; 215 /// 216 /// let mut s = BitSet::new(); 217 /// ``` 218 #[inline] 219 pub fn new() -> Self { 220 Self::default() 221 } 222 223 /// Creates a new `BitSet` with initially no contents, able to 224 /// hold `nbits` elements without resizing. 225 /// 226 /// # Examples 227 /// 228 /// ``` 229 /// use bit_set::BitSet; 230 /// 231 /// let mut s = BitSet::with_capacity(100); 232 /// assert!(s.capacity() >= 100); 233 /// ``` 234 #[inline] 235 pub fn with_capacity(nbits: usize) -> Self { 236 let bit_vec = BitVec::from_elem(nbits, false); 237 Self::from_bit_vec(bit_vec) 238 } 239 240 /// Creates a new `BitSet` from the given bit vector. 241 /// 242 /// # Examples 243 /// 244 /// ``` 245 /// use bit_vec::BitVec; 246 /// use bit_set::BitSet; 247 /// 248 /// let bv = BitVec::from_bytes(&[0b01100000]); 249 /// let s = BitSet::from_bit_vec(bv); 250 /// 251 /// // Print 1, 2 in arbitrary order 252 /// for x in s.iter() { 253 /// println!("{}", x); 254 /// } 255 /// ``` 256 #[inline] 257 pub fn from_bit_vec(bit_vec: BitVec) -> Self { 258 BitSet { bit_vec } 259 } 260 261 pub fn from_bytes(bytes: &[u8]) -> Self { 262 BitSet { 263 bit_vec: BitVec::from_bytes(bytes), 264 } 265 } 266} 267 268impl<B: BitBlockOrStore> BitSet<B> { 269 /// Creates a new empty `BitSet`. 270 /// 271 /// # Examples 272 /// 273 /// ``` 274 /// use bit_set::BitSet; 275 /// 276 /// let mut s = <BitSet>::new_general(); 277 /// ``` 278 #[inline] 279 pub fn new_general() -> Self { 280 Self::default() 281 } 282 283 /// Creates a new `BitSet` with initially no contents, able to 284 /// hold `nbits` elements without resizing. 285 /// 286 /// # Examples 287 /// 288 /// ``` 289 /// use bit_set::BitSet; 290 /// 291 /// let mut s = <BitSet>::with_capacity_general(100); 292 /// assert!(s.capacity() >= 100); 293 /// ``` 294 #[inline] 295 pub fn with_capacity_general(nbits: usize) -> Self { 296 let bit_vec = BitVec::from_elem_general(nbits, false); 297 Self::from_bit_vec_general(bit_vec) 298 } 299 300 /// Creates a new `BitSet` from the given bit vector. 301 /// 302 /// # Examples 303 /// 304 /// ``` 305 /// use bit_vec::BitVec; 306 /// use bit_set::BitSet; 307 /// 308 /// let bv: BitVec<u64> = BitVec::from_bytes_general(&[0b01100000]); 309 /// let s = BitSet::from_bit_vec_general(bv); 310 /// 311 /// // Print 1, 2 in arbitrary order 312 /// for x in s.iter() { 313 /// println!("{}", x); 314 /// } 315 /// ``` 316 #[inline] 317 pub fn from_bit_vec_general(bit_vec: BitVec<B>) -> Self { 318 BitSet { bit_vec } 319 } 320 321 pub fn from_bytes_general(bytes: &[u8]) -> Self { 322 BitSet { 323 bit_vec: BitVec::from_bytes_general(bytes), 324 } 325 } 326 327 /// Returns the capacity in bits for this bit vector. Inserting any 328 /// element less than this amount will not trigger a resizing. 329 /// 330 /// # Examples 331 /// 332 /// ``` 333 /// use bit_set::BitSet; 334 /// 335 /// let mut s = BitSet::with_capacity(100); 336 /// assert!(s.capacity() >= 100); 337 /// ``` 338 #[inline] 339 pub fn capacity(&self) -> usize { 340 self.bit_vec.capacity() 341 } 342 343 /// Reserves capacity for the given `BitSet` to contain `len` distinct elements. In the case 344 /// of `BitSet` this means reallocations will not occur as long as all inserted elements 345 /// are less than `len`. 346 /// 347 /// The collection may reserve more space to avoid frequent reallocations. 348 /// 349 /// 350 /// # Examples 351 /// 352 /// ``` 353 /// use bit_set::BitSet; 354 /// 355 /// let mut s = BitSet::new(); 356 /// s.reserve_len(10); 357 /// assert!(s.capacity() >= 10); 358 /// ``` 359 pub fn reserve_len(&mut self, len: usize) { 360 let cur_len = self.bit_vec.len(); 361 if len >= cur_len { 362 self.bit_vec.reserve(len - cur_len); 363 } 364 } 365 366 /// Reserves the minimum capacity for the given `BitSet` to contain `len` distinct elements. 367 /// In the case of `BitSet` this means reallocations will not occur as long as all inserted 368 /// elements are less than `len`. 369 /// 370 /// Note that the allocator may give the collection more space than it requests. Therefore 371 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve_len` if future 372 /// insertions are expected. 373 /// 374 /// 375 /// # Examples 376 /// 377 /// ``` 378 /// use bit_set::BitSet; 379 /// 380 /// let mut s = BitSet::new(); 381 /// s.reserve_len_exact(10); 382 /// assert!(s.capacity() >= 10); 383 /// ``` 384 pub fn reserve_len_exact(&mut self, len: usize) { 385 let cur_len = self.bit_vec.len(); 386 if len >= cur_len { 387 self.bit_vec.reserve_exact(len - cur_len); 388 } 389 } 390 391 /// Consumes this set to return the underlying bit vector. 392 /// 393 /// # Examples 394 /// 395 /// ``` 396 /// use bit_set::BitSet; 397 /// 398 /// let mut s = BitSet::new(); 399 /// s.insert(0); 400 /// s.insert(3); 401 /// 402 /// let bv = s.into_bit_vec(); 403 /// assert!(bv[0]); 404 /// assert!(bv[3]); 405 /// ``` 406 #[inline] 407 pub fn into_bit_vec(self) -> BitVec<B> { 408 self.bit_vec 409 } 410 411 /// Returns a reference to the underlying bit vector. 412 /// 413 /// # Examples 414 /// 415 /// ``` 416 /// use bit_set::BitSet; 417 /// 418 /// let mut set = BitSet::new(); 419 /// set.insert(0); 420 /// 421 /// let bv = set.get_ref(); 422 /// assert_eq!(bv[0], true); 423 /// ``` 424 #[inline] 425 pub fn get_ref(&self) -> &BitVec<B> { 426 &self.bit_vec 427 } 428 429 /// Returns a mutable reference to the underlying bit vector. 430 /// 431 /// # Examples 432 /// 433 /// ``` 434 /// use bit_set::BitSet; 435 /// 436 /// let mut set = BitSet::new(); 437 /// set.insert(0); 438 /// set.insert(3); 439 /// 440 /// { 441 /// let bv = set.get_mut(); 442 /// bv.set(1, true); 443 /// } 444 /// 445 /// assert!(set.contains(0)); 446 /// assert!(set.contains(1)); 447 /// assert!(set.contains(3)); 448 /// ``` 449 #[inline] 450 pub fn get_mut(&mut self) -> &mut BitVec<B> { 451 &mut self.bit_vec 452 } 453 454 #[inline] 455 fn other_op<F>(&mut self, other: &Self, mut f: F) 456 where 457 F: FnMut(Block<B>, Block<B>) -> Block<B>, 458 { 459 // Unwrap BitVecs 460 let self_bit_vec = &mut self.bit_vec; 461 let other_bit_vec = &other.bit_vec; 462 463 let self_len = self_bit_vec.len(); 464 let other_len = other_bit_vec.len(); 465 466 // Expand the vector if necessary 467 if self_len < other_len { 468 self_bit_vec.grow(other_len - self_len, false); 469 } 470 471 // virtually pad other with 0's for equal lengths 472 let other_words = { 473 let (_, result) = match_words(self_bit_vec, other_bit_vec); 474 result 475 }; 476 477 // Apply values found in other 478 for (i, w) in other_words { 479 let old = self_bit_vec.storage()[i]; 480 let new = f(old, w); 481 unsafe { 482 self_bit_vec.storage_mut().slice_mut()[i] = new; 483 } 484 } 485 } 486 487 /// Truncates the underlying vector to the least length required. 488 /// 489 /// # Examples 490 /// 491 /// ``` 492 /// use bit_set::BitSet; 493 /// 494 /// let mut s = BitSet::new(); 495 /// s.insert(3231); 496 /// s.remove(3231); 497 /// 498 /// // Internal storage will probably be bigger than necessary 499 /// println!("old capacity: {}", s.capacity()); 500 /// assert!(s.capacity() >= 3231); 501 /// 502 /// // Now should be smaller 503 /// s.shrink_to_fit(); 504 /// println!("new capacity: {}", s.capacity()); 505 /// ``` 506 #[inline] 507 pub fn shrink_to_fit(&mut self) { 508 let bit_vec = &mut self.bit_vec; 509 // Obtain original length 510 let old_len = bit_vec.storage().len(); 511 // Obtain coarse trailing zero length 512 let n = bit_vec 513 .storage() 514 .iter() 515 .rev() 516 .take_while(|&&n| n == B::ZERO) 517 .count(); 518 // Truncate away all empty trailing blocks, then shrink_to_fit 519 let trunc_len = old_len - n; 520 unsafe { 521 bit_vec.storage_mut().truncate(trunc_len); 522 bit_vec.set_len(trunc_len * B::BITS); 523 } 524 bit_vec.shrink_to_fit(); 525 } 526 527 /// Iterator over each usize stored in the `BitSet`. 528 /// 529 /// # Examples 530 /// 531 /// ``` 532 /// use bit_set::BitSet; 533 /// 534 /// let s = BitSet::from_bytes(&[0b01001010]); 535 /// 536 /// // Print 1, 4, 6 in arbitrary order 537 /// for x in s.iter() { 538 /// println!("{}", x); 539 /// } 540 /// ``` 541 #[inline] 542 pub fn iter(&self) -> Iter<'_, B> { 543 Iter(BlockIter::from_blocks(self.bit_vec.blocks())) 544 } 545 546 /// Iterator over each usize stored in `self` union `other`. 547 /// See [`union_with`] for an efficient in-place version. 548 /// 549 /// # Examples 550 /// 551 /// ``` 552 /// use bit_set::BitSet; 553 /// 554 /// let a = BitSet::from_bytes(&[0b01101000]); 555 /// let b = BitSet::from_bytes(&[0b10100000]); 556 /// 557 /// // Print 0, 1, 2, 4 in arbitrary order 558 /// for x in a.union(&b) { 559 /// println!("{}", x); 560 /// } 561 /// ``` 562 /// 563 /// [`union_with`]: Self::union_with 564 #[inline] 565 pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, B> { 566 fn or<B: BitBlock>(w1: B, w2: B) -> B { 567 w1 | w2 568 } 569 570 Union(BlockIter::from_blocks(TwoBitPositions { 571 set: self.bit_vec.blocks(), 572 other: other.bit_vec.blocks(), 573 merge: or, 574 })) 575 } 576 577 /// Iterator over each usize stored in `self` intersect `other`. 578 /// See [`intersect_with`] for an efficient in-place version. 579 /// 580 /// # Examples 581 /// 582 /// ``` 583 /// use bit_set::BitSet; 584 /// 585 /// let a = BitSet::from_bytes(&[0b01101000]); 586 /// let b = BitSet::from_bytes(&[0b10100000]); 587 /// 588 /// // Print 2 589 /// for x in a.intersection(&b) { 590 /// println!("{}", x); 591 /// } 592 /// ``` 593 /// 594 /// [`intersect_with`]: Self::intersect_with 595 #[inline] 596 pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, B> { 597 fn bitand<B: BitBlock>(w1: B, w2: B) -> B { 598 w1 & w2 599 } 600 let min = cmp::min(self.bit_vec.len(), other.bit_vec.len()); 601 602 Intersection { 603 iter: BlockIter::from_blocks(TwoBitPositions { 604 set: self.bit_vec.blocks(), 605 other: other.bit_vec.blocks(), 606 merge: bitand, 607 }), 608 n: min, 609 } 610 } 611 612 /// Iterator over each usize stored in the `self` setminus `other`. 613 /// See [`difference_with`] for an efficient in-place version. 614 /// 615 /// # Examples 616 /// 617 /// ``` 618 /// use bit_set::BitSet; 619 /// 620 /// let a = BitSet::from_bytes(&[0b01101000]); 621 /// let b = BitSet::from_bytes(&[0b10100000]); 622 /// 623 /// // Print 1, 4 in arbitrary order 624 /// for x in a.difference(&b) { 625 /// println!("{}", x); 626 /// } 627 /// 628 /// // Note that difference is not symmetric, 629 /// // and `b - a` means something else. 630 /// // This prints 0 631 /// for x in b.difference(&a) { 632 /// println!("{}", x); 633 /// } 634 /// ``` 635 /// 636 /// [`difference_with`]: Self::difference_with 637 #[inline] 638 pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, B> { 639 fn diff<B: BitBlock>(w1: B, w2: B) -> B { 640 w1 & !w2 641 } 642 643 Difference(BlockIter::from_blocks(TwoBitPositions { 644 set: self.bit_vec.blocks(), 645 other: other.bit_vec.blocks(), 646 merge: diff, 647 })) 648 } 649 650 /// Iterator over each usize stored in the symmetric difference of `self` and `other`. 651 /// See [`symmetric_difference_with`] for an efficient in-place version. 652 /// 653 /// # Examples 654 /// 655 /// ``` 656 /// use bit_set::BitSet; 657 /// 658 /// let a = BitSet::from_bytes(&[0b01101000]); 659 /// let b = BitSet::from_bytes(&[0b10100000]); 660 /// 661 /// // Print 0, 1, 4 in arbitrary order 662 /// for x in a.symmetric_difference(&b) { 663 /// println!("{}", x); 664 /// } 665 /// ``` 666 /// 667 /// [`symmetric_difference_with`]: Self::symmetric_difference_with 668 #[inline] 669 pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> SymmetricDifference<'a, B> { 670 fn bitxor<B: BitBlock>(w1: B, w2: B) -> B { 671 w1 ^ w2 672 } 673 674 SymmetricDifference(BlockIter::from_blocks(TwoBitPositions { 675 set: self.bit_vec.blocks(), 676 other: other.bit_vec.blocks(), 677 merge: bitxor, 678 })) 679 } 680 681 /// Unions in-place with the specified other bit vector. 682 /// 683 /// # Examples 684 /// 685 /// ``` 686 /// use bit_set::BitSet; 687 /// 688 /// let a = 0b01101000; 689 /// let b = 0b10100000; 690 /// let res = 0b11101000; 691 /// 692 /// let mut a = BitSet::from_bytes(&[a]); 693 /// let b = BitSet::from_bytes(&[b]); 694 /// let res = BitSet::from_bytes(&[res]); 695 /// 696 /// a.union_with(&b); 697 /// assert_eq!(a, res); 698 /// ``` 699 #[inline] 700 pub fn union_with(&mut self, other: &Self) { 701 self.other_op(other, |w1, w2| w1 | w2); 702 } 703 704 /// Intersects in-place with the specified other bit vector. 705 /// 706 /// # Examples 707 /// 708 /// ``` 709 /// use bit_set::BitSet; 710 /// 711 /// let a = 0b01101000; 712 /// let b = 0b10100000; 713 /// let res = 0b00100000; 714 /// 715 /// let mut a = BitSet::from_bytes(&[a]); 716 /// let b = BitSet::from_bytes(&[b]); 717 /// let res = BitSet::from_bytes(&[res]); 718 /// 719 /// a.intersect_with(&b); 720 /// assert_eq!(a, res); 721 /// ``` 722 #[inline] 723 pub fn intersect_with(&mut self, other: &Self) { 724 self.other_op(other, |w1, w2| w1 & w2); 725 } 726 727 /// Makes this bit vector the difference with the specified other bit vector 728 /// in-place. 729 /// 730 /// # Examples 731 /// 732 /// ``` 733 /// use bit_set::BitSet; 734 /// 735 /// let a = 0b01101000; 736 /// let b = 0b10100000; 737 /// let a_b = 0b01001000; // a - b 738 /// let b_a = 0b10000000; // b - a 739 /// 740 /// let mut bva = BitSet::from_bytes(&[a]); 741 /// let bvb = BitSet::from_bytes(&[b]); 742 /// let bva_b = BitSet::from_bytes(&[a_b]); 743 /// let bvb_a = BitSet::from_bytes(&[b_a]); 744 /// 745 /// bva.difference_with(&bvb); 746 /// assert_eq!(bva, bva_b); 747 /// 748 /// let bva = BitSet::from_bytes(&[a]); 749 /// let mut bvb = BitSet::from_bytes(&[b]); 750 /// 751 /// bvb.difference_with(&bva); 752 /// assert_eq!(bvb, bvb_a); 753 /// ``` 754 #[inline] 755 pub fn difference_with(&mut self, other: &Self) { 756 self.other_op(other, |w1, w2| w1 & !w2); 757 } 758 759 /// Makes this bit vector the symmetric difference with the specified other 760 /// bit vector in-place. 761 /// 762 /// # Examples 763 /// 764 /// ``` 765 /// use bit_set::BitSet; 766 /// 767 /// let a = 0b01101000; 768 /// let b = 0b10100000; 769 /// let res = 0b11001000; 770 /// 771 /// let mut a = BitSet::from_bytes(&[a]); 772 /// let b = BitSet::from_bytes(&[b]); 773 /// let res = BitSet::from_bytes(&[res]); 774 /// 775 /// a.symmetric_difference_with(&b); 776 /// assert_eq!(a, res); 777 /// ``` 778 #[inline] 779 pub fn symmetric_difference_with(&mut self, other: &Self) { 780 self.other_op(other, |w1, w2| w1 ^ w2); 781 } 782 783 /* 784 /// Moves all elements from `other` into `Self`, leaving `other` empty. 785 /// 786 /// # Examples 787 /// 788 /// ``` 789 /// use bit_set::BitSet; 790 /// 791 /// let mut a = BitSet::new(); 792 /// a.insert(2); 793 /// a.insert(6); 794 /// 795 /// let mut b = BitSet::new(); 796 /// b.insert(1); 797 /// b.insert(3); 798 /// b.insert(6); 799 /// 800 /// a.append(&mut b); 801 /// 802 /// assert_eq!(a.len(), 4); 803 /// assert_eq!(b.len(), 0); 804 /// assert_eq!(a, BitSet::from_bytes(&[0b01110010])); 805 /// ``` 806 pub fn append(&mut self, other: &mut Self) { 807 self.union_with(other); 808 other.clear(); 809 } 810 811 /// Splits the `BitSet` into two at the given key including the key. 812 /// Retains the first part in-place while returning the second part. 813 /// 814 /// # Examples 815 /// 816 /// ``` 817 /// use bit_set::BitSet; 818 /// 819 /// let mut a = BitSet::new(); 820 /// a.insert(2); 821 /// a.insert(6); 822 /// a.insert(1); 823 /// a.insert(3); 824 /// 825 /// let b = a.split_off(3); 826 /// 827 /// assert_eq!(a.len(), 2); 828 /// assert_eq!(b.len(), 2); 829 /// assert_eq!(a, BitSet::from_bytes(&[0b01100000])); 830 /// assert_eq!(b, BitSet::from_bytes(&[0b00010010])); 831 /// ``` 832 pub fn split_off(&mut self, at: usize) -> Self { 833 let mut other = BitSet::new(); 834 835 if at == 0 { 836 swap(self, &mut other); 837 return other; 838 } else if at >= self.bit_vec.len() { 839 return other; 840 } 841 842 // Calculate block and bit at which to split 843 let w = at / BITS; 844 let b = at % BITS; 845 846 // Pad `other` with `w` zero blocks, 847 // append `self`'s blocks in the range from `w` to the end to `other` 848 other.bit_vec.storage_mut().extend(repeat(0u32).take(w) 849 .chain(self.bit_vec.storage()[w..].iter().cloned())); 850 other.bit_vec.nbits = self.bit_vec.nbits; 851 852 if b > 0 { 853 other.bit_vec.storage_mut()[w] &= !0 << b; 854 } 855 856 // Sets `bit_vec.len()` and fixes the last block as well 857 self.bit_vec.truncate(at); 858 859 other 860 } 861 */ 862 863 /// Counts the number of set bits in this set. 864 /// 865 /// Note that this function scans the set to calculate the number. 866 #[inline] 867 pub fn count(&self) -> usize { 868 self.bit_vec.blocks().fold(0, |acc, n| acc + n.count_ones()) 869 } 870 871 /// Counts the number of set bits in this set. 872 /// 873 /// Note that this function scans the set to calculate the number. 874 #[inline] 875 #[deprecated = "use BitVec::count() instead"] 876 pub fn len(&self) -> usize { 877 self.count() 878 } 879 880 /// Returns whether there are no bits set in this set 881 #[inline] 882 pub fn is_empty(&self) -> bool { 883 self.bit_vec.none() 884 } 885 886 /// Removes all elements of this set. 887 /// 888 /// Different from [`reset`] only in that the capacity is preserved. 889 /// 890 /// [`reset`]: Self::reset 891 #[inline] 892 pub fn make_empty(&mut self) { 893 self.bit_vec.fill(false); 894 } 895 896 /// Resets this set to an empty state. 897 /// 898 /// Different from [`make_empty`] only in that the capacity may NOT be preserved. 899 /// 900 /// [`make_empty`]: Self::make_empty 901 #[inline] 902 pub fn reset(&mut self) { 903 self.bit_vec.remove_all(); 904 } 905 906 /// Clears all bits in this set 907 #[deprecated(since = "0.9.0", note = "please use `fn make_empty` instead")] 908 #[inline] 909 pub fn clear(&mut self) { 910 self.make_empty(); 911 } 912 913 /// Returns `true` if this set contains the specified integer. 914 #[inline] 915 pub fn contains(&self, value: usize) -> bool { 916 let bit_vec = &self.bit_vec; 917 value < bit_vec.len() && bit_vec[value] 918 } 919 920 /// Returns `true` if the set has no elements in common with `other`. 921 /// This is equivalent to checking for an empty intersection. 922 #[inline] 923 pub fn is_disjoint(&self, other: &Self) -> bool { 924 self.intersection(other).next().is_none() 925 } 926 927 /// Returns `true` if the set is a subset of another. 928 #[inline] 929 pub fn is_subset(&self, other: &Self) -> bool { 930 let self_bit_vec = &self.bit_vec; 931 let other_bit_vec = &other.bit_vec; 932 let other_blocks = blocks_for_bits::<B>(other_bit_vec.len()); 933 934 // Check that `self` intersect `other` is self 935 self_bit_vec.blocks().zip(other_bit_vec.blocks()).all(|(w1, w2)| w1 & w2 == w1) && 936 // Make sure if `self` has any more blocks than `other`, they're all 0 937 self_bit_vec.blocks().skip(other_blocks).all(|w| w == B::ZERO) 938 } 939 940 /// Returns `true` if the set is a superset of another. 941 #[inline] 942 pub fn is_superset(&self, other: &Self) -> bool { 943 other.is_subset(self) 944 } 945 946 /// Adds a value to the set. Returns `true` if the value was not already 947 /// present in the set. 948 pub fn insert(&mut self, value: usize) -> bool { 949 if self.contains(value) { 950 return false; 951 } 952 953 // Ensure we have enough space to hold the new element 954 let len = self.bit_vec.len(); 955 if value >= len { 956 self.bit_vec.grow(value - len + 1, false); 957 } 958 959 self.bit_vec.set(value, true); 960 true 961 } 962 963 /// Removes a value from the set. Returns `true` if the value was 964 /// present in the set. 965 pub fn remove(&mut self, value: usize) -> bool { 966 if !self.contains(value) { 967 return false; 968 } 969 970 self.bit_vec.set(value, false); 971 972 true 973 } 974 975 /// Excludes `element` and all greater elements from the `BitSet`. 976 pub fn truncate(&mut self, element: usize) { 977 self.bit_vec.truncate(element); 978 } 979} 980 981impl<B: BitBlockOrStore> fmt::Debug for BitSet<B> { 982 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 983 fmt.debug_struct("BitSet") 984 .field("bit_vec", &self.bit_vec) 985 .finish() 986 } 987} 988 989impl<B: BitBlockOrStore> fmt::Display for BitSet<B> { 990 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 991 fmt.debug_set().entries(self).finish() 992 } 993} 994 995impl<B: BitBlockOrStore> hash::Hash for BitSet<B> { 996 fn hash<H: hash::Hasher>(&self, state: &mut H) { 997 for pos in self { 998 pos.hash(state); 999 } 1000 } 1001} 1002 1003#[derive(Clone)] 1004struct BlockIter<T, B: BitBlockOrStore> { 1005 head: Block<B>, 1006 head_offset: usize, 1007 tail: T, 1008} 1009 1010impl<T, B: BitBlockOrStore> BlockIter<T, B> 1011where 1012 T: Iterator<Item = Block<B>>, 1013{ 1014 fn from_blocks(mut blocks: T) -> Self { 1015 let h = blocks.next().unwrap_or(B::ZERO); 1016 BlockIter { 1017 tail: blocks, 1018 head: h, 1019 head_offset: 0, 1020 } 1021 } 1022} 1023 1024/// An iterator combining two `BitSet` iterators. 1025#[derive(Clone)] 1026struct TwoBitPositions<'a, B: 'a + BitBlockOrStore> { 1027 set: Blocks<'a, B>, 1028 other: Blocks<'a, B>, 1029 merge: fn(Block<B>, Block<B>) -> Block<B>, 1030} 1031 1032/// An iterator for `BitSet`. 1033#[derive(Clone)] 1034pub struct Iter<'a, B: 'a + BitBlockOrStore>(BlockIter<Blocks<'a, B>, B>); 1035#[derive(Clone)] 1036pub struct Union<'a, B: 'a + BitBlockOrStore>(BlockIter<TwoBitPositions<'a, B>, B>); 1037#[derive(Clone)] 1038pub struct Intersection<'a, B: 'a + BitBlockOrStore> { 1039 iter: BlockIter<TwoBitPositions<'a, B>, B>, 1040 // as an optimization, we compute the maximum possible 1041 // number of elements in the intersection, and count it 1042 // down as we return elements. If we reach zero, we can 1043 // stop. 1044 n: usize, 1045} 1046#[derive(Clone)] 1047pub struct Difference<'a, B: 'a + BitBlockOrStore>(BlockIter<TwoBitPositions<'a, B>, B>); 1048#[derive(Clone)] 1049pub struct SymmetricDifference<'a, B: 'a + BitBlockOrStore>(BlockIter<TwoBitPositions<'a, B>, B>); 1050 1051impl<T, B: BitBlockOrStore> Iterator for BlockIter<T, B> 1052where 1053 T: Iterator<Item = Block<B>>, 1054{ 1055 type Item = usize; 1056 1057 fn next(&mut self) -> Option<Self::Item> { 1058 while self.head == B::ZERO { 1059 match self.tail.next() { 1060 Some(w) => self.head = w, 1061 None => return None, 1062 } 1063 self.head_offset += B::BITS; 1064 } 1065 1066 // from the current block, isolate the 1067 // LSB and subtract 1, producing k: 1068 // a block with a number of set bits 1069 // equal to the index of the LSB 1070 let k = (self.head & (!self.head + B::ONE)) - B::ONE; 1071 // update block, removing the LSB 1072 self.head = self.head & (self.head - B::ONE); 1073 // return offset + (index of LSB) 1074 Some(self.head_offset + (<B::Store as BitStore>::Block::count_ones(k))) 1075 } 1076 1077 fn count(self) -> usize { 1078 self.head.count_ones() + self.tail.map(|block| block.count_ones()).sum::<usize>() 1079 } 1080 1081 #[inline] 1082 fn size_hint(&self) -> (usize, Option<usize>) { 1083 match self.tail.size_hint() { 1084 (_, Some(h)) => (0, Some((1 + h) * B::BITS)), 1085 _ => (0, None), 1086 } 1087 } 1088} 1089 1090impl<B: BitBlockOrStore> Iterator for TwoBitPositions<'_, B> { 1091 type Item = Block<B>; 1092 1093 fn next(&mut self) -> Option<Self::Item> { 1094 match (self.set.next(), self.other.next()) { 1095 (Some(a), Some(b)) => Some((self.merge)(a, b)), 1096 (Some(a), None) => Some((self.merge)(a, B::ZERO)), 1097 (None, Some(b)) => Some((self.merge)(B::ZERO, b)), 1098 _ => None, 1099 } 1100 } 1101 1102 #[inline] 1103 fn size_hint(&self) -> (usize, Option<usize>) { 1104 let (first_lower_bound, first_upper_bound) = self.set.size_hint(); 1105 let (second_lower_bound, second_upper_bound) = self.other.size_hint(); 1106 1107 let upper_bound = first_upper_bound.zip(second_upper_bound); 1108 1109 let get_max = |(a, b)| cmp::max(a, b); 1110 ( 1111 cmp::max(first_lower_bound, second_lower_bound), 1112 upper_bound.map(get_max), 1113 ) 1114 } 1115} 1116 1117impl<B: BitBlockOrStore> Iterator for Iter<'_, B> { 1118 type Item = usize; 1119 1120 #[inline] 1121 fn next(&mut self) -> Option<usize> { 1122 self.0.next() 1123 } 1124 #[inline] 1125 fn size_hint(&self) -> (usize, Option<usize>) { 1126 self.0.size_hint() 1127 } 1128 #[inline] 1129 fn count(self) -> usize { 1130 self.0.count() 1131 } 1132} 1133 1134impl<B: BitBlockOrStore> Iterator for Union<'_, B> { 1135 type Item = usize; 1136 1137 #[inline] 1138 fn next(&mut self) -> Option<usize> { 1139 self.0.next() 1140 } 1141 #[inline] 1142 fn size_hint(&self) -> (usize, Option<usize>) { 1143 self.0.size_hint() 1144 } 1145 #[inline] 1146 fn count(self) -> usize { 1147 self.0.count() 1148 } 1149} 1150 1151impl<B: BitBlockOrStore> Iterator for Intersection<'_, B> { 1152 type Item = usize; 1153 1154 #[inline] 1155 fn next(&mut self) -> Option<usize> { 1156 if self.n != 0 { 1157 self.n -= 1; 1158 self.iter.next() 1159 } else { 1160 None 1161 } 1162 } 1163 #[inline] 1164 fn size_hint(&self) -> (usize, Option<usize>) { 1165 // We could invoke self.iter.size_hint() and incorporate that into the hint. 1166 // In practice, that does not seem worthwhile because the lower bound will 1167 // always be zero and the upper bound could only possibly less then n in a 1168 // partially iterated iterator. However, it makes little sense ask for size_hint 1169 // in a partially iterated iterator, so it did not seem worthwhile. 1170 (0, Some(self.n)) 1171 } 1172 #[inline] 1173 fn count(self) -> usize { 1174 self.iter.count() 1175 } 1176} 1177 1178impl<B: BitBlockOrStore> Iterator for Difference<'_, B> { 1179 type Item = usize; 1180 1181 #[inline] 1182 fn next(&mut self) -> Option<usize> { 1183 self.0.next() 1184 } 1185 #[inline] 1186 fn size_hint(&self) -> (usize, Option<usize>) { 1187 self.0.size_hint() 1188 } 1189 #[inline] 1190 fn count(self) -> usize { 1191 self.0.count() 1192 } 1193} 1194 1195impl<B: BitBlockOrStore> Iterator for SymmetricDifference<'_, B> { 1196 type Item = usize; 1197 1198 #[inline] 1199 fn next(&mut self) -> Option<usize> { 1200 self.0.next() 1201 } 1202 #[inline] 1203 fn size_hint(&self) -> (usize, Option<usize>) { 1204 self.0.size_hint() 1205 } 1206 #[inline] 1207 fn count(self) -> usize { 1208 self.0.count() 1209 } 1210} 1211 1212impl<'a, B: BitBlockOrStore> IntoIterator for &'a BitSet<B> { 1213 type Item = usize; 1214 type IntoIter = Iter<'a, B>; 1215 1216 fn into_iter(self) -> Iter<'a, B> { 1217 self.iter() 1218 } 1219} 1220 1221#[cfg(test)] 1222mod tests { 1223 #![allow(clippy::shadow_reuse)] 1224 #![allow(clippy::shadow_same)] 1225 #![allow(clippy::shadow_unrelated)] 1226 1227 use super::BitSet; 1228 use bit_vec::BitVec; 1229 use std::cmp::Ordering::{Equal, Greater, Less}; 1230 use std::vec::Vec; 1231 use std::{format, vec}; 1232 1233 #[test] 1234 fn test_bit_set_display() { 1235 let mut s = BitSet::new(); 1236 s.insert(1); 1237 s.insert(10); 1238 s.insert(50); 1239 s.insert(2); 1240 assert_eq!("{1, 2, 10, 50}", format!("{}", s)); 1241 } 1242 1243 #[test] 1244 fn test_bit_set_debug() { 1245 let mut s = BitSet::new(); 1246 s.insert(1); 1247 s.insert(10); 1248 s.insert(50); 1249 s.insert(2); 1250 let expected = "BitSet { bit_vec: BitVec { storage: \ 1251 \"01100000001000000000000000000000 \ 1252 0000000000000000001\", nbits: 51 } }"; 1253 let actual = format!("{:?}", s); 1254 assert_eq!(expected, actual); 1255 } 1256 1257 #[test] 1258 fn test_bit_set_from_usizes() { 1259 let usizes = vec![0, 2, 2, 3]; 1260 let a: BitSet = usizes.into_iter().collect(); 1261 let mut b = BitSet::new(); 1262 b.insert(0); 1263 b.insert(2); 1264 b.insert(3); 1265 assert_eq!(a, b); 1266 } 1267 1268 #[test] 1269 fn test_bit_set_iterator() { 1270 let usizes = vec![0, 2, 2, 3]; 1271 let bit_vec: BitSet = usizes.into_iter().collect(); 1272 1273 let idxs: Vec<_> = bit_vec.iter().collect(); 1274 assert_eq!(idxs, [0, 2, 3]); 1275 assert_eq!(bit_vec.iter().count(), 3); 1276 1277 let long: BitSet = (0..10000).filter(|&n| n % 2 == 0).collect(); 1278 let real: Vec<_> = (0..10000 / 2).map(|x| x * 2).collect(); 1279 1280 let idxs: Vec<_> = long.iter().collect(); 1281 assert_eq!(idxs, real); 1282 assert_eq!(long.iter().count(), real.len()); 1283 } 1284 1285 #[test] 1286 fn test_bit_set_frombit_vec_init() { 1287 let bools = [true, false]; 1288 let lengths = [10, 64, 100]; 1289 for &b in &bools { 1290 for &l in &lengths { 1291 let bitset = BitSet::from_bit_vec(BitVec::from_elem(l, b)); 1292 assert_eq!(bitset.contains(1), b); 1293 assert_eq!(bitset.contains(l - 1), b); 1294 assert!(!bitset.contains(l)); 1295 } 1296 } 1297 } 1298 1299 #[test] 1300 fn test_bit_vec_masking() { 1301 let b = BitVec::from_elem(140, true); 1302 let mut bs = BitSet::from_bit_vec(b); 1303 assert!(bs.contains(139)); 1304 assert!(!bs.contains(140)); 1305 assert!(bs.insert(150)); 1306 assert!(!bs.contains(140)); 1307 assert!(!bs.contains(149)); 1308 assert!(bs.contains(150)); 1309 assert!(!bs.contains(151)); 1310 } 1311 1312 #[test] 1313 fn test_bit_set_basic() { 1314 let mut b = BitSet::new(); 1315 assert!(b.insert(3)); 1316 assert!(!b.insert(3)); 1317 assert!(b.contains(3)); 1318 assert!(b.insert(4)); 1319 assert!(!b.insert(4)); 1320 assert!(b.contains(3)); 1321 assert!(b.insert(400)); 1322 assert!(!b.insert(400)); 1323 assert!(b.contains(400)); 1324 assert_eq!(b.count(), 3); 1325 } 1326 1327 #[test] 1328 fn test_bit_set_intersection() { 1329 let mut a = BitSet::new(); 1330 let mut b = BitSet::new(); 1331 1332 assert!(a.insert(11)); 1333 assert!(a.insert(1)); 1334 assert!(a.insert(3)); 1335 assert!(a.insert(77)); 1336 assert!(a.insert(103)); 1337 assert!(a.insert(5)); 1338 1339 assert!(b.insert(2)); 1340 assert!(b.insert(11)); 1341 assert!(b.insert(77)); 1342 assert!(b.insert(5)); 1343 assert!(b.insert(3)); 1344 1345 let expected = [3, 5, 11, 77]; 1346 let actual: Vec<_> = a.intersection(&b).collect(); 1347 assert_eq!(actual, expected); 1348 assert_eq!(a.intersection(&b).count(), expected.len()); 1349 } 1350 1351 #[test] 1352 fn test_bit_set_difference() { 1353 let mut a = BitSet::new(); 1354 let mut b = BitSet::new(); 1355 1356 assert!(a.insert(1)); 1357 assert!(a.insert(3)); 1358 assert!(a.insert(5)); 1359 assert!(a.insert(200)); 1360 assert!(a.insert(500)); 1361 1362 assert!(b.insert(3)); 1363 assert!(b.insert(200)); 1364 1365 let expected = [1, 5, 500]; 1366 let actual: Vec<_> = a.difference(&b).collect(); 1367 assert_eq!(actual, expected); 1368 assert_eq!(a.difference(&b).count(), expected.len()); 1369 } 1370 1371 #[test] 1372 fn test_bit_set_symmetric_difference() { 1373 let mut a = BitSet::new(); 1374 let mut b = BitSet::new(); 1375 1376 assert!(a.insert(1)); 1377 assert!(a.insert(3)); 1378 assert!(a.insert(5)); 1379 assert!(a.insert(9)); 1380 assert!(a.insert(11)); 1381 1382 assert!(b.insert(3)); 1383 assert!(b.insert(9)); 1384 assert!(b.insert(14)); 1385 assert!(b.insert(220)); 1386 1387 let expected = [1, 5, 11, 14, 220]; 1388 let actual: Vec<_> = a.symmetric_difference(&b).collect(); 1389 assert_eq!(actual, expected); 1390 assert_eq!(a.symmetric_difference(&b).count(), expected.len()); 1391 } 1392 1393 #[test] 1394 fn test_bit_set_union() { 1395 let mut a = BitSet::new(); 1396 let mut b = BitSet::new(); 1397 assert!(a.insert(1)); 1398 assert!(a.insert(3)); 1399 assert!(a.insert(5)); 1400 assert!(a.insert(9)); 1401 assert!(a.insert(11)); 1402 assert!(a.insert(160)); 1403 assert!(a.insert(19)); 1404 assert!(a.insert(24)); 1405 assert!(a.insert(200)); 1406 1407 assert!(b.insert(1)); 1408 assert!(b.insert(5)); 1409 assert!(b.insert(9)); 1410 assert!(b.insert(13)); 1411 assert!(b.insert(19)); 1412 1413 let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160, 200]; 1414 let actual: Vec<_> = a.union(&b).collect(); 1415 assert_eq!(actual, expected); 1416 assert_eq!(a.union(&b).count(), expected.len()); 1417 } 1418 1419 #[test] 1420 fn test_bit_set_subset() { 1421 let mut set1 = BitSet::new(); 1422 let mut set2 = BitSet::new(); 1423 1424 assert!(set1.is_subset(&set2)); // {} {} 1425 set2.insert(100); 1426 assert!(set1.is_subset(&set2)); // {} { 1 } 1427 set2.insert(200); 1428 assert!(set1.is_subset(&set2)); // {} { 1, 2 } 1429 set1.insert(200); 1430 assert!(set1.is_subset(&set2)); // { 2 } { 1, 2 } 1431 set1.insert(300); 1432 assert!(!set1.is_subset(&set2)); // { 2, 3 } { 1, 2 } 1433 set2.insert(300); 1434 assert!(set1.is_subset(&set2)); // { 2, 3 } { 1, 2, 3 } 1435 set2.insert(400); 1436 assert!(set1.is_subset(&set2)); // { 2, 3 } { 1, 2, 3, 4 } 1437 set2.remove(100); 1438 assert!(set1.is_subset(&set2)); // { 2, 3 } { 2, 3, 4 } 1439 set2.remove(300); 1440 assert!(!set1.is_subset(&set2)); // { 2, 3 } { 2, 4 } 1441 set1.remove(300); 1442 assert!(set1.is_subset(&set2)); // { 2 } { 2, 4 } 1443 } 1444 1445 #[test] 1446 fn test_bit_set_is_disjoint() { 1447 let a = BitSet::from_bytes(&[0b10100010]); 1448 let b = BitSet::from_bytes(&[0b01000000]); 1449 let c = BitSet::new(); 1450 let d = BitSet::from_bytes(&[0b00110000]); 1451 1452 assert!(!a.is_disjoint(&d)); 1453 assert!(!d.is_disjoint(&a)); 1454 1455 assert!(a.is_disjoint(&b)); 1456 assert!(a.is_disjoint(&c)); 1457 assert!(b.is_disjoint(&a)); 1458 assert!(b.is_disjoint(&c)); 1459 assert!(c.is_disjoint(&a)); 1460 assert!(c.is_disjoint(&b)); 1461 } 1462 1463 #[test] 1464 fn test_bit_set_union_with() { 1465 //a should grow to include larger elements 1466 let mut a = BitSet::new(); 1467 a.insert(0); 1468 let mut b = BitSet::new(); 1469 b.insert(5); 1470 let expected = BitSet::from_bytes(&[0b10000100]); 1471 a.union_with(&b); 1472 assert_eq!(a, expected); 1473 1474 // Standard 1475 let mut a = BitSet::from_bytes(&[0b10100010]); 1476 let mut b = BitSet::from_bytes(&[0b01100010]); 1477 let c = a.clone(); 1478 a.union_with(&b); 1479 b.union_with(&c); 1480 assert_eq!(a.count(), 4); 1481 assert_eq!(b.count(), 4); 1482 } 1483 1484 #[test] 1485 fn test_bit_set_intersect_with() { 1486 // Explicitly 0'ed bits 1487 let mut a = BitSet::from_bytes(&[0b10100010]); 1488 let mut b = BitSet::from_bytes(&[0b00000000]); 1489 let c = a.clone(); 1490 a.intersect_with(&b); 1491 b.intersect_with(&c); 1492 assert!(a.is_empty()); 1493 assert!(b.is_empty()); 1494 1495 // Uninitialized bits should behave like 0's 1496 let mut a = BitSet::from_bytes(&[0b10100010]); 1497 let mut b = BitSet::new(); 1498 let c = a.clone(); 1499 a.intersect_with(&b); 1500 b.intersect_with(&c); 1501 assert!(a.is_empty()); 1502 assert!(b.is_empty()); 1503 1504 // Standard 1505 let mut a = BitSet::from_bytes(&[0b10100010]); 1506 let mut b = BitSet::from_bytes(&[0b01100010]); 1507 let c = a.clone(); 1508 a.intersect_with(&b); 1509 b.intersect_with(&c); 1510 assert_eq!(a.count(), 2); 1511 assert_eq!(b.count(), 2); 1512 } 1513 1514 #[test] 1515 fn test_bit_set_difference_with() { 1516 // Explicitly 0'ed bits 1517 let mut a = BitSet::from_bytes(&[0b00000000]); 1518 let b = BitSet::from_bytes(&[0b10100010]); 1519 a.difference_with(&b); 1520 assert!(a.is_empty()); 1521 1522 // Uninitialized bits should behave like 0's 1523 let mut a = BitSet::new(); 1524 let b = BitSet::from_bytes(&[0b11111111]); 1525 a.difference_with(&b); 1526 assert!(a.is_empty()); 1527 1528 // Standard 1529 let mut a = BitSet::from_bytes(&[0b10100010]); 1530 let mut b = BitSet::from_bytes(&[0b01100010]); 1531 let c = a.clone(); 1532 a.difference_with(&b); 1533 b.difference_with(&c); 1534 assert_eq!(a.count(), 1); 1535 assert_eq!(b.count(), 1); 1536 } 1537 1538 #[test] 1539 fn test_bit_set_symmetric_difference_with() { 1540 //a should grow to include larger elements 1541 let mut a = BitSet::new(); 1542 a.insert(0); 1543 a.insert(1); 1544 let mut b = BitSet::new(); 1545 b.insert(1); 1546 b.insert(5); 1547 let expected = BitSet::from_bytes(&[0b10000100]); 1548 a.symmetric_difference_with(&b); 1549 assert_eq!(a, expected); 1550 1551 let mut a = BitSet::from_bytes(&[0b10100010]); 1552 let b = BitSet::new(); 1553 let c = a.clone(); 1554 a.symmetric_difference_with(&b); 1555 assert_eq!(a, c); 1556 1557 // Standard 1558 let mut a = BitSet::from_bytes(&[0b11100010]); 1559 let mut b = BitSet::from_bytes(&[0b01101010]); 1560 let c = a.clone(); 1561 a.symmetric_difference_with(&b); 1562 b.symmetric_difference_with(&c); 1563 assert_eq!(a.count(), 2); 1564 assert_eq!(b.count(), 2); 1565 } 1566 1567 #[test] 1568 fn test_bit_set_eq() { 1569 let a = BitSet::from_bytes(&[0b10100010]); 1570 let b = BitSet::from_bytes(&[0b00000000]); 1571 let c = BitSet::new(); 1572 1573 assert!(a == a); 1574 assert!(a != b); 1575 assert!(a != c); 1576 assert!(b == b); 1577 assert!(b == c); 1578 assert!(c == c); 1579 } 1580 1581 #[test] 1582 fn test_bit_set_cmp() { 1583 let a = BitSet::from_bytes(&[0b10100010]); 1584 let b = BitSet::from_bytes(&[0b00000000]); 1585 let c = BitSet::new(); 1586 1587 assert_eq!(a.cmp(&b), Greater); 1588 assert_eq!(a.cmp(&c), Greater); 1589 assert_eq!(b.cmp(&a), Less); 1590 assert_eq!(b.cmp(&c), Equal); 1591 assert_eq!(c.cmp(&a), Less); 1592 assert_eq!(c.cmp(&b), Equal); 1593 } 1594 1595 #[test] 1596 fn test_bit_set_shrink_to_fit_new() { 1597 // There was a strange bug where we refused to truncate to 0 1598 // and this would end up actually growing the array in a way 1599 // that (safely corrupted the state). 1600 let mut a = BitSet::new(); 1601 assert_eq!(a.count(), 0); 1602 assert_eq!(a.capacity(), 0); 1603 a.shrink_to_fit(); 1604 assert_eq!(a.count(), 0); 1605 assert_eq!(a.capacity(), 0); 1606 assert!(!a.contains(1)); 1607 a.insert(3); 1608 assert!(a.contains(3)); 1609 assert_eq!(a.count(), 1); 1610 assert!(a.capacity() > 0); 1611 a.shrink_to_fit(); 1612 assert!(a.contains(3)); 1613 assert_eq!(a.count(), 1); 1614 assert!(a.capacity() > 0); 1615 } 1616 1617 #[test] 1618 fn test_bit_set_shrink_to_fit() { 1619 let mut a = BitSet::new(); 1620 assert_eq!(a.count(), 0); 1621 assert_eq!(a.capacity(), 0); 1622 a.insert(259); 1623 a.insert(98); 1624 a.insert(3); 1625 assert_eq!(a.count(), 3); 1626 assert!(a.capacity() > 0); 1627 assert!(!a.contains(1)); 1628 assert!(a.contains(259)); 1629 assert!(a.contains(98)); 1630 assert!(a.contains(3)); 1631 1632 a.shrink_to_fit(); 1633 assert!(!a.contains(1)); 1634 assert!(a.contains(259)); 1635 assert!(a.contains(98)); 1636 assert!(a.contains(3)); 1637 assert_eq!(a.count(), 3); 1638 assert!(a.capacity() > 0); 1639 1640 let old_cap = a.capacity(); 1641 assert!(a.remove(259)); 1642 a.shrink_to_fit(); 1643 assert!(a.capacity() < old_cap, "{} {}", a.capacity(), old_cap); 1644 assert!(!a.contains(1)); 1645 assert!(!a.contains(259)); 1646 assert!(a.contains(98)); 1647 assert!(a.contains(3)); 1648 assert_eq!(a.count(), 2); 1649 1650 let old_cap2 = a.capacity(); 1651 a.make_empty(); 1652 assert_eq!(a.capacity(), old_cap2); 1653 assert_eq!(a.count(), 0); 1654 assert!(!a.contains(1)); 1655 assert!(!a.contains(259)); 1656 assert!(!a.contains(98)); 1657 assert!(!a.contains(3)); 1658 1659 a.insert(512); 1660 assert!(a.capacity() > 0); 1661 assert_eq!(a.count(), 1); 1662 assert!(a.contains(512)); 1663 assert!(!a.contains(1)); 1664 assert!(!a.contains(259)); 1665 assert!(!a.contains(98)); 1666 assert!(!a.contains(3)); 1667 1668 a.remove(512); 1669 a.shrink_to_fit(); 1670 assert_eq!(a.capacity(), 0); 1671 assert_eq!(a.count(), 0); 1672 assert!(!a.contains(512)); 1673 assert!(!a.contains(1)); 1674 assert!(!a.contains(259)); 1675 assert!(!a.contains(98)); 1676 assert!(!a.contains(3)); 1677 assert!(!a.contains(0)); 1678 } 1679 1680 #[test] 1681 fn test_bit_vec_remove() { 1682 let mut a = BitSet::new(); 1683 1684 assert!(a.insert(1)); 1685 assert!(a.remove(1)); 1686 1687 assert!(a.insert(100)); 1688 assert!(a.remove(100)); 1689 1690 assert!(a.insert(1000)); 1691 assert!(a.remove(1000)); 1692 a.shrink_to_fit(); 1693 } 1694 1695 #[test] 1696 fn test_bit_vec_clone() { 1697 let mut a = BitSet::new(); 1698 1699 assert!(a.insert(1)); 1700 assert!(a.insert(100)); 1701 assert!(a.insert(1000)); 1702 1703 let mut b = a.clone(); 1704 1705 assert!(a == b); 1706 1707 assert!(b.remove(1)); 1708 assert!(a.contains(1)); 1709 1710 assert!(a.remove(1000)); 1711 assert!(b.contains(1000)); 1712 } 1713 1714 #[test] 1715 fn test_truncate() { 1716 let bytes = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]; 1717 1718 let mut s = BitSet::from_bytes(&bytes); 1719 s.truncate(5 * 8); 1720 1721 assert_eq!(s, BitSet::from_bytes(&bytes[..5])); 1722 assert_eq!(s.count(), 5 * 8); 1723 s.truncate(4 * 8); 1724 assert_eq!(s, BitSet::from_bytes(&bytes[..4])); 1725 assert_eq!(s.count(), 4 * 8); 1726 // Truncating to a size > s.len() should be a noop 1727 s.truncate(5 * 8); 1728 assert_eq!(s, BitSet::from_bytes(&bytes[..4])); 1729 assert_eq!(s.count(), 4 * 8); 1730 s.truncate(8); 1731 assert_eq!(s, BitSet::from_bytes(&bytes[..1])); 1732 assert_eq!(s.count(), 8); 1733 s.truncate(0); 1734 assert_eq!(s, BitSet::from_bytes(&[])); 1735 assert_eq!(s.count(), 0); 1736 } 1737 1738 #[cfg(feature = "serde")] 1739 #[test] 1740 fn test_serialization() { 1741 let bset: BitSet = BitSet::new(); 1742 let serialized = serde_json::to_string(&bset).unwrap(); 1743 let unserialized: BitSet = serde_json::from_str(&serialized).unwrap(); 1744 assert_eq!(bset, unserialized); 1745 1746 let elems: Vec<usize> = vec![11, 42, 100, 101]; 1747 let bset: BitSet = elems.iter().map(|n| *n).collect(); 1748 let serialized = serde_json::to_string(&bset).unwrap(); 1749 let unserialized = serde_json::from_str(&serialized).unwrap(); 1750 assert_eq!(bset, unserialized); 1751 } 1752 1753 #[cfg(feature = "miniserde")] 1754 #[test] 1755 fn test_miniserde_serialization() { 1756 let bset: BitSet = BitSet::new(); 1757 let serialized = miniserde::json::to_string(&bset); 1758 let unserialized: BitSet = miniserde::json::from_str(&serialized[..]).unwrap(); 1759 assert_eq!(bset, unserialized); 1760 1761 let elems: Vec<usize> = vec![11, 42, 100, 101]; 1762 let bset: BitSet = elems.iter().map(|n| *n).collect(); 1763 let serialized = miniserde::json::to_string(&bset); 1764 let unserialized = miniserde::json::from_str(&serialized[..]).unwrap(); 1765 assert_eq!(bset, unserialized); 1766 } 1767 1768 #[cfg(feature = "nanoserde")] 1769 #[test] 1770 fn test_nanoserde_json_serialization() { 1771 use nanoserde::{DeJson, SerJson}; 1772 1773 let bset: BitSet = BitSet::new(); 1774 let serialized = bset.serialize_json(); 1775 let unserialized: BitSet = BitSet::deserialize_json(&serialized[..]).unwrap(); 1776 assert_eq!(bset, unserialized); 1777 1778 let elems: Vec<usize> = vec![11, 42, 100, 101]; 1779 let bset: BitSet = elems.iter().map(|n| *n).collect(); 1780 let serialized = bset.serialize_json(); 1781 let unserialized = BitSet::deserialize_json(&serialized[..]).unwrap(); 1782 assert_eq!(bset, unserialized); 1783 } 1784 1785 #[cfg(feature = "borsh")] 1786 #[test] 1787 fn test_borsh_serialization() { 1788 let bset: BitSet = BitSet::new(); 1789 let serialized = borsh::to_vec(&bset).unwrap(); 1790 let unserialized: BitSet = borsh::from_slice(&serialized[..]).unwrap(); 1791 assert_eq!(bset, unserialized); 1792 1793 let elems: Vec<usize> = vec![11, 42, 100, 101]; 1794 let bset: BitSet = elems.iter().map(|n| *n).collect(); 1795 let serialized = borsh::to_vec(&bset).unwrap(); 1796 let unserialized = borsh::from_slice(&serialized[..]).unwrap(); 1797 assert_eq!(bset, unserialized); 1798 } 1799 1800 /* 1801 #[test] 1802 fn test_bit_set_append() { 1803 let mut a = BitSet::new(); 1804 a.insert(2); 1805 a.insert(6); 1806 1807 let mut b = BitSet::new(); 1808 b.insert(1); 1809 b.insert(3); 1810 b.insert(6); 1811 1812 a.append(&mut b); 1813 1814 assert_eq!(a.len(), 4); 1815 assert_eq!(b.len(), 0); 1816 assert!(b.capacity() >= 6); 1817 1818 assert_eq!(a, BitSet::from_bytes(&[0b01110010])); 1819 } 1820 1821 #[test] 1822 fn test_bit_set_split_off() { 1823 // Split at 0 1824 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010, 1825 0b00110011, 0b01101011, 0b10101101]); 1826 1827 let b = a.split_off(0); 1828 1829 assert_eq!(a.len(), 0); 1830 assert_eq!(b.len(), 21); 1831 1832 assert_eq!(b, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010, 1833 0b00110011, 0b01101011, 0b10101101]); 1834 1835 // Split behind last element 1836 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010, 1837 0b00110011, 0b01101011, 0b10101101]); 1838 1839 let b = a.split_off(50); 1840 1841 assert_eq!(a.len(), 21); 1842 assert_eq!(b.len(), 0); 1843 1844 assert_eq!(a, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010, 1845 0b00110011, 0b01101011, 0b10101101])); 1846 1847 // Split at arbitrary element 1848 let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010, 1849 0b00110011, 0b01101011, 0b10101101]); 1850 1851 let b = a.split_off(34); 1852 1853 assert_eq!(a.len(), 12); 1854 assert_eq!(b.len(), 9); 1855 1856 assert_eq!(a, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010, 1857 0b00110011, 0b01000000])); 1858 assert_eq!(b, BitSet::from_bytes(&[0, 0, 0, 0, 1859 0b00101011, 0b10101101])); 1860 } 1861 */ 1862}