Skip to main content

bit_set/
lib.rs

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