fixedbitset/
lib.rs

1//! `FixedBitSet` is a simple fixed size set of bits.
2//!
3//!
4//! ### Crate features
5//!
6//! - `std` (default feature)  
7//!   Disabling this feature disables using std and instead uses crate alloc.
8//!   Requires Rust 1.36 to disable.
9//!
10//! ### Rust Version
11//!
12//! This version of fixedbitset requires Rust 1.39 or later.
13//!
14#![doc(html_root_url = "https://docs.rs/fixedbitset/0.4.2/")]
15#![cfg_attr(not(feature = "std"), no_std)]
16
17#[cfg(not(feature = "std"))]
18extern crate alloc;
19#[cfg(not(feature = "std"))]
20use alloc::{vec, vec::Vec};
21
22#[cfg(not(feature = "std"))]
23use core as std;
24
25mod range;
26
27#[cfg(feature = "serde")]
28extern crate serde;
29#[cfg(feature = "serde")]
30use serde::{Deserialize, Serialize};
31
32use std::fmt::Write;
33use std::fmt::{Binary, Display, Error, Formatter};
34
35pub use range::IndexRange;
36use std::cmp::{Ord, Ordering};
37use std::iter::{Chain, FromIterator};
38use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Index};
39
40const BITS: usize = 32;
41type Block = u32;
42
43#[inline]
44fn div_rem(x: usize, d: usize) -> (usize, usize) {
45    (x / d, x % d)
46}
47
48/// `FixedBitSet` is a simple fixed size set of bits that each can
49/// be enabled (1 / **true**) or disabled (0 / **false**).
50///
51/// The bit set has a fixed capacity in terms of enabling bits (and the
52/// capacity can grow using the `grow` method).
53///
54/// Derived traits depend on both the zeros and ones, so [0,1] is not equal to
55/// [0,1,0].
56#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
57#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
58pub struct FixedBitSet {
59    data: Vec<Block>,
60    /// length in bits
61    length: usize,
62}
63
64impl FixedBitSet {
65    /// Create a new empty **FixedBitSet**.
66    pub const fn new() -> Self {
67        FixedBitSet {
68            data: Vec::new(),
69            length: 0,
70        }
71    }
72
73    /// Create a new **FixedBitSet** with a specific number of bits,
74    /// all initially clear.
75    pub fn with_capacity(bits: usize) -> Self {
76        let (mut blocks, rem) = div_rem(bits, BITS);
77        blocks += (rem > 0) as usize;
78        FixedBitSet {
79            data: vec![0; blocks],
80            length: bits,
81        }
82    }
83
84    /// Create a new **FixedBitSet** with a specific number of bits,
85    /// initialized from provided blocks.
86    ///
87    /// If the blocks are not the exact size needed for the capacity
88    /// they will be padded with zeros (if shorter) or truncated to
89    /// the capacity (if longer).
90    ///
91    /// For example:
92    /// ```
93    /// let data = vec![4];
94    /// let bs = fixedbitset::FixedBitSet::with_capacity_and_blocks(4, data);
95    /// assert_eq!(format!("{:b}", bs), "0010");
96    /// ```
97    pub fn with_capacity_and_blocks<I: IntoIterator<Item = Block>>(bits: usize, blocks: I) -> Self {
98        let (mut n_blocks, rem) = div_rem(bits, BITS);
99        n_blocks += (rem > 0) as usize;
100        let mut data: Vec<Block> = blocks.into_iter().collect();
101        // Pad data with zeros if smaller or truncate if larger
102        if data.len() != n_blocks {
103            data.resize(n_blocks, 0);
104        }
105        // Disable bits in blocks beyond capacity
106        let end = data.len() * 32;
107        for (block, mask) in Masks::new(bits..end, end) {
108            unsafe {
109                *data.get_unchecked_mut(block) &= !mask;
110            }
111        }
112        FixedBitSet { data, length: bits }
113    }
114
115    /// Grow capacity to **bits**, all new bits initialized to zero
116    pub fn grow(&mut self, bits: usize) {
117        let (mut blocks, rem) = div_rem(bits, BITS);
118        blocks += (rem > 0) as usize;
119        if bits > self.length {
120            self.length = bits;
121            self.data.resize(blocks, 0);
122        }
123    }
124
125    /// The length of the [`FixedBitSet`] in bits.
126    ///
127    /// Note: `len` includes both set and unset bits.
128    /// ```
129    /// # use fixedbitset::FixedBitSet;
130    /// let bitset = FixedBitSet::with_capacity(10);
131    /// // there are 0 set bits, but 10 unset bits
132    /// assert_eq!(bitset.len(), 10);
133    /// ```
134    /// `len` does not return the count of set bits. For that, use
135    /// [`bitset.count_ones(..)`](FixedBitSet::count_ones) instead.
136    #[inline]
137    pub fn len(&self) -> usize {
138        self.length
139    }
140
141    /// `true` if the [`FixedBitSet`] is empty.
142    ///
143    /// Note that an "empty" `FixedBitSet` is a `FixedBitSet` with
144    /// no bits (meaning: it's length is zero). If you want to check
145    /// if all bits are unset, use [`FixedBitSet::is_clear`].
146    ///
147    /// ```
148    /// # use fixedbitset::FixedBitSet;
149    /// let bitset = FixedBitSet::with_capacity(10);
150    /// assert!(!bitset.is_empty());
151    ///
152    /// let bitset = FixedBitSet::with_capacity(0);
153    /// assert!(bitset.is_empty());
154    /// ```
155    #[inline]
156    pub fn is_empty(&self) -> bool {
157        self.len() == 0
158    }
159
160    /// `true` if all bits in the [`FixedBitSet`] are unset.
161    ///
162    /// As opposed to [`FixedBitSet::is_empty`], which is `true` only for
163    /// sets without any bits, set or unset.
164    ///
165    /// ```
166    /// # use fixedbitset::FixedBitSet;
167    /// let mut bitset = FixedBitSet::with_capacity(10);
168    /// assert!(bitset.is_clear());
169    ///
170    /// bitset.insert(2);
171    /// assert!(!bitset.is_clear());
172    /// ```
173    ///
174    /// This is equivalent to [`bitset.count_ones(..) == 0`](FixedBitSet::count_ones).
175    #[inline]
176    pub fn is_clear(&self) -> bool {
177        self.data.iter().all(|block| *block == 0)
178    }
179
180    /// Return **true** if the bit is enabled in the **FixedBitSet**,
181    /// **false** otherwise.
182    ///
183    /// Note: bits outside the capacity are always disabled.
184    ///
185    /// Note: Also available with index syntax: `bitset[bit]`.
186    #[inline]
187    pub fn contains(&self, bit: usize) -> bool {
188        let (block, i) = div_rem(bit, BITS);
189        match self.data.get(block) {
190            None => false,
191            Some(b) => (b & (1 << i)) != 0,
192        }
193    }
194
195    /// Clear all bits.
196    #[inline]
197    pub fn clear(&mut self) {
198        for elt in &mut self.data[..] {
199            *elt = 0
200        }
201    }
202
203    /// Enable `bit`.
204    ///
205    /// **Panics** if **bit** is out of bounds.
206    #[inline]
207    pub fn insert(&mut self, bit: usize) {
208        assert!(
209            bit < self.length,
210            "insert at index {} exceeds fixbitset size {}",
211            bit,
212            self.length
213        );
214        let (block, i) = div_rem(bit, BITS);
215        unsafe {
216            *self.data.get_unchecked_mut(block) |= 1 << i;
217        }
218    }
219
220    /// Enable `bit`, and return its previous value.
221    ///
222    /// **Panics** if **bit** is out of bounds.
223    #[inline]
224    pub fn put(&mut self, bit: usize) -> bool {
225        assert!(
226            bit < self.length,
227            "put at index {} exceeds fixbitset size {}",
228            bit,
229            self.length
230        );
231        let (block, i) = div_rem(bit, BITS);
232        unsafe {
233            let word = self.data.get_unchecked_mut(block);
234            let prev = *word & (1 << i) != 0;
235            *word |= 1 << i;
236            prev
237        }
238    }
239    /// Toggle `bit` (inverting its state).
240    ///
241    /// ***Panics*** if **bit** is out of bounds
242    #[inline]
243    pub fn toggle(&mut self, bit: usize) {
244        assert!(
245            bit < self.length,
246            "toggle at index {} exceeds fixbitset size {}",
247            bit,
248            self.length
249        );
250        let (block, i) = div_rem(bit, BITS);
251        unsafe {
252            *self.data.get_unchecked_mut(block) ^= 1 << i;
253        }
254    }
255    /// **Panics** if **bit** is out of bounds.
256    #[inline]
257    pub fn set(&mut self, bit: usize, enabled: bool) {
258        assert!(
259            bit < self.length,
260            "set at index {} exceeds fixbitset size {}",
261            bit,
262            self.length
263        );
264        let (block, i) = div_rem(bit, BITS);
265        unsafe {
266            let elt = self.data.get_unchecked_mut(block);
267            if enabled {
268                *elt |= 1 << i;
269            } else {
270                *elt &= !(1 << i);
271            }
272        }
273    }
274
275    /// Copies boolean value from specified bit to the specified bit.
276    ///
277    /// **Panics** if **to** is out of bounds.
278    #[inline]
279    pub fn copy_bit(&mut self, from: usize, to: usize) {
280        assert!(
281            to < self.length,
282            "copy at index {} exceeds fixbitset size {}",
283            to,
284            self.length
285        );
286        let (to_block, t) = div_rem(to, BITS);
287        let enabled = self.contains(from);
288        unsafe {
289            let to_elt = self.data.get_unchecked_mut(to_block);
290            if enabled {
291                *to_elt |= 1 << t;
292            } else {
293                *to_elt &= !(1 << t);
294            }
295        }
296    }
297
298    /// Count the number of set bits in the given bit range.
299    ///
300    /// Use `..` to count the whole content of the bitset.
301    ///
302    /// **Panics** if the range extends past the end of the bitset.
303    #[inline]
304    pub fn count_ones<T: IndexRange>(&self, range: T) -> usize {
305        Masks::new(range, self.length)
306            .map(|(block, mask)| unsafe {
307                let value = *self.data.get_unchecked(block);
308                (value & mask).count_ones() as usize
309            })
310            .sum()
311    }
312
313    /// Sets every bit in the given range to the given state (`enabled`)
314    ///
315    /// Use `..` to set the whole bitset.
316    ///
317    /// **Panics** if the range extends past the end of the bitset.
318    #[inline]
319    pub fn set_range<T: IndexRange>(&mut self, range: T, enabled: bool) {
320        for (block, mask) in Masks::new(range, self.length) {
321            unsafe {
322                if enabled {
323                    *self.data.get_unchecked_mut(block) |= mask;
324                } else {
325                    *self.data.get_unchecked_mut(block) &= !mask;
326                }
327            }
328        }
329    }
330
331    /// Enables every bit in the given range.
332    ///
333    /// Use `..` to make the whole bitset ones.
334    ///
335    /// **Panics** if the range extends past the end of the bitset.
336    #[inline]
337    pub fn insert_range<T: IndexRange>(&mut self, range: T) {
338        self.set_range(range, true);
339    }
340
341    /// Toggles (inverts) every bit in the given range.
342    ///
343    /// Use `..` to toggle the whole bitset.
344    ///
345    /// **Panics** if the range extends past the end of the bitset.
346    #[inline]
347    pub fn toggle_range<T: IndexRange>(&mut self, range: T) {
348        for (block, mask) in Masks::new(range, self.length) {
349            unsafe {
350                *self.data.get_unchecked_mut(block) ^= mask;
351            }
352        }
353    }
354
355    /// View the bitset as a slice of `u32` blocks
356    #[inline]
357    pub fn as_slice(&self) -> &[u32] {
358        &self.data
359    }
360
361    /// View the bitset as a mutable slice of `u32` blocks. Writing past the bitlength in the last
362    /// will cause `contains` to return potentially incorrect results for bits past the bitlength.
363    #[inline]
364    pub fn as_mut_slice(&mut self) -> &mut [u32] {
365        &mut self.data
366    }
367
368    /// Iterates over all enabled bits.
369    ///
370    /// Iterator element is the index of the `1` bit, type `usize`.
371    #[inline]
372    pub fn ones(&self) -> Ones {
373        match self.as_slice().split_first() {
374            Some((&block, rem)) => Ones {
375                bitset: block,
376                block_idx: 0,
377                remaining_blocks: rem,
378            },
379            None => Ones {
380                bitset: 0,
381                block_idx: 0,
382                remaining_blocks: &[],
383            },
384        }
385    }
386
387    /// Returns a lazy iterator over the intersection of two `FixedBitSet`s
388    pub fn intersection<'a>(&'a self, other: &'a FixedBitSet) -> Intersection<'a> {
389        Intersection {
390            iter: self.ones(),
391            other,
392        }
393    }
394
395    /// Returns a lazy iterator over the union of two `FixedBitSet`s.
396    pub fn union<'a>(&'a self, other: &'a FixedBitSet) -> Union<'a> {
397        Union {
398            iter: self.ones().chain(other.difference(self)),
399        }
400    }
401
402    /// Returns a lazy iterator over the difference of two `FixedBitSet`s. The difference of `a`
403    /// and `b` is the elements of `a` which are not in `b`.
404    pub fn difference<'a>(&'a self, other: &'a FixedBitSet) -> Difference<'a> {
405        Difference {
406            iter: self.ones(),
407            other,
408        }
409    }
410
411    /// Returns a lazy iterator over the symmetric difference of two `FixedBitSet`s.
412    /// The symmetric difference of `a` and `b` is the elements of one, but not both, sets.
413    pub fn symmetric_difference<'a>(&'a self, other: &'a FixedBitSet) -> SymmetricDifference<'a> {
414        SymmetricDifference {
415            iter: self.difference(other).chain(other.difference(self)),
416        }
417    }
418
419    /// In-place union of two `FixedBitSet`s.
420    ///
421    /// On calling this method, `self`'s capacity may be increased to match `other`'s.
422    pub fn union_with(&mut self, other: &FixedBitSet) {
423        if other.len() >= self.len() {
424            self.grow(other.len());
425        }
426        for (x, y) in self.data.iter_mut().zip(other.data.iter()) {
427            *x |= *y;
428        }
429    }
430
431    /// In-place intersection of two `FixedBitSet`s.
432    ///
433    /// On calling this method, `self`'s capacity will remain the same as before.
434    pub fn intersect_with(&mut self, other: &FixedBitSet) {
435        for (x, y) in self.data.iter_mut().zip(other.data.iter()) {
436            *x &= *y;
437        }
438        let mn = std::cmp::min(self.data.len(), other.data.len());
439        for wd in &mut self.data[mn..] {
440            *wd = 0;
441        }
442    }
443
444    /// In-place difference of two `FixedBitSet`s.
445    ///
446    /// On calling this method, `self`'s capacity will remain the same as before.
447    pub fn difference_with(&mut self, other: &FixedBitSet) {
448        for (x, y) in self.data.iter_mut().zip(other.data.iter()) {
449            *x &= !*y;
450        }
451
452        // There's no need to grow self or do any other adjustments.
453        //
454        // * If self is longer than other, the bits at the end of self won't be affected since other
455        //   has them implicitly set to 0.
456        // * If other is longer than self, the bits at the end of other are irrelevant since self
457        //   has them set to 0 anyway.
458    }
459
460    /// In-place symmetric difference of two `FixedBitSet`s.
461    ///
462    /// On calling this method, `self`'s capacity may be increased to match `other`'s.
463    pub fn symmetric_difference_with(&mut self, other: &FixedBitSet) {
464        if other.len() >= self.len() {
465            self.grow(other.len());
466        }
467        for (x, y) in self.data.iter_mut().zip(other.data.iter()) {
468            *x ^= *y;
469        }
470    }
471
472    /// Returns `true` if `self` has no elements in common with `other`. This
473    /// is equivalent to checking for an empty intersection.
474    pub fn is_disjoint(&self, other: &FixedBitSet) -> bool {
475        self.data
476            .iter()
477            .zip(other.data.iter())
478            .all(|(x, y)| x & y == 0)
479    }
480
481    /// Returns `true` if the set is a subset of another, i.e. `other` contains
482    /// at least all the values in `self`.
483    pub fn is_subset(&self, other: &FixedBitSet) -> bool {
484        self.data
485            .iter()
486            .zip(other.data.iter())
487            .all(|(x, y)| x & !y == 0)
488            && self.data.iter().skip(other.data.len()).all(|x| *x == 0)
489    }
490
491    /// Returns `true` if the set is a superset of another, i.e. `self` contains
492    /// at least all the values in `other`.
493    pub fn is_superset(&self, other: &FixedBitSet) -> bool {
494        other.is_subset(self)
495    }
496}
497
498impl Binary for FixedBitSet {
499    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
500        if f.alternate() {
501            f.write_str("0b")?;
502        }
503
504        for i in 0..self.length {
505            if self[i] {
506                f.write_char('1')?;
507            } else {
508                f.write_char('0')?;
509            }
510        }
511
512        Ok(())
513    }
514}
515
516impl Display for FixedBitSet {
517    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
518        Binary::fmt(&self, f)
519    }
520}
521
522/// An iterator producing elements in the difference of two sets.
523///
524/// This struct is created by the [`FixedBitSet::difference`] method.
525pub struct Difference<'a> {
526    iter: Ones<'a>,
527    other: &'a FixedBitSet,
528}
529
530impl<'a> Iterator for Difference<'a> {
531    type Item = usize;
532
533    #[inline]
534    fn next(&mut self) -> Option<Self::Item> {
535        while let Some(nxt) = self.iter.next() {
536            if !self.other.contains(nxt) {
537                return Some(nxt);
538            }
539        }
540        None
541    }
542}
543
544/// An iterator producing elements in the symmetric difference of two sets.
545///
546/// This struct is created by the [`FixedBitSet::symmetric_difference`] method.
547pub struct SymmetricDifference<'a> {
548    iter: Chain<Difference<'a>, Difference<'a>>,
549}
550
551impl<'a> Iterator for SymmetricDifference<'a> {
552    type Item = usize;
553
554    #[inline]
555    fn next(&mut self) -> Option<Self::Item> {
556        self.iter.next()
557    }
558}
559
560/// An iterator producing elements in the intersection of two sets.
561///
562/// This struct is created by the [`FixedBitSet::intersection`] method.
563pub struct Intersection<'a> {
564    iter: Ones<'a>,
565    other: &'a FixedBitSet,
566}
567
568impl<'a> Iterator for Intersection<'a> {
569    type Item = usize; // the bit position of the '1'
570
571    #[inline]
572    fn next(&mut self) -> Option<Self::Item> {
573        while let Some(nxt) = self.iter.next() {
574            if self.other.contains(nxt) {
575                return Some(nxt);
576            }
577        }
578        None
579    }
580}
581
582/// An iterator producing elements in the union of two sets.
583///
584/// This struct is created by the [`FixedBitSet::union`] method.
585pub struct Union<'a> {
586    iter: Chain<Ones<'a>, Difference<'a>>,
587}
588
589impl<'a> Iterator for Union<'a> {
590    type Item = usize;
591
592    #[inline]
593    fn next(&mut self) -> Option<Self::Item> {
594        self.iter.next()
595    }
596}
597
598struct Masks {
599    first_block: usize,
600    first_mask: Block,
601    last_block: usize,
602    last_mask: Block,
603}
604
605impl Masks {
606    #[inline]
607    fn new<T: IndexRange>(range: T, length: usize) -> Masks {
608        let start = range.start().unwrap_or(0);
609        let end = range.end().unwrap_or(length);
610        assert!(
611            start <= end && end <= length,
612            "invalid range {}..{} for a fixedbitset of size {}",
613            start,
614            end,
615            length
616        );
617
618        let (first_block, first_rem) = div_rem(start, BITS);
619        let (last_block, last_rem) = div_rem(end, BITS);
620
621        Masks {
622            first_block: first_block as usize,
623            first_mask: Block::max_value() << first_rem,
624            last_block: last_block as usize,
625            last_mask: (Block::max_value() >> 1) >> (BITS - last_rem - 1),
626            // this is equivalent to `MAX >> (BITS - x)` with correct semantics when x == 0.
627        }
628    }
629}
630
631impl Iterator for Masks {
632    type Item = (usize, Block);
633    #[inline]
634    fn next(&mut self) -> Option<Self::Item> {
635        match self.first_block.cmp(&self.last_block) {
636            Ordering::Less => {
637                let res = (self.first_block, self.first_mask);
638                self.first_block += 1;
639                self.first_mask = !0;
640                Some(res)
641            }
642            Ordering::Equal => {
643                let mask = self.first_mask & self.last_mask;
644                let res = if mask == 0 {
645                    None
646                } else {
647                    Some((self.first_block, mask))
648                };
649                self.first_block += 1;
650                res
651            }
652            Ordering::Greater => None,
653        }
654    }
655}
656
657/// An  iterator producing the indices of the set bit in a set.
658///
659/// This struct is created by the [`FixedBitSet::ones`] method.
660pub struct Ones<'a> {
661    bitset: Block,
662    block_idx: usize,
663    remaining_blocks: &'a [Block],
664}
665
666impl<'a> Iterator for Ones<'a> {
667    type Item = usize; // the bit position of the '1'
668
669    #[inline]
670    fn next(&mut self) -> Option<Self::Item> {
671        while self.bitset == 0 {
672            if self.remaining_blocks.is_empty() {
673                return None;
674            }
675            self.bitset = self.remaining_blocks[0];
676            self.remaining_blocks = &self.remaining_blocks[1..];
677            self.block_idx += 1;
678        }
679        let t = self.bitset & (0 as Block).wrapping_sub(self.bitset);
680        let r = self.bitset.trailing_zeros() as usize;
681        self.bitset ^= t;
682        Some(self.block_idx * BITS + r)
683    }
684}
685
686impl Clone for FixedBitSet {
687    #[inline]
688    fn clone(&self) -> Self {
689        FixedBitSet {
690            data: self.data.clone(),
691            length: self.length,
692        }
693    }
694}
695
696/// Return **true** if the bit is enabled in the bitset,
697/// or **false** otherwise.
698///
699/// Note: bits outside the capacity are always disabled, and thus
700/// indexing a FixedBitSet will not panic.
701impl Index<usize> for FixedBitSet {
702    type Output = bool;
703
704    #[inline]
705    fn index(&self, bit: usize) -> &bool {
706        if self.contains(bit) {
707            &true
708        } else {
709            &false
710        }
711    }
712}
713
714/// Sets the bit at index **i** to **true** for each item **i** in the input **src**.
715impl Extend<usize> for FixedBitSet {
716    fn extend<I: IntoIterator<Item = usize>>(&mut self, src: I) {
717        let iter = src.into_iter();
718        for i in iter {
719            if i >= self.len() {
720                self.grow(i + 1);
721            }
722            self.put(i);
723        }
724    }
725}
726
727/// Return a FixedBitSet containing bits set to **true** for every bit index in
728/// the iterator, other bits are set to **false**.
729impl FromIterator<usize> for FixedBitSet {
730    fn from_iter<I: IntoIterator<Item = usize>>(src: I) -> Self {
731        let mut fbs = FixedBitSet::with_capacity(0);
732        fbs.extend(src);
733        fbs
734    }
735}
736
737impl<'a> BitAnd for &'a FixedBitSet {
738    type Output = FixedBitSet;
739    fn bitand(self, other: &FixedBitSet) -> FixedBitSet {
740        let (short, long) = {
741            if self.len() <= other.len() {
742                (&self.data, &other.data)
743            } else {
744                (&other.data, &self.data)
745            }
746        };
747        let mut data = short.clone();
748        for (data, block) in data.iter_mut().zip(long.iter()) {
749            *data &= *block;
750        }
751        let len = std::cmp::min(self.len(), other.len());
752        FixedBitSet { data, length: len }
753    }
754}
755
756impl<'a> BitAndAssign for FixedBitSet {
757    fn bitand_assign(&mut self, other: Self) {
758        self.intersect_with(&other);
759    }
760}
761
762impl<'a> BitAndAssign<&Self> for FixedBitSet {
763    fn bitand_assign(&mut self, other: &Self) {
764        self.intersect_with(other);
765    }
766}
767
768impl<'a> BitOr for &'a FixedBitSet {
769    type Output = FixedBitSet;
770    fn bitor(self, other: &FixedBitSet) -> FixedBitSet {
771        let (short, long) = {
772            if self.len() <= other.len() {
773                (&self.data, &other.data)
774            } else {
775                (&other.data, &self.data)
776            }
777        };
778        let mut data = long.clone();
779        for (data, block) in data.iter_mut().zip(short.iter()) {
780            *data |= *block;
781        }
782        let len = std::cmp::max(self.len(), other.len());
783        FixedBitSet { data, length: len }
784    }
785}
786
787impl<'a> BitOrAssign for FixedBitSet {
788    fn bitor_assign(&mut self, other: Self) {
789        self.union_with(&other);
790    }
791}
792
793impl<'a> BitOrAssign<&Self> for FixedBitSet {
794    fn bitor_assign(&mut self, other: &Self) {
795        self.union_with(other);
796    }
797}
798
799impl<'a> BitXor for &'a FixedBitSet {
800    type Output = FixedBitSet;
801    fn bitxor(self, other: &FixedBitSet) -> FixedBitSet {
802        let (short, long) = {
803            if self.len() <= other.len() {
804                (&self.data, &other.data)
805            } else {
806                (&other.data, &self.data)
807            }
808        };
809        let mut data = long.clone();
810        for (data, block) in data.iter_mut().zip(short.iter()) {
811            *data ^= *block;
812        }
813        let len = std::cmp::max(self.len(), other.len());
814        FixedBitSet { data, length: len }
815    }
816}
817
818impl<'a> BitXorAssign for FixedBitSet {
819    fn bitxor_assign(&mut self, other: Self) {
820        self.symmetric_difference_with(&other);
821    }
822}
823
824impl<'a> BitXorAssign<&Self> for FixedBitSet {
825    fn bitxor_assign(&mut self, other: &Self) {
826        self.symmetric_difference_with(other);
827    }
828}
829
830#[test]
831fn it_works() {
832    const N: usize = 50;
833    let mut fb = FixedBitSet::with_capacity(N);
834
835    for i in 0..(N + 10) {
836        assert_eq!(fb.contains(i), false);
837    }
838
839    fb.insert(10);
840    fb.set(11, false);
841    fb.set(12, false);
842    fb.set(12, true);
843    fb.set(N - 1, true);
844
845    assert!(fb.contains(10));
846    assert!(!fb.contains(11));
847    assert!(fb.contains(12));
848    assert!(fb.contains(N - 1));
849    for i in 0..N {
850        let contain = i == 10 || i == 12 || i == N - 1;
851        assert_eq!(contain, fb[i]);
852    }
853
854    fb.clear();
855}
856
857#[test]
858fn with_blocks() {
859    let fb = FixedBitSet::with_capacity_and_blocks(50, vec![8u32, 0u32]);
860    assert!(fb.contains(3));
861
862    let ones: Vec<_> = fb.ones().collect();
863    assert_eq!(ones.len(), 1);
864}
865
866#[test]
867fn with_blocks_too_small() {
868    let mut fb = FixedBitSet::with_capacity_and_blocks(500, vec![8u32, 0u32]);
869    fb.insert(400);
870    assert!(fb.contains(400));
871}
872
873#[test]
874fn with_blocks_too_big() {
875    let fb = FixedBitSet::with_capacity_and_blocks(1, vec![8u32]);
876
877    // since capacity is 1, 3 shouldn't be set here
878    assert!(!fb.contains(3));
879}
880
881#[test]
882fn with_blocks_too_big_range_check() {
883    let fb = FixedBitSet::with_capacity_and_blocks(1, vec![0xff]);
884
885    // since capacity is 1, only 0 should be set
886    assert!(fb.contains(0));
887    for i in 1..0xff {
888        assert!(!fb.contains(i));
889    }
890}
891
892#[test]
893fn grow() {
894    let mut fb = FixedBitSet::with_capacity(48);
895    for i in 0..fb.len() {
896        fb.set(i, true);
897    }
898
899    let old_len = fb.len();
900    fb.grow(72);
901    for j in 0..fb.len() {
902        assert_eq!(fb.contains(j), j < old_len);
903    }
904    fb.set(64, true);
905    assert!(fb.contains(64));
906}
907
908#[test]
909fn test_toggle() {
910    let mut fb = FixedBitSet::with_capacity(16);
911    fb.toggle(1);
912    fb.put(2);
913    fb.toggle(2);
914    fb.put(3);
915    assert!(fb.contains(1));
916    assert!(!fb.contains(2));
917    assert!(fb.contains(3));
918}
919
920#[test]
921fn copy_bit() {
922    let mut fb = FixedBitSet::with_capacity(48);
923    for i in 0..fb.len() {
924        fb.set(i, true);
925    }
926    fb.set(42, false);
927    fb.copy_bit(42, 2);
928    assert!(!fb.contains(42));
929    assert!(!fb.contains(2));
930    assert!(fb.contains(1));
931    fb.copy_bit(1, 42);
932    assert!(fb.contains(42));
933    fb.copy_bit(1024, 42);
934    assert!(!fb[42]);
935}
936
937#[test]
938fn count_ones() {
939    let mut fb = FixedBitSet::with_capacity(100);
940    fb.set(11, true);
941    fb.set(12, true);
942    fb.set(7, true);
943    fb.set(35, true);
944    fb.set(40, true);
945    fb.set(77, true);
946    fb.set(95, true);
947    fb.set(50, true);
948    fb.set(99, true);
949    assert_eq!(fb.count_ones(..7), 0);
950    assert_eq!(fb.count_ones(..8), 1);
951    assert_eq!(fb.count_ones(..11), 1);
952    assert_eq!(fb.count_ones(..12), 2);
953    assert_eq!(fb.count_ones(..13), 3);
954    assert_eq!(fb.count_ones(..35), 3);
955    assert_eq!(fb.count_ones(..36), 4);
956    assert_eq!(fb.count_ones(..40), 4);
957    assert_eq!(fb.count_ones(..41), 5);
958    assert_eq!(fb.count_ones(50..), 4);
959    assert_eq!(fb.count_ones(70..95), 1);
960    assert_eq!(fb.count_ones(70..96), 2);
961    assert_eq!(fb.count_ones(70..99), 2);
962    assert_eq!(fb.count_ones(..), 9);
963    assert_eq!(fb.count_ones(0..100), 9);
964    assert_eq!(fb.count_ones(0..0), 0);
965    assert_eq!(fb.count_ones(100..100), 0);
966    assert_eq!(fb.count_ones(7..), 9);
967    assert_eq!(fb.count_ones(8..), 8);
968}
969
970#[test]
971fn ones() {
972    let mut fb = FixedBitSet::with_capacity(100);
973    fb.set(11, true);
974    fb.set(12, true);
975    fb.set(7, true);
976    fb.set(35, true);
977    fb.set(40, true);
978    fb.set(77, true);
979    fb.set(95, true);
980    fb.set(50, true);
981    fb.set(99, true);
982
983    let ones: Vec<_> = fb.ones().collect();
984
985    assert_eq!(vec![7, 11, 12, 35, 40, 50, 77, 95, 99], ones);
986}
987
988#[test]
989fn iter_ones_range() {
990    fn test_range(from: usize, to: usize, capa: usize) {
991        assert!(to <= capa);
992        let mut fb = FixedBitSet::with_capacity(capa);
993        for i in from..to {
994            fb.insert(i);
995        }
996        let ones: Vec<_> = fb.ones().collect();
997        let expected: Vec<_> = (from..to).collect();
998        assert_eq!(expected, ones);
999    }
1000
1001    for i in 0..100 {
1002        test_range(i, 100, 100);
1003        test_range(0, i, 100);
1004    }
1005}
1006
1007#[should_panic]
1008#[test]
1009fn count_ones_oob() {
1010    let fb = FixedBitSet::with_capacity(100);
1011    fb.count_ones(90..101);
1012}
1013
1014#[should_panic]
1015#[test]
1016fn count_ones_negative_range() {
1017    let fb = FixedBitSet::with_capacity(100);
1018    fb.count_ones(90..80);
1019}
1020
1021#[test]
1022fn count_ones_panic() {
1023    for i in 1..128 {
1024        let fb = FixedBitSet::with_capacity(i);
1025        for j in 0..fb.len() + 1 {
1026            for k in j..fb.len() + 1 {
1027                assert_eq!(fb.count_ones(j..k), 0);
1028            }
1029        }
1030    }
1031}
1032
1033#[test]
1034fn default() {
1035    let fb = FixedBitSet::default();
1036    assert_eq!(fb.len(), 0);
1037}
1038
1039#[test]
1040fn insert_range() {
1041    let mut fb = FixedBitSet::with_capacity(97);
1042    fb.insert_range(..3);
1043    fb.insert_range(9..32);
1044    fb.insert_range(37..81);
1045    fb.insert_range(90..);
1046    for i in 0..97 {
1047        assert_eq!(
1048            fb.contains(i),
1049            i < 3 || 9 <= i && i < 32 || 37 <= i && i < 81 || 90 <= i
1050        );
1051    }
1052    assert!(!fb.contains(97));
1053    assert!(!fb.contains(127));
1054    assert!(!fb.contains(128));
1055}
1056
1057#[test]
1058fn set_range() {
1059    let mut fb = FixedBitSet::with_capacity(48);
1060    fb.insert_range(..);
1061
1062    fb.set_range(..32, false);
1063    fb.set_range(37.., false);
1064    fb.set_range(5..9, true);
1065    fb.set_range(40..40, true);
1066
1067    for i in 0..48 {
1068        assert_eq!(fb.contains(i), 5 <= i && i < 9 || 32 <= i && i < 37);
1069    }
1070    assert!(!fb.contains(48));
1071    assert!(!fb.contains(64));
1072}
1073
1074#[test]
1075fn toggle_range() {
1076    let mut fb = FixedBitSet::with_capacity(40);
1077    fb.insert_range(..10);
1078    fb.insert_range(34..38);
1079
1080    fb.toggle_range(5..12);
1081    fb.toggle_range(30..);
1082
1083    for i in 0..40 {
1084        assert_eq!(
1085            fb.contains(i),
1086            i < 5 || 10 <= i && i < 12 || 30 <= i && i < 34 || 38 <= i
1087        );
1088    }
1089    assert!(!fb.contains(40));
1090    assert!(!fb.contains(64));
1091}
1092
1093#[test]
1094fn bitand_equal_lengths() {
1095    let len = 109;
1096    let a_end = 59;
1097    let b_start = 23;
1098    let mut a = FixedBitSet::with_capacity(len);
1099    let mut b = FixedBitSet::with_capacity(len);
1100    a.set_range(..a_end, true);
1101    b.set_range(b_start.., true);
1102    let ab = &a & &b;
1103    for i in 0..b_start {
1104        assert!(!ab.contains(i));
1105    }
1106    for i in b_start..a_end {
1107        assert!(ab.contains(i));
1108    }
1109    for i in a_end..len {
1110        assert!(!ab.contains(i));
1111    }
1112    assert_eq!(a.len(), ab.len());
1113}
1114
1115#[test]
1116fn bitand_first_smaller() {
1117    let a_len = 113;
1118    let b_len = 137;
1119    let len = std::cmp::min(a_len, b_len);
1120    let a_end = 97;
1121    let b_start = 89;
1122    let mut a = FixedBitSet::with_capacity(a_len);
1123    let mut b = FixedBitSet::with_capacity(b_len);
1124    a.set_range(..a_end, true);
1125    b.set_range(b_start.., true);
1126    let ab = &a & &b;
1127    for i in 0..b_start {
1128        assert!(!ab.contains(i));
1129    }
1130    for i in b_start..a_end {
1131        assert!(ab.contains(i));
1132    }
1133    for i in a_end..len {
1134        assert!(!ab.contains(i));
1135    }
1136    assert_eq!(a.len(), ab.len());
1137}
1138
1139#[test]
1140fn bitand_first_larger() {
1141    let a_len = 173;
1142    let b_len = 137;
1143    let len = std::cmp::min(a_len, b_len);
1144    let a_end = 107;
1145    let b_start = 43;
1146    let mut a = FixedBitSet::with_capacity(a_len);
1147    let mut b = FixedBitSet::with_capacity(b_len);
1148    a.set_range(..a_end, true);
1149    b.set_range(b_start.., true);
1150    let ab = &a & &b;
1151    for i in 0..b_start {
1152        assert!(!ab.contains(i));
1153    }
1154    for i in b_start..a_end {
1155        assert!(ab.contains(i));
1156    }
1157    for i in a_end..len {
1158        assert!(!ab.contains(i));
1159    }
1160    assert_eq!(b.len(), ab.len());
1161}
1162
1163#[test]
1164fn intersection() {
1165    let len = 109;
1166    let a_end = 59;
1167    let b_start = 23;
1168    let mut a = FixedBitSet::with_capacity(len);
1169    let mut b = FixedBitSet::with_capacity(len);
1170    a.set_range(..a_end, true);
1171    b.set_range(b_start.., true);
1172
1173    let mut ab = a.intersection(&b).collect::<FixedBitSet>();
1174
1175    for i in 0..b_start {
1176        assert!(!ab.contains(i));
1177    }
1178    for i in b_start..a_end {
1179        assert!(ab.contains(i));
1180    }
1181    for i in a_end..len {
1182        assert!(!ab.contains(i));
1183    }
1184
1185    a.intersect_with(&b);
1186    // intersection + collect produces the same results but with a shorter length.
1187    ab.grow(a.len());
1188    assert_eq!(
1189        ab, a,
1190        "intersection and intersect_with produce the same results"
1191    );
1192}
1193
1194#[test]
1195fn union() {
1196    let a_len = 173;
1197    let b_len = 137;
1198    let a_start = 139;
1199    let b_end = 107;
1200    let mut a = FixedBitSet::with_capacity(a_len);
1201    let mut b = FixedBitSet::with_capacity(b_len);
1202    a.set_range(a_start.., true);
1203    b.set_range(..b_end, true);
1204    let ab = a.union(&b).collect::<FixedBitSet>();
1205    for i in a_start..a_len {
1206        assert!(ab.contains(i));
1207    }
1208    for i in 0..b_end {
1209        assert!(ab.contains(i));
1210    }
1211    for i in b_end..a_start {
1212        assert!(!ab.contains(i));
1213    }
1214
1215    a.union_with(&b);
1216    assert_eq!(ab, a, "union and union_with produce the same results");
1217}
1218
1219#[test]
1220fn difference() {
1221    let a_len = 83;
1222    let b_len = 151;
1223    let a_start = 0;
1224    let a_end = 79;
1225    let b_start = 53;
1226    let mut a = FixedBitSet::with_capacity(a_len);
1227    let mut b = FixedBitSet::with_capacity(b_len);
1228    a.set_range(a_start..a_end, true);
1229    b.set_range(b_start..b_len, true);
1230    let mut a_diff_b = a.difference(&b).collect::<FixedBitSet>();
1231    for i in a_start..b_start {
1232        assert!(a_diff_b.contains(i));
1233    }
1234    for i in b_start..b_len {
1235        assert!(!a_diff_b.contains(i));
1236    }
1237
1238    a.difference_with(&b);
1239    // difference + collect produces the same results but with a shorter length.
1240    a_diff_b.grow(a.len());
1241    assert_eq!(
1242        a_diff_b, a,
1243        "difference and difference_with produce the same results"
1244    );
1245}
1246
1247#[test]
1248fn symmetric_difference() {
1249    let a_len = 83;
1250    let b_len = 151;
1251    let a_start = 47;
1252    let a_end = 79;
1253    let b_start = 53;
1254    let mut a = FixedBitSet::with_capacity(a_len);
1255    let mut b = FixedBitSet::with_capacity(b_len);
1256    a.set_range(a_start..a_end, true);
1257    b.set_range(b_start..b_len, true);
1258    let a_sym_diff_b = a.symmetric_difference(&b).collect::<FixedBitSet>();
1259    for i in 0..a_start {
1260        assert!(!a_sym_diff_b.contains(i));
1261    }
1262    for i in a_start..b_start {
1263        assert!(a_sym_diff_b.contains(i));
1264    }
1265    for i in b_start..a_end {
1266        assert!(!a_sym_diff_b.contains(i));
1267    }
1268    for i in a_end..b_len {
1269        assert!(a_sym_diff_b.contains(i));
1270    }
1271
1272    a.symmetric_difference_with(&b);
1273    assert_eq!(
1274        a_sym_diff_b, a,
1275        "symmetric_difference and _with produce the same results"
1276    );
1277}
1278
1279#[test]
1280fn bitor_equal_lengths() {
1281    let len = 109;
1282    let a_start = 17;
1283    let a_end = 23;
1284    let b_start = 19;
1285    let b_end = 59;
1286    let mut a = FixedBitSet::with_capacity(len);
1287    let mut b = FixedBitSet::with_capacity(len);
1288    a.set_range(a_start..a_end, true);
1289    b.set_range(b_start..b_end, true);
1290    let ab = &a | &b;
1291    for i in 0..a_start {
1292        assert!(!ab.contains(i));
1293    }
1294    for i in a_start..b_end {
1295        assert!(ab.contains(i));
1296    }
1297    for i in b_end..len {
1298        assert!(!ab.contains(i));
1299    }
1300    assert_eq!(ab.len(), len);
1301}
1302
1303#[test]
1304fn bitor_first_smaller() {
1305    let a_len = 113;
1306    let b_len = 137;
1307    let a_end = 89;
1308    let b_start = 97;
1309    let mut a = FixedBitSet::with_capacity(a_len);
1310    let mut b = FixedBitSet::with_capacity(b_len);
1311    a.set_range(..a_end, true);
1312    b.set_range(b_start.., true);
1313    let ab = &a | &b;
1314    for i in 0..a_end {
1315        assert!(ab.contains(i));
1316    }
1317    for i in a_end..b_start {
1318        assert!(!ab.contains(i));
1319    }
1320    for i in b_start..b_len {
1321        assert!(ab.contains(i));
1322    }
1323    assert_eq!(b_len, ab.len());
1324}
1325
1326#[test]
1327fn bitor_first_larger() {
1328    let a_len = 173;
1329    let b_len = 137;
1330    let a_start = 139;
1331    let b_end = 107;
1332    let mut a = FixedBitSet::with_capacity(a_len);
1333    let mut b = FixedBitSet::with_capacity(b_len);
1334    a.set_range(a_start.., true);
1335    b.set_range(..b_end, true);
1336    let ab = &a | &b;
1337    for i in a_start..a_len {
1338        assert!(ab.contains(i));
1339    }
1340    for i in 0..b_end {
1341        assert!(ab.contains(i));
1342    }
1343    for i in b_end..a_start {
1344        assert!(!ab.contains(i));
1345    }
1346    assert_eq!(a_len, ab.len());
1347}
1348
1349#[test]
1350fn bitxor_equal_lengths() {
1351    let len = 109;
1352    let a_end = 59;
1353    let b_start = 23;
1354    let mut a = FixedBitSet::with_capacity(len);
1355    let mut b = FixedBitSet::with_capacity(len);
1356    a.set_range(..a_end, true);
1357    b.set_range(b_start.., true);
1358    let ab = &a ^ &b;
1359    for i in 0..b_start {
1360        assert!(ab.contains(i));
1361    }
1362    for i in b_start..a_end {
1363        assert!(!ab.contains(i));
1364    }
1365    for i in a_end..len {
1366        assert!(ab.contains(i));
1367    }
1368    assert_eq!(a.len(), ab.len());
1369}
1370
1371#[test]
1372fn bitxor_first_smaller() {
1373    let a_len = 113;
1374    let b_len = 137;
1375    let len = std::cmp::max(a_len, b_len);
1376    let a_end = 97;
1377    let b_start = 89;
1378    let mut a = FixedBitSet::with_capacity(a_len);
1379    let mut b = FixedBitSet::with_capacity(b_len);
1380    a.set_range(..a_end, true);
1381    b.set_range(b_start.., true);
1382    let ab = &a ^ &b;
1383    for i in 0..b_start {
1384        assert!(ab.contains(i));
1385    }
1386    for i in b_start..a_end {
1387        assert!(!ab.contains(i));
1388    }
1389    for i in a_end..len {
1390        assert!(ab.contains(i));
1391    }
1392    assert_eq!(b.len(), ab.len());
1393}
1394
1395#[test]
1396fn bitxor_first_larger() {
1397    let a_len = 173;
1398    let b_len = 137;
1399    let len = std::cmp::max(a_len, b_len);
1400    let a_end = 107;
1401    let b_start = 43;
1402    let mut a = FixedBitSet::with_capacity(a_len);
1403    let mut b = FixedBitSet::with_capacity(b_len);
1404    a.set_range(..a_end, true);
1405    b.set_range(b_start.., true);
1406    let ab = &a ^ &b;
1407    for i in 0..b_start {
1408        assert!(ab.contains(i));
1409    }
1410    for i in b_start..a_end {
1411        assert!(!ab.contains(i));
1412    }
1413    for i in a_end..b_len {
1414        assert!(ab.contains(i));
1415    }
1416    for i in b_len..len {
1417        assert!(!ab.contains(i));
1418    }
1419    assert_eq!(a.len(), ab.len());
1420}
1421
1422#[test]
1423fn bitand_assign_shorter() {
1424    let a_ones: Vec<usize> = vec![2, 3, 7, 19, 31, 32, 37, 41, 43, 47, 71, 73, 101];
1425    let b_ones: Vec<usize> = vec![2, 7, 8, 11, 23, 31, 32];
1426    let a_and_b: Vec<usize> = vec![2, 7, 31, 32];
1427    let mut a = a_ones.iter().cloned().collect::<FixedBitSet>();
1428    let b = b_ones.iter().cloned().collect::<FixedBitSet>();
1429    a &= b;
1430    let res = a.ones().collect::<Vec<usize>>();
1431
1432    assert!(res == a_and_b);
1433}
1434
1435#[test]
1436fn bitand_assign_longer() {
1437    let a_ones: Vec<usize> = vec![2, 7, 8, 11, 23, 31, 32];
1438    let b_ones: Vec<usize> = vec![2, 3, 7, 19, 31, 32, 37, 41, 43, 47, 71, 73, 101];
1439    let a_and_b: Vec<usize> = vec![2, 7, 31, 32];
1440    let mut a = a_ones.iter().cloned().collect::<FixedBitSet>();
1441    let b = b_ones.iter().cloned().collect::<FixedBitSet>();
1442    a &= b;
1443    let res = a.ones().collect::<Vec<usize>>();
1444    assert!(res == a_and_b);
1445}
1446
1447#[test]
1448fn bitor_assign_shorter() {
1449    let a_ones: Vec<usize> = vec![2, 3, 7, 19, 31, 32, 37, 41, 43, 47, 71, 73, 101];
1450    let b_ones: Vec<usize> = vec![2, 7, 8, 11, 23, 31, 32];
1451    let a_or_b: Vec<usize> = vec![2, 3, 7, 8, 11, 19, 23, 31, 32, 37, 41, 43, 47, 71, 73, 101];
1452    let mut a = a_ones.iter().cloned().collect::<FixedBitSet>();
1453    let b = b_ones.iter().cloned().collect::<FixedBitSet>();
1454    a |= b;
1455    let res = a.ones().collect::<Vec<usize>>();
1456    assert!(res == a_or_b);
1457}
1458
1459#[test]
1460fn bitor_assign_longer() {
1461    let a_ones: Vec<usize> = vec![2, 7, 8, 11, 23, 31, 32];
1462    let b_ones: Vec<usize> = vec![2, 3, 7, 19, 31, 32, 37, 41, 43, 47, 71, 73, 101];
1463    let a_or_b: Vec<usize> = vec![2, 3, 7, 8, 11, 19, 23, 31, 32, 37, 41, 43, 47, 71, 73, 101];
1464    let mut a = a_ones.iter().cloned().collect::<FixedBitSet>();
1465    let b = b_ones.iter().cloned().collect::<FixedBitSet>();
1466    a |= b;
1467    let res = a.ones().collect::<Vec<usize>>();
1468    assert!(res == a_or_b);
1469}
1470
1471#[test]
1472fn bitxor_assign_shorter() {
1473    let a_ones: Vec<usize> = vec![2, 3, 7, 19, 31, 32, 37, 41, 43, 47, 71, 73, 101];
1474    let b_ones: Vec<usize> = vec![2, 7, 8, 11, 23, 31, 32];
1475    let a_xor_b: Vec<usize> = vec![3, 8, 11, 19, 23, 37, 41, 43, 47, 71, 73, 101];
1476    let mut a = a_ones.iter().cloned().collect::<FixedBitSet>();
1477    let b = b_ones.iter().cloned().collect::<FixedBitSet>();
1478    a ^= b;
1479    let res = a.ones().collect::<Vec<usize>>();
1480    assert!(res == a_xor_b);
1481}
1482
1483#[test]
1484fn bitxor_assign_longer() {
1485    let a_ones: Vec<usize> = vec![2, 7, 8, 11, 23, 31, 32];
1486    let b_ones: Vec<usize> = vec![2, 3, 7, 19, 31, 32, 37, 41, 43, 47, 71, 73, 101];
1487    let a_xor_b: Vec<usize> = vec![3, 8, 11, 19, 23, 37, 41, 43, 47, 71, 73, 101];
1488    let mut a = a_ones.iter().cloned().collect::<FixedBitSet>();
1489    let b = b_ones.iter().cloned().collect::<FixedBitSet>();
1490    a ^= b;
1491    let res = a.ones().collect::<Vec<usize>>();
1492    assert!(res == a_xor_b);
1493}
1494
1495#[test]
1496fn op_assign_ref() {
1497    let mut a = FixedBitSet::with_capacity(8);
1498    let b = FixedBitSet::with_capacity(8);
1499
1500    //check that all assign type operators work on references
1501    a &= &b;
1502    a |= &b;
1503    a ^= &b;
1504}
1505
1506#[test]
1507fn subset_superset_shorter() {
1508    let a_ones: Vec<usize> = vec![7, 31, 32, 63];
1509    let b_ones: Vec<usize> = vec![2, 7, 19, 31, 32, 37, 41, 43, 47, 63, 73, 101];
1510    let mut a = a_ones.iter().cloned().collect::<FixedBitSet>();
1511    let b = b_ones.iter().cloned().collect::<FixedBitSet>();
1512    assert!(a.is_subset(&b) && b.is_superset(&a));
1513    a.insert(14);
1514    assert!(!a.is_subset(&b) && !b.is_superset(&a));
1515}
1516
1517#[test]
1518fn subset_superset_longer() {
1519    let a_len = 153;
1520    let b_len = 75;
1521    let a_ones: Vec<usize> = vec![7, 31, 32, 63];
1522    let b_ones: Vec<usize> = vec![2, 7, 19, 31, 32, 37, 41, 43, 47, 63, 73];
1523    let mut a = FixedBitSet::with_capacity(a_len);
1524    let mut b = FixedBitSet::with_capacity(b_len);
1525    a.extend(a_ones.iter().cloned());
1526    b.extend(b_ones.iter().cloned());
1527    assert!(a.is_subset(&b) && b.is_superset(&a));
1528    a.insert(100);
1529    assert!(!a.is_subset(&b) && !b.is_superset(&a));
1530}
1531
1532#[test]
1533fn is_disjoint_first_shorter() {
1534    let a_len = 75;
1535    let b_len = 153;
1536    let a_ones: Vec<usize> = vec![2, 19, 32, 37, 41, 43, 47, 73];
1537    let b_ones: Vec<usize> = vec![7, 23, 31, 63, 124];
1538    let mut a = FixedBitSet::with_capacity(a_len);
1539    let mut b = FixedBitSet::with_capacity(b_len);
1540    a.extend(a_ones.iter().cloned());
1541    b.extend(b_ones.iter().cloned());
1542    assert!(a.is_disjoint(&b));
1543    a.insert(63);
1544    assert!(!a.is_disjoint(&b));
1545}
1546
1547#[test]
1548fn is_disjoint_first_longer() {
1549    let a_ones: Vec<usize> = vec![2, 19, 32, 37, 41, 43, 47, 73, 101];
1550    let b_ones: Vec<usize> = vec![7, 23, 31, 63];
1551    let a = a_ones.iter().cloned().collect::<FixedBitSet>();
1552    let mut b = b_ones.iter().cloned().collect::<FixedBitSet>();
1553    assert!(a.is_disjoint(&b));
1554    b.insert(2);
1555    assert!(!a.is_disjoint(&b));
1556}
1557
1558#[test]
1559fn extend_on_empty() {
1560    let items: Vec<usize> = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 27, 29, 31, 37, 167];
1561    let mut fbs = FixedBitSet::with_capacity(0);
1562    fbs.extend(items.iter().cloned());
1563    let ones = fbs.ones().collect::<Vec<usize>>();
1564    assert!(ones == items);
1565}
1566
1567#[test]
1568fn extend() {
1569    let items: Vec<usize> = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 27, 29, 31, 37, 167];
1570    let mut fbs = FixedBitSet::with_capacity(168);
1571    let new: Vec<usize> = vec![7, 37, 67, 137];
1572    for i in &new {
1573        fbs.put(*i);
1574    }
1575
1576    fbs.extend(items.iter().cloned());
1577
1578    let ones = fbs.ones().collect::<Vec<usize>>();
1579    let expected = {
1580        let mut tmp = items.clone();
1581        tmp.extend(new);
1582        tmp.sort();
1583        tmp.dedup();
1584        tmp
1585    };
1586
1587    assert!(ones == expected);
1588}
1589
1590#[test]
1591fn from_iterator() {
1592    let items: Vec<usize> = vec![0, 2, 4, 6, 8];
1593    let fb = items.iter().cloned().collect::<FixedBitSet>();
1594    for i in items {
1595        assert!(fb.contains(i));
1596    }
1597    for i in vec![1, 3, 5, 7] {
1598        assert!(!fb.contains(i));
1599    }
1600    assert_eq!(fb.len(), 9);
1601}
1602
1603#[test]
1604fn from_iterator_ones() {
1605    let len = 257;
1606    let mut fb = FixedBitSet::with_capacity(len);
1607    for i in (0..len).filter(|i| i % 7 == 0) {
1608        fb.put(i);
1609    }
1610    fb.put(len - 1);
1611    let dup = fb.ones().collect::<FixedBitSet>();
1612
1613    assert_eq!(fb.len(), dup.len());
1614    assert_eq!(
1615        fb.ones().collect::<Vec<usize>>(),
1616        dup.ones().collect::<Vec<usize>>()
1617    );
1618}
1619
1620#[cfg(feature = "std")]
1621#[test]
1622fn binary_trait() {
1623    let items: Vec<usize> = vec![1, 5, 7, 10, 14, 15];
1624    let fb = items.iter().cloned().collect::<FixedBitSet>();
1625
1626    assert_eq!(format!("{:b}", fb), "0100010100100011");
1627    assert_eq!(format!("{:#b}", fb), "0b0100010100100011");
1628}
1629
1630#[cfg(feature = "std")]
1631#[test]
1632fn display_trait() {
1633    let len = 8;
1634    let mut fb = FixedBitSet::with_capacity(len);
1635
1636    fb.put(4);
1637    fb.put(2);
1638
1639    assert_eq!(format!("{}", fb), "00101000");
1640    assert_eq!(format!("{:#}", fb), "0b00101000");
1641}
1642
1643#[test]
1644#[cfg(feature = "serde")]
1645fn test_serialize() {
1646    let mut fb = FixedBitSet::with_capacity(10);
1647    fb.put(2);
1648    fb.put(3);
1649    fb.put(6);
1650    fb.put(8);
1651    let serialized = serde_json::to_string(&fb).unwrap();
1652    assert_eq!(r#"{"data":[332],"length":10}"#, serialized);
1653}
1654
1655#[test]
1656fn test_is_clear() {
1657    let mut fb = FixedBitSet::with_capacity(0);
1658    assert!(fb.is_clear());
1659
1660    fb.grow(1);
1661    assert!(fb.is_clear());
1662
1663    fb.put(0);
1664    assert!(!fb.is_clear());
1665
1666    fb.grow(42);
1667    fb.clear();
1668    assert!(fb.is_clear());
1669
1670    fb.put(17);
1671    fb.put(19);
1672    assert!(!fb.is_clear());
1673}