]> git.lizzy.rs Git - bit-set.git/blob - src/lib.rs
548202ff4e760818be3d7da02ea9d61a71b87eba
[bit-set.git] / src / 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 //! An implementation of a set using a bit vector as an underlying
12 //! representation for holding unsigned numerical elements.
13 //!
14 //! It should also be noted that the amount of storage necessary for holding a
15 //! set of objects is proportional to the maximum of the objects when viewed
16 //! as a `usize`.
17 //!
18 //! # Examples
19 //!
20 //! ```
21 //! use bit_set::BitSet;
22 //!
23 //! // It's a regular set
24 //! let mut s = BitSet::new();
25 //! s.insert(0);
26 //! s.insert(3);
27 //! s.insert(7);
28 //!
29 //! s.remove(7);
30 //!
31 //! if !s.contains(7) {
32 //!     println!("There is no 7");
33 //! }
34 //!
35 //! // Can initialize from a `BitVec`
36 //! let other = BitSet::from_bytes(&[0b11010000]);
37 //!
38 //! s.union_with(&other);
39 //!
40 //! // Print 0, 1, 3 in some order
41 //! for x in s.iter() {
42 //!     println!("{}", x);
43 //! }
44 //!
45 //! // Can convert back to a `BitVec`
46 //! let bv = s.into_bit_vec();
47 //! assert!(bv[3]);
48 //! ```
49
50 #![cfg_attr(all(test, feature = "nightly"), feature(test))]
51 #[cfg(all(test, feature = "nightly"))] extern crate test;
52 #[cfg(all(test, feature = "nightly"))] extern crate rand;
53 extern crate bit_vec;
54
55 use bit_vec::{BitVec, Blocks, BitBlock};
56 use std::cmp::Ordering;
57 use std::cmp;
58 use std::fmt;
59 use std::hash;
60 use std::iter::{self, Chain, Enumerate, FromIterator, Repeat, Skip, Take};
61
62 type MatchWords<'a, B> = Chain<Enumerate<Blocks<'a, B>>, Skip<Take<Enumerate<Repeat<B>>>>>;
63
64 /// Computes how many blocks are needed to store that many bits
65 fn blocks_for_bits<B: BitBlock>(bits: usize) -> usize {
66     // If we want 17 bits, dividing by 32 will produce 0. So we add 1 to make sure we
67     // reserve enough. But if we want exactly a multiple of 32, this will actually allocate
68     // one too many. So we need to check if that's the case. We can do that by computing if
69     // bitwise AND by `32 - 1` is 0. But LLVM should be able to optimize the semantically
70     // superior modulo operator on a power of two to this.
71     //
72     // Note that we can technically avoid this branch with the expression
73     // `(nbits + BITS - 1) / 32::BITS`, but if nbits is almost usize::MAX this will overflow.
74     if bits % B::bits() == 0 {
75         bits / B::bits()
76     } else {
77         bits / B::bits() + 1
78     }
79 }
80
81 // Take two BitVec's, and return iterators of their words, where the shorter one
82 // has been padded with 0's
83 fn match_words<'a, 'b, B: BitBlock>(a: &'a BitVec<B>, b: &'b BitVec<B>)
84     -> (MatchWords<'a, B>, MatchWords<'b, B>)
85 {
86     let a_len = a.storage().len();
87     let b_len = b.storage().len();
88
89     // have to uselessly pretend to pad the longer one for type matching
90     if a_len < b_len {
91         (a.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(b_len).skip(a_len)),
92          b.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(0).skip(0)))
93     } else {
94         (a.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(0).skip(0)),
95          b.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(a_len).skip(b_len)))
96     }
97 }
98
99 pub struct BitSet<B = u32> {
100     bit_vec: BitVec<B>,
101 }
102
103 impl<B: BitBlock> Clone for BitSet<B> {
104     fn clone(&self) -> Self {
105         BitSet {
106             bit_vec: self.bit_vec.clone(),
107         }
108     }
109 }
110
111 impl<B: BitBlock> Default for BitSet<B> {
112     #[inline]
113     fn default() -> Self { BitSet { bit_vec: Default::default() } }
114 }
115
116 impl<B: BitBlock> FromIterator<usize> for BitSet<B> {
117     fn from_iter<I: IntoIterator<Item = usize>>(iter: I) -> Self {
118         let mut ret = Self::default();
119         ret.extend(iter);
120         ret
121     }
122 }
123
124 impl<B: BitBlock> Extend<usize> for BitSet<B> {
125     #[inline]
126     fn extend<I: IntoIterator<Item = usize>>(&mut self, iter: I) {
127         for i in iter {
128             self.insert(i);
129         }
130     }
131 }
132
133 impl<B: BitBlock> PartialOrd for BitSet<B> {
134     #[inline]
135     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
136         self.iter().partial_cmp(other)
137     }
138 }
139
140 impl<B: BitBlock> Ord for BitSet<B> {
141     #[inline]
142     fn cmp(&self, other: &Self) -> Ordering {
143         self.iter().cmp(other)
144     }
145 }
146
147 impl<B: BitBlock> PartialEq for BitSet<B> {
148     #[inline]
149     fn eq(&self, other: &Self) -> bool {
150         self.iter().eq(other)
151     }
152 }
153
154 impl<B: BitBlock> Eq for BitSet<B> {}
155
156 impl BitSet<u32> {
157     /// Creates a new empty `BitSet`.
158     ///
159     /// # Examples
160     ///
161     /// ```
162     /// use bit_set::BitSet;
163     ///
164     /// let mut s = BitSet::new();
165     /// ```
166     #[inline]
167     pub fn new() -> Self {
168         Self::default()
169     }
170
171     /// Creates a new `BitSet` with initially no contents, able to
172     /// hold `nbits` elements without resizing.
173     ///
174     /// # Examples
175     ///
176     /// ```
177     /// use bit_set::BitSet;
178     ///
179     /// let mut s = BitSet::with_capacity(100);
180     /// assert!(s.capacity() >= 100);
181     /// ```
182     #[inline]
183     pub fn with_capacity(nbits: usize) -> Self {
184         let bit_vec = BitVec::from_elem(nbits, false);
185         Self::from_bit_vec(bit_vec)
186     }
187
188     /// Creates a new `BitSet` from the given bit vector.
189     ///
190     /// # Examples
191     ///
192     /// ```
193     /// extern crate bit_vec;
194     /// extern crate bit_set;
195     ///
196     /// fn main() {
197     ///     use bit_vec::BitVec;
198     ///     use bit_set::BitSet;
199     ///
200     ///     let bv = BitVec::from_bytes(&[0b01100000]);
201     ///     let s = BitSet::from_bit_vec(bv);
202     ///
203     ///     // Print 1, 2 in arbitrary order
204     ///     for x in s.iter() {
205     ///         println!("{}", x);
206     ///     }
207     /// }
208     /// ```
209     #[inline]
210     pub fn from_bit_vec(bit_vec: BitVec) -> Self {
211         BitSet { bit_vec: bit_vec }
212     }
213
214     pub fn from_bytes(bytes: &[u8]) -> Self {
215         BitSet { bit_vec: BitVec::from_bytes(bytes) }
216     }
217 }
218
219 impl<B: BitBlock> BitSet<B> {
220
221     /// Returns the capacity in bits for this bit vector. Inserting any
222     /// element less than this amount will not trigger a resizing.
223     ///
224     /// # Examples
225     ///
226     /// ```
227     /// use bit_set::BitSet;
228     ///
229     /// let mut s = BitSet::with_capacity(100);
230     /// assert!(s.capacity() >= 100);
231     /// ```
232     #[inline]
233     pub fn capacity(&self) -> usize {
234         self.bit_vec.capacity()
235     }
236
237     /// Reserves capacity for the given `BitSet` to contain `len` distinct elements. In the case
238     /// of `BitSet` this means reallocations will not occur as long as all inserted elements
239     /// are less than `len`.
240     ///
241     /// The collection may reserve more space to avoid frequent reallocations.
242     ///
243     ///
244     /// # Examples
245     ///
246     /// ```
247     /// use bit_set::BitSet;
248     ///
249     /// let mut s = BitSet::new();
250     /// s.reserve_len(10);
251     /// assert!(s.capacity() >= 10);
252     /// ```
253     pub fn reserve_len(&mut self, len: usize) {
254         let cur_len = self.bit_vec.len();
255         if len >= cur_len {
256             self.bit_vec.reserve(len - cur_len);
257         }
258     }
259
260     /// Reserves the minimum capacity for the given `BitSet` to contain `len` distinct elements.
261     /// In the case of `BitSet` this means reallocations will not occur as long as all inserted
262     /// elements are less than `len`.
263     ///
264     /// Note that the allocator may give the collection more space than it requests. Therefore
265     /// capacity can not be relied upon to be precisely minimal. Prefer `reserve_len` if future
266     /// insertions are expected.
267     ///
268     ///
269     /// # Examples
270     ///
271     /// ```
272     /// use bit_set::BitSet;
273     ///
274     /// let mut s = BitSet::new();
275     /// s.reserve_len_exact(10);
276     /// assert!(s.capacity() >= 10);
277     /// ```
278     pub fn reserve_len_exact(&mut self, len: usize) {
279         let cur_len = self.bit_vec.len();
280         if len >= cur_len {
281             self.bit_vec.reserve_exact(len - cur_len);
282         }
283     }
284
285     /// Consumes this set to return the underlying bit vector.
286     ///
287     /// # Examples
288     ///
289     /// ```
290     /// use bit_set::BitSet;
291     ///
292     /// let mut s = BitSet::new();
293     /// s.insert(0);
294     /// s.insert(3);
295     ///
296     /// let bv = s.into_bit_vec();
297     /// assert!(bv[0]);
298     /// assert!(bv[3]);
299     /// ```
300     #[inline]
301     pub fn into_bit_vec(self) -> BitVec<B> {
302         self.bit_vec
303     }
304
305     /// Returns a reference to the underlying bit vector.
306     ///
307     /// # Examples
308     ///
309     /// ```
310     /// use bit_set::BitSet;
311     ///
312     /// let mut s = BitSet::new();
313     /// s.insert(0);
314     ///
315     /// let bv = s.get_ref();
316     /// assert_eq!(bv[0], true);
317     /// ```
318     #[inline]
319     pub fn get_ref(&self) -> &BitVec<B> {
320         &self.bit_vec
321     }
322
323     #[inline]
324     fn other_op<F>(&mut self, other: &Self, mut f: F) where F: FnMut(B, B) -> B {
325         // Unwrap BitVecs
326         let self_bit_vec = &mut self.bit_vec;
327         let other_bit_vec = &other.bit_vec;
328
329         let self_len = self_bit_vec.len();
330         let other_len = other_bit_vec.len();
331
332         // Expand the vector if necessary
333         if self_len < other_len {
334             self_bit_vec.grow(other_len - self_len, false);
335         }
336
337         // virtually pad other with 0's for equal lengths
338         let other_words = {
339             let (_, result) = match_words(self_bit_vec, other_bit_vec);
340             result
341         };
342
343         // Apply values found in other
344         for (i, w) in other_words {
345             let old = self_bit_vec.storage()[i];
346             let new = f(old, w);
347             unsafe {
348                 self_bit_vec.storage_mut()[i] = new;
349             }
350         }
351     }
352
353     /// Truncates the underlying vector to the least length required.
354     ///
355     /// # Examples
356     ///
357     /// ```
358     /// use bit_set::BitSet;
359     ///
360     /// let mut s = BitSet::new();
361     /// s.insert(32183231);
362     /// s.remove(32183231);
363     ///
364     /// // Internal storage will probably be bigger than necessary
365     /// println!("old capacity: {}", s.capacity());
366     ///
367     /// // Now should be smaller
368     /// s.shrink_to_fit();
369     /// println!("new capacity: {}", s.capacity());
370     /// ```
371     #[inline]
372     pub fn shrink_to_fit(&mut self) {
373         let bit_vec = &mut self.bit_vec;
374         // Obtain original length
375         let old_len = bit_vec.storage().len();
376         // Obtain coarse trailing zero length
377         let n = bit_vec.storage().iter().rev().take_while(|&&n| n == B::zero()).count();
378         // Truncate
379         let trunc_len = cmp::max(old_len - n, 1);
380         unsafe {
381             bit_vec.storage_mut().truncate(trunc_len);
382             bit_vec.set_len(trunc_len * B::bits());
383         }
384     }
385
386     /// Iterator over each usize stored in the `BitSet`.
387     ///
388     /// # Examples
389     ///
390     /// ```
391     /// use bit_set::BitSet;
392     ///
393     /// let s = BitSet::from_bytes(&[0b01001010]);
394     ///
395     /// // Print 1, 4, 6 in arbitrary order
396     /// for x in s.iter() {
397     ///     println!("{}", x);
398     /// }
399     /// ```
400     #[inline]
401     pub fn iter(&self) -> Iter<B> {
402         Iter(BlockIter::from_blocks(self.bit_vec.blocks()))
403     }
404
405     /// Iterator over each usize stored in `self` union `other`.
406     /// See [union_with](#method.union_with) for an efficient in-place version.
407     ///
408     /// # Examples
409     ///
410     /// ```
411     /// use bit_set::BitSet;
412     ///
413     /// let a = BitSet::from_bytes(&[0b01101000]);
414     /// let b = BitSet::from_bytes(&[0b10100000]);
415     ///
416     /// // Print 0, 1, 2, 4 in arbitrary order
417     /// for x in a.union(&b) {
418     ///     println!("{}", x);
419     /// }
420     /// ```
421     #[inline]
422     pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, B> {
423         fn or<B: BitBlock>(w1: B, w2: B) -> B { w1 | w2 }
424
425         Union(BlockIter::from_blocks(TwoBitPositions {
426             set: self.bit_vec.blocks(),
427             other: other.bit_vec.blocks(),
428             merge: or,
429         }))
430     }
431
432     /// Iterator over each usize stored in `self` intersect `other`.
433     /// See [intersect_with](#method.intersect_with) for an efficient in-place version.
434     ///
435     /// # Examples
436     ///
437     /// ```
438     /// use bit_set::BitSet;
439     ///
440     /// let a = BitSet::from_bytes(&[0b01101000]);
441     /// let b = BitSet::from_bytes(&[0b10100000]);
442     ///
443     /// // Print 2
444     /// for x in a.intersection(&b) {
445     ///     println!("{}", x);
446     /// }
447     /// ```
448     #[inline]
449     pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, B> {
450         fn bitand<B: BitBlock>(w1: B, w2: B) -> B { w1 & w2 }
451         let min = cmp::min(self.bit_vec.len(), other.bit_vec.len());
452
453         Intersection(BlockIter::from_blocks(TwoBitPositions {
454             set: self.bit_vec.blocks(),
455             other: other.bit_vec.blocks(),
456             merge: bitand,
457         }).take(min))
458     }
459
460     /// Iterator over each usize stored in the `self` setminus `other`.
461     /// See [difference_with](#method.difference_with) for an efficient in-place version.
462     ///
463     /// # Examples
464     ///
465     /// ```
466     /// use bit_set::BitSet;
467     ///
468     /// let a = BitSet::from_bytes(&[0b01101000]);
469     /// let b = BitSet::from_bytes(&[0b10100000]);
470     ///
471     /// // Print 1, 4 in arbitrary order
472     /// for x in a.difference(&b) {
473     ///     println!("{}", x);
474     /// }
475     ///
476     /// // Note that difference is not symmetric,
477     /// // and `b - a` means something else.
478     /// // This prints 0
479     /// for x in b.difference(&a) {
480     ///     println!("{}", x);
481     /// }
482     /// ```
483     #[inline]
484     pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, B> {
485         fn diff<B: BitBlock>(w1: B, w2: B) -> B { w1 & !w2 }
486
487         Difference(BlockIter::from_blocks(TwoBitPositions {
488             set: self.bit_vec.blocks(),
489             other: other.bit_vec.blocks(),
490             merge: diff,
491         }))
492     }
493
494     /// Iterator over each usize stored in the symmetric difference of `self` and `other`.
495     /// See [symmetric_difference_with](#method.symmetric_difference_with) for
496     /// an efficient in-place version.
497     ///
498     /// # Examples
499     ///
500     /// ```
501     /// use bit_set::BitSet;
502     ///
503     /// let a = BitSet::from_bytes(&[0b01101000]);
504     /// let b = BitSet::from_bytes(&[0b10100000]);
505     ///
506     /// // Print 0, 1, 4 in arbitrary order
507     /// for x in a.symmetric_difference(&b) {
508     ///     println!("{}", x);
509     /// }
510     /// ```
511     #[inline]
512     pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> SymmetricDifference<'a, B> {
513         fn bitxor<B: BitBlock>(w1: B, w2: B) -> B { w1 ^ w2 }
514
515         SymmetricDifference(BlockIter::from_blocks(TwoBitPositions {
516             set: self.bit_vec.blocks(),
517             other: other.bit_vec.blocks(),
518             merge: bitxor,
519         }))
520     }
521
522     /// Unions in-place with the specified other bit vector.
523     ///
524     /// # Examples
525     ///
526     /// ```
527     /// use bit_set::BitSet;
528     ///
529     /// let a   = 0b01101000;
530     /// let b   = 0b10100000;
531     /// let res = 0b11101000;
532     ///
533     /// let mut a = BitSet::from_bytes(&[a]);
534     /// let b = BitSet::from_bytes(&[b]);
535     /// let res = BitSet::from_bytes(&[res]);
536     ///
537     /// a.union_with(&b);
538     /// assert_eq!(a, res);
539     /// ```
540     #[inline]
541     pub fn union_with(&mut self, other: &Self) {
542         self.other_op(other, |w1, w2| w1 | w2);
543     }
544
545     /// Intersects in-place with the specified other bit vector.
546     ///
547     /// # Examples
548     ///
549     /// ```
550     /// use bit_set::BitSet;
551     ///
552     /// let a   = 0b01101000;
553     /// let b   = 0b10100000;
554     /// let res = 0b00100000;
555     ///
556     /// let mut a = BitSet::from_bytes(&[a]);
557     /// let b = BitSet::from_bytes(&[b]);
558     /// let res = BitSet::from_bytes(&[res]);
559     ///
560     /// a.intersect_with(&b);
561     /// assert_eq!(a, res);
562     /// ```
563     #[inline]
564     pub fn intersect_with(&mut self, other: &Self) {
565         self.other_op(other, |w1, w2| w1 & w2);
566     }
567
568     /// Makes this bit vector the difference with the specified other bit vector
569     /// in-place.
570     ///
571     /// # Examples
572     ///
573     /// ```
574     /// use bit_set::BitSet;
575     ///
576     /// let a   = 0b01101000;
577     /// let b   = 0b10100000;
578     /// let a_b = 0b01001000; // a - b
579     /// let b_a = 0b10000000; // b - a
580     ///
581     /// let mut bva = BitSet::from_bytes(&[a]);
582     /// let bvb = BitSet::from_bytes(&[b]);
583     /// let bva_b = BitSet::from_bytes(&[a_b]);
584     /// let bvb_a = BitSet::from_bytes(&[b_a]);
585     ///
586     /// bva.difference_with(&bvb);
587     /// assert_eq!(bva, bva_b);
588     ///
589     /// let bva = BitSet::from_bytes(&[a]);
590     /// let mut bvb = BitSet::from_bytes(&[b]);
591     ///
592     /// bvb.difference_with(&bva);
593     /// assert_eq!(bvb, bvb_a);
594     /// ```
595     #[inline]
596     pub fn difference_with(&mut self, other: &Self) {
597         self.other_op(other, |w1, w2| w1 & !w2);
598     }
599
600     /// Makes this bit vector the symmetric difference with the specified other
601     /// bit vector in-place.
602     ///
603     /// # Examples
604     ///
605     /// ```
606     /// use bit_set::BitSet;
607     ///
608     /// let a   = 0b01101000;
609     /// let b   = 0b10100000;
610     /// let res = 0b11001000;
611     ///
612     /// let mut a = BitSet::from_bytes(&[a]);
613     /// let b = BitSet::from_bytes(&[b]);
614     /// let res = BitSet::from_bytes(&[res]);
615     ///
616     /// a.symmetric_difference_with(&b);
617     /// assert_eq!(a, res);
618     /// ```
619     #[inline]
620     pub fn symmetric_difference_with(&mut self, other: &Self) {
621         self.other_op(other, |w1, w2| w1 ^ w2);
622     }
623
624 /*
625     /// Moves all elements from `other` into `Self`, leaving `other` empty.
626     ///
627     /// # Examples
628     ///
629     /// ```
630     /// use bit_set::BitSet;
631     ///
632     /// let mut a = BitSet::new();
633     /// a.insert(2);
634     /// a.insert(6);
635     ///
636     /// let mut b = BitSet::new();
637     /// b.insert(1);
638     /// b.insert(3);
639     /// b.insert(6);
640     ///
641     /// a.append(&mut b);
642     ///
643     /// assert_eq!(a.len(), 4);
644     /// assert_eq!(b.len(), 0);
645     /// assert_eq!(a, BitSet::from_bytes(&[0b01110010]));
646     /// ```
647     pub fn append(&mut self, other: &mut Self) {
648         self.union_with(other);
649         other.clear();
650     }
651
652     /// Splits the `BitSet` into two at the given key including the key.
653     /// Retains the first part in-place while returning the second part.
654     ///
655     /// # Examples
656     ///
657     /// ```
658     /// use bit_set::BitSet;
659     ///
660     /// let mut a = BitSet::new();
661     /// a.insert(2);
662     /// a.insert(6);
663     /// a.insert(1);
664     /// a.insert(3);
665     ///
666     /// let b = a.split_off(3);
667     ///
668     /// assert_eq!(a.len(), 2);
669     /// assert_eq!(b.len(), 2);
670     /// assert_eq!(a, BitSet::from_bytes(&[0b01100000]));
671     /// assert_eq!(b, BitSet::from_bytes(&[0b00010010]));
672     /// ```
673     pub fn split_off(&mut self, at: usize) -> Self {
674         let mut other = BitSet::new();
675
676         if at == 0 {
677             swap(self, &mut other);
678             return other;
679         } else if at >= self.bit_vec.len() {
680             return other;
681         }
682
683         // Calculate block and bit at which to split
684         let w = at / BITS;
685         let b = at % BITS;
686
687         // Pad `other` with `w` zero blocks,
688         // append `self`'s blocks in the range from `w` to the end to `other`
689         other.bit_vec.storage_mut().extend(repeat(0u32).take(w)
690                                      .chain(self.bit_vec.storage()[w..].iter().cloned()));
691         other.bit_vec.nbits = self.bit_vec.nbits;
692
693         if b > 0 {
694             other.bit_vec.storage_mut()[w] &= !0 << b;
695         }
696
697         // Sets `bit_vec.len()` and fixes the last block as well
698         self.bit_vec.truncate(at);
699
700         other
701     }
702 */
703
704     /// Returns the number of set bits in this set.
705     #[inline]
706     pub fn len(&self) -> usize  {
707         self.bit_vec.blocks().fold(0, |acc, n| acc + n.count_ones() as usize)
708     }
709
710     /// Returns whether there are no bits set in this set
711     #[inline]
712     pub fn is_empty(&self) -> bool {
713         self.bit_vec.none()
714     }
715
716     /// Clears all bits in this set
717     #[inline]
718     pub fn clear(&mut self) {
719         self.bit_vec.clear();
720     }
721
722     /// Returns `true` if this set contains the specified integer.
723     #[inline]
724     pub fn contains(&self, value: usize) -> bool {
725         let bit_vec = &self.bit_vec;
726         value < bit_vec.len() && bit_vec[value]
727     }
728
729     /// Returns `true` if the set has no elements in common with `other`.
730     /// This is equivalent to checking for an empty intersection.
731     #[inline]
732     pub fn is_disjoint(&self, other: &Self) -> bool {
733         self.intersection(other).next().is_none()
734     }
735
736     /// Returns `true` if the set is a subset of another.
737     #[inline]
738     pub fn is_subset(&self, other: &Self) -> bool {
739         let self_bit_vec = &self.bit_vec;
740         let other_bit_vec = &other.bit_vec;
741         let other_blocks = blocks_for_bits::<B>(other_bit_vec.len());
742
743         // Check that `self` intersect `other` is self
744         self_bit_vec.blocks().zip(other_bit_vec.blocks()).all(|(w1, w2)| w1 & w2 == w1) &&
745         // Make sure if `self` has any more blocks than `other`, they're all 0
746         self_bit_vec.blocks().skip(other_blocks).all(|w| w == B::zero())
747     }
748
749     /// Returns `true` if the set is a superset of another.
750     #[inline]
751     pub fn is_superset(&self, other: &Self) -> bool {
752         other.is_subset(self)
753     }
754
755     /// Adds a value to the set. Returns `true` if the value was not already
756     /// present in the set.
757     pub fn insert(&mut self, value: usize) -> bool {
758         if self.contains(value) {
759             return false;
760         }
761
762         // Ensure we have enough space to hold the new element
763         let len = self.bit_vec.len();
764         if value >= len {
765             self.bit_vec.grow(value - len + 1, false)
766         }
767
768         self.bit_vec.set(value, true);
769         return true;
770     }
771
772     /// Removes a value from the set. Returns `true` if the value was
773     /// present in the set.
774     pub fn remove(&mut self, value: usize) -> bool {
775         if !self.contains(value) {
776             return false;
777         }
778
779         self.bit_vec.set(value, false);
780
781         return true;
782     }
783 }
784
785 impl<B: BitBlock> fmt::Debug for BitSet<B> {
786     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
787         fmt.debug_set().entries(self).finish()
788     }
789 }
790
791 impl<B: BitBlock> hash::Hash for BitSet<B> {
792     fn hash<H: hash::Hasher>(&self, state: &mut H) {
793         for pos in self {
794             pos.hash(state);
795         }
796     }
797 }
798
799 #[derive(Clone)]
800 struct BlockIter<T, B> {
801     head: B,
802     head_offset: usize,
803     tail: T,
804 }
805
806 impl<T, B: BitBlock> BlockIter<T, B> where T: Iterator<Item=B> {
807     fn from_blocks(mut blocks: T) -> BlockIter<T, B> {
808         let h = blocks.next().unwrap_or(B::zero());
809         BlockIter {tail: blocks, head: h, head_offset: 0}
810     }
811 }
812
813 /// An iterator combining two `BitSet` iterators.
814 #[derive(Clone)]
815 struct TwoBitPositions<'a, B: 'a> {
816     set: Blocks<'a, B>,
817     other: Blocks<'a, B>,
818     merge: fn(B, B) -> B,
819 }
820
821 /// An iterator for `BitSet`.
822 #[derive(Clone)]
823 pub struct Iter<'a, B: 'a>(BlockIter<Blocks<'a, B>, B>);
824 #[derive(Clone)]
825 pub struct Union<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
826 #[derive(Clone)]
827 pub struct Intersection<'a, B: 'a>(Take<BlockIter<TwoBitPositions<'a, B>, B>>);
828 #[derive(Clone)]
829 pub struct Difference<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
830 #[derive(Clone)]
831 pub struct SymmetricDifference<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
832
833 impl<'a, T, B: BitBlock> Iterator for BlockIter<T, B> where T: Iterator<Item=B> {
834     type Item = usize;
835
836     fn next(&mut self) -> Option<usize> {
837         while self.head == B::zero() {
838             match self.tail.next() {
839                 Some(w) => self.head = w,
840                 None => return None
841             }
842             self.head_offset += B::bits();
843         }
844
845         // from the current block, isolate the
846         // LSB and subtract 1, producing k:
847         // a block with a number of set bits
848         // equal to the index of the LSB
849         let k = (self.head & (!self.head + B::one())) - B::one();
850         // update block, removing the LSB
851         self.head = self.head & (self.head - B::one());
852         // return offset + (index of LSB)
853         Some(self.head_offset + (B::count_ones(k) as usize))
854     }
855
856     #[inline]
857     fn size_hint(&self) -> (usize, Option<usize>) {
858         match self.tail.size_hint() {
859             (_, Some(h)) => (0, Some(1 + h * B::bits())),
860             _ => (0, None)
861         }
862     }
863 }
864
865 impl<'a, B: BitBlock> Iterator for TwoBitPositions<'a, B> {
866     type Item = B;
867
868     fn next(&mut self) -> Option<B> {
869         match (self.set.next(), self.other.next()) {
870             (Some(a), Some(b)) => Some((self.merge)(a, b)),
871             (Some(a), None) => Some((self.merge)(a, B::zero())),
872             (None, Some(b)) => Some((self.merge)(B::zero(), b)),
873             _ => return None
874         }
875     }
876
877     #[inline]
878     fn size_hint(&self) -> (usize, Option<usize>) {
879         let (a, au) = self.set.size_hint();
880         let (b, bu) = self.other.size_hint();
881
882         let upper = match (au, bu) {
883             (Some(au), Some(bu)) => Some(cmp::max(au, bu)),
884             _ => None
885         };
886
887         (cmp::max(a, b), upper)
888     }
889 }
890
891 impl<'a, B: BitBlock> Iterator for Iter<'a, B> {
892     type Item = usize;
893
894     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
895     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
896 }
897
898 impl<'a, B: BitBlock> Iterator for Union<'a, B> {
899     type Item = usize;
900
901     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
902     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
903 }
904
905 impl<'a, B: BitBlock> Iterator for Intersection<'a, B> {
906     type Item = usize;
907
908     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
909     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
910 }
911
912 impl<'a, B: BitBlock> Iterator for Difference<'a, B> {
913     type Item = usize;
914
915     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
916     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
917 }
918
919 impl<'a, B: BitBlock> Iterator for SymmetricDifference<'a, B> {
920     type Item = usize;
921
922     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
923     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
924 }
925
926 impl<'a, B: BitBlock> IntoIterator for &'a BitSet<B> {
927     type Item = usize;
928     type IntoIter = Iter<'a, B>;
929
930     fn into_iter(self) -> Iter<'a, B> {
931         self.iter()
932     }
933 }
934
935 #[cfg(test)]
936 mod tests {
937     use std::cmp::Ordering::{Equal, Greater, Less};
938     use super::BitSet;
939     use bit_vec::BitVec;
940
941     #[test]
942     fn test_bit_set_show() {
943         let mut s = BitSet::new();
944         s.insert(1);
945         s.insert(10);
946         s.insert(50);
947         s.insert(2);
948         assert_eq!("{1, 2, 10, 50}", format!("{:?}", s));
949     }
950
951     #[test]
952     fn test_bit_set_from_usizes() {
953         let usizes = vec![0, 2, 2, 3];
954         let a: BitSet = usizes.into_iter().collect();
955         let mut b = BitSet::new();
956         b.insert(0);
957         b.insert(2);
958         b.insert(3);
959         assert_eq!(a, b);
960     }
961
962     #[test]
963     fn test_bit_set_iterator() {
964         let usizes = vec![0, 2, 2, 3];
965         let bit_vec: BitSet = usizes.into_iter().collect();
966
967         let idxs: Vec<_> = bit_vec.iter().collect();
968         assert_eq!(idxs, [0, 2, 3]);
969
970         let long: BitSet = (0..10000).filter(|&n| n % 2 == 0).collect();
971         let real: Vec<_> = (0..10000/2).map(|x| x*2).collect();
972
973         let idxs: Vec<_> = long.iter().collect();
974         assert_eq!(idxs, real);
975     }
976
977     #[test]
978     fn test_bit_set_frombit_vec_init() {
979         let bools = [true, false];
980         let lengths = [10, 64, 100];
981         for &b in &bools {
982             for &l in &lengths {
983                 let bitset = BitSet::from_bit_vec(BitVec::from_elem(l, b));
984                 assert_eq!(bitset.contains(1), b);
985                 assert_eq!(bitset.contains((l-1)), b);
986                 assert!(!bitset.contains(l));
987             }
988         }
989     }
990
991     #[test]
992     fn test_bit_vec_masking() {
993         let b = BitVec::from_elem(140, true);
994         let mut bs = BitSet::from_bit_vec(b);
995         assert!(bs.contains(139));
996         assert!(!bs.contains(140));
997         assert!(bs.insert(150));
998         assert!(!bs.contains(140));
999         assert!(!bs.contains(149));
1000         assert!(bs.contains(150));
1001         assert!(!bs.contains(151));
1002     }
1003
1004     #[test]
1005     fn test_bit_set_basic() {
1006         let mut b = BitSet::new();
1007         assert!(b.insert(3));
1008         assert!(!b.insert(3));
1009         assert!(b.contains(3));
1010         assert!(b.insert(4));
1011         assert!(!b.insert(4));
1012         assert!(b.contains(3));
1013         assert!(b.insert(400));
1014         assert!(!b.insert(400));
1015         assert!(b.contains(400));
1016         assert_eq!(b.len(), 3);
1017     }
1018
1019     #[test]
1020     fn test_bit_set_intersection() {
1021         let mut a = BitSet::new();
1022         let mut b = BitSet::new();
1023
1024         assert!(a.insert(11));
1025         assert!(a.insert(1));
1026         assert!(a.insert(3));
1027         assert!(a.insert(77));
1028         assert!(a.insert(103));
1029         assert!(a.insert(5));
1030
1031         assert!(b.insert(2));
1032         assert!(b.insert(11));
1033         assert!(b.insert(77));
1034         assert!(b.insert(5));
1035         assert!(b.insert(3));
1036
1037         let expected = [3, 5, 11, 77];
1038         let actual: Vec<_> = a.intersection(&b).collect();
1039         assert_eq!(actual, expected);
1040     }
1041
1042     #[test]
1043     fn test_bit_set_difference() {
1044         let mut a = BitSet::new();
1045         let mut b = BitSet::new();
1046
1047         assert!(a.insert(1));
1048         assert!(a.insert(3));
1049         assert!(a.insert(5));
1050         assert!(a.insert(200));
1051         assert!(a.insert(500));
1052
1053         assert!(b.insert(3));
1054         assert!(b.insert(200));
1055
1056         let expected = [1, 5, 500];
1057         let actual: Vec<_> = a.difference(&b).collect();
1058         assert_eq!(actual, expected);
1059     }
1060
1061     #[test]
1062     fn test_bit_set_symmetric_difference() {
1063         let mut a = BitSet::new();
1064         let mut b = BitSet::new();
1065
1066         assert!(a.insert(1));
1067         assert!(a.insert(3));
1068         assert!(a.insert(5));
1069         assert!(a.insert(9));
1070         assert!(a.insert(11));
1071
1072         assert!(b.insert(3));
1073         assert!(b.insert(9));
1074         assert!(b.insert(14));
1075         assert!(b.insert(220));
1076
1077         let expected = [1, 5, 11, 14, 220];
1078         let actual: Vec<_> = a.symmetric_difference(&b).collect();
1079         assert_eq!(actual, expected);
1080     }
1081
1082     #[test]
1083     fn test_bit_set_union() {
1084         let mut a = BitSet::new();
1085         let mut b = BitSet::new();
1086         assert!(a.insert(1));
1087         assert!(a.insert(3));
1088         assert!(a.insert(5));
1089         assert!(a.insert(9));
1090         assert!(a.insert(11));
1091         assert!(a.insert(160));
1092         assert!(a.insert(19));
1093         assert!(a.insert(24));
1094         assert!(a.insert(200));
1095
1096         assert!(b.insert(1));
1097         assert!(b.insert(5));
1098         assert!(b.insert(9));
1099         assert!(b.insert(13));
1100         assert!(b.insert(19));
1101
1102         let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160, 200];
1103         let actual: Vec<_> = a.union(&b).collect();
1104         assert_eq!(actual, expected);
1105     }
1106
1107     #[test]
1108     fn test_bit_set_subset() {
1109         let mut set1 = BitSet::new();
1110         let mut set2 = BitSet::new();
1111
1112         assert!(set1.is_subset(&set2)); //  {}  {}
1113         set2.insert(100);
1114         assert!(set1.is_subset(&set2)); //  {}  { 1 }
1115         set2.insert(200);
1116         assert!(set1.is_subset(&set2)); //  {}  { 1, 2 }
1117         set1.insert(200);
1118         assert!(set1.is_subset(&set2)); //  { 2 }  { 1, 2 }
1119         set1.insert(300);
1120         assert!(!set1.is_subset(&set2)); // { 2, 3 }  { 1, 2 }
1121         set2.insert(300);
1122         assert!(set1.is_subset(&set2)); // { 2, 3 }  { 1, 2, 3 }
1123         set2.insert(400);
1124         assert!(set1.is_subset(&set2)); // { 2, 3 }  { 1, 2, 3, 4 }
1125         set2.remove(100);
1126         assert!(set1.is_subset(&set2)); // { 2, 3 }  { 2, 3, 4 }
1127         set2.remove(300);
1128         assert!(!set1.is_subset(&set2)); // { 2, 3 }  { 2, 4 }
1129         set1.remove(300);
1130         assert!(set1.is_subset(&set2)); // { 2 }  { 2, 4 }
1131     }
1132
1133     #[test]
1134     fn test_bit_set_is_disjoint() {
1135         let a = BitSet::from_bytes(&[0b10100010]);
1136         let b = BitSet::from_bytes(&[0b01000000]);
1137         let c = BitSet::new();
1138         let d = BitSet::from_bytes(&[0b00110000]);
1139
1140         assert!(!a.is_disjoint(&d));
1141         assert!(!d.is_disjoint(&a));
1142
1143         assert!(a.is_disjoint(&b));
1144         assert!(a.is_disjoint(&c));
1145         assert!(b.is_disjoint(&a));
1146         assert!(b.is_disjoint(&c));
1147         assert!(c.is_disjoint(&a));
1148         assert!(c.is_disjoint(&b));
1149     }
1150
1151     #[test]
1152     fn test_bit_set_union_with() {
1153         //a should grow to include larger elements
1154         let mut a = BitSet::new();
1155         a.insert(0);
1156         let mut b = BitSet::new();
1157         b.insert(5);
1158         let expected = BitSet::from_bytes(&[0b10000100]);
1159         a.union_with(&b);
1160         assert_eq!(a, expected);
1161
1162         // Standard
1163         let mut a = BitSet::from_bytes(&[0b10100010]);
1164         let mut b = BitSet::from_bytes(&[0b01100010]);
1165         let c = a.clone();
1166         a.union_with(&b);
1167         b.union_with(&c);
1168         assert_eq!(a.len(), 4);
1169         assert_eq!(b.len(), 4);
1170     }
1171
1172     #[test]
1173     fn test_bit_set_intersect_with() {
1174         // Explicitly 0'ed bits
1175         let mut a = BitSet::from_bytes(&[0b10100010]);
1176         let mut b = BitSet::from_bytes(&[0b00000000]);
1177         let c = a.clone();
1178         a.intersect_with(&b);
1179         b.intersect_with(&c);
1180         assert!(a.is_empty());
1181         assert!(b.is_empty());
1182
1183         // Uninitialized bits should behave like 0's
1184         let mut a = BitSet::from_bytes(&[0b10100010]);
1185         let mut b = BitSet::new();
1186         let c = a.clone();
1187         a.intersect_with(&b);
1188         b.intersect_with(&c);
1189         assert!(a.is_empty());
1190         assert!(b.is_empty());
1191
1192         // Standard
1193         let mut a = BitSet::from_bytes(&[0b10100010]);
1194         let mut b = BitSet::from_bytes(&[0b01100010]);
1195         let c = a.clone();
1196         a.intersect_with(&b);
1197         b.intersect_with(&c);
1198         assert_eq!(a.len(), 2);
1199         assert_eq!(b.len(), 2);
1200     }
1201
1202     #[test]
1203     fn test_bit_set_difference_with() {
1204         // Explicitly 0'ed bits
1205         let mut a = BitSet::from_bytes(&[0b00000000]);
1206         let b = BitSet::from_bytes(&[0b10100010]);
1207         a.difference_with(&b);
1208         assert!(a.is_empty());
1209
1210         // Uninitialized bits should behave like 0's
1211         let mut a = BitSet::new();
1212         let b = BitSet::from_bytes(&[0b11111111]);
1213         a.difference_with(&b);
1214         assert!(a.is_empty());
1215
1216         // Standard
1217         let mut a = BitSet::from_bytes(&[0b10100010]);
1218         let mut b = BitSet::from_bytes(&[0b01100010]);
1219         let c = a.clone();
1220         a.difference_with(&b);
1221         b.difference_with(&c);
1222         assert_eq!(a.len(), 1);
1223         assert_eq!(b.len(), 1);
1224     }
1225
1226     #[test]
1227     fn test_bit_set_symmetric_difference_with() {
1228         //a should grow to include larger elements
1229         let mut a = BitSet::new();
1230         a.insert(0);
1231         a.insert(1);
1232         let mut b = BitSet::new();
1233         b.insert(1);
1234         b.insert(5);
1235         let expected = BitSet::from_bytes(&[0b10000100]);
1236         a.symmetric_difference_with(&b);
1237         assert_eq!(a, expected);
1238
1239         let mut a = BitSet::from_bytes(&[0b10100010]);
1240         let b = BitSet::new();
1241         let c = a.clone();
1242         a.symmetric_difference_with(&b);
1243         assert_eq!(a, c);
1244
1245         // Standard
1246         let mut a = BitSet::from_bytes(&[0b11100010]);
1247         let mut b = BitSet::from_bytes(&[0b01101010]);
1248         let c = a.clone();
1249         a.symmetric_difference_with(&b);
1250         b.symmetric_difference_with(&c);
1251         assert_eq!(a.len(), 2);
1252         assert_eq!(b.len(), 2);
1253     }
1254
1255     #[test]
1256     fn test_bit_set_eq() {
1257         let a = BitSet::from_bytes(&[0b10100010]);
1258         let b = BitSet::from_bytes(&[0b00000000]);
1259         let c = BitSet::new();
1260
1261         assert!(a == a);
1262         assert!(a != b);
1263         assert!(a != c);
1264         assert!(b == b);
1265         assert!(b == c);
1266         assert!(c == c);
1267     }
1268
1269     #[test]
1270     fn test_bit_set_cmp() {
1271         let a = BitSet::from_bytes(&[0b10100010]);
1272         let b = BitSet::from_bytes(&[0b00000000]);
1273         let c = BitSet::new();
1274
1275         assert_eq!(a.cmp(&b), Greater);
1276         assert_eq!(a.cmp(&c), Greater);
1277         assert_eq!(b.cmp(&a), Less);
1278         assert_eq!(b.cmp(&c), Equal);
1279         assert_eq!(c.cmp(&a), Less);
1280         assert_eq!(c.cmp(&b), Equal);
1281     }
1282
1283     #[test]
1284     fn test_bit_vec_remove() {
1285         let mut a = BitSet::new();
1286
1287         assert!(a.insert(1));
1288         assert!(a.remove(1));
1289
1290         assert!(a.insert(100));
1291         assert!(a.remove(100));
1292
1293         assert!(a.insert(1000));
1294         assert!(a.remove(1000));
1295         a.shrink_to_fit();
1296     }
1297
1298     #[test]
1299     fn test_bit_vec_clone() {
1300         let mut a = BitSet::new();
1301
1302         assert!(a.insert(1));
1303         assert!(a.insert(100));
1304         assert!(a.insert(1000));
1305
1306         let mut b = a.clone();
1307
1308         assert!(a == b);
1309
1310         assert!(b.remove(1));
1311         assert!(a.contains(1));
1312
1313         assert!(a.remove(1000));
1314         assert!(b.contains(1000));
1315     }
1316
1317 /*
1318     #[test]
1319     fn test_bit_set_append() {
1320         let mut a = BitSet::new();
1321         a.insert(2);
1322         a.insert(6);
1323
1324         let mut b = BitSet::new();
1325         b.insert(1);
1326         b.insert(3);
1327         b.insert(6);
1328
1329         a.append(&mut b);
1330
1331         assert_eq!(a.len(), 4);
1332         assert_eq!(b.len(), 0);
1333         assert!(b.capacity() >= 6);
1334
1335         assert_eq!(a, BitSet::from_bytes(&[0b01110010]));
1336     }
1337
1338     #[test]
1339     fn test_bit_set_split_off() {
1340         // Split at 0
1341         let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1342                                          0b00110011, 0b01101011, 0b10101101]);
1343
1344         let b = a.split_off(0);
1345
1346         assert_eq!(a.len(), 0);
1347         assert_eq!(b.len(), 21);
1348
1349         assert_eq!(b, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1350                                            0b00110011, 0b01101011, 0b10101101]);
1351
1352         // Split behind last element
1353         let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1354                                          0b00110011, 0b01101011, 0b10101101]);
1355
1356         let b = a.split_off(50);
1357
1358         assert_eq!(a.len(), 21);
1359         assert_eq!(b.len(), 0);
1360
1361         assert_eq!(a, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1362                                            0b00110011, 0b01101011, 0b10101101]));
1363
1364         // Split at arbitrary element
1365         let mut a = BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1366                                          0b00110011, 0b01101011, 0b10101101]);
1367
1368         let b = a.split_off(34);
1369
1370         assert_eq!(a.len(), 12);
1371         assert_eq!(b.len(), 9);
1372
1373         assert_eq!(a, BitSet::from_bytes(&[0b10100000, 0b00010010, 0b10010010,
1374                                            0b00110011, 0b01000000]));
1375         assert_eq!(b, BitSet::from_bytes(&[0, 0, 0, 0,
1376                                            0b00101011, 0b10101101]));
1377     }
1378 */
1379 }
1380
1381 #[cfg(all(test, feature = "nightly"))]
1382 mod bench {
1383     use super::BitSet;
1384     use bit_vec::BitVec;
1385     use rand::{Rng, thread_rng, ThreadRng};
1386
1387     use test::{Bencher, black_box};
1388
1389     const BENCH_BITS: usize = 1 << 14;
1390     const BITS: usize = 32;
1391
1392     fn rng() -> ThreadRng {
1393         thread_rng()
1394     }
1395
1396     #[bench]
1397     fn bench_bit_vecset_small(b: &mut Bencher) {
1398         let mut r = rng();
1399         let mut bit_vec = BitSet::new();
1400         b.iter(|| {
1401             for _ in 0..100 {
1402                 bit_vec.insert((r.next_u32() as usize) % BITS);
1403             }
1404             black_box(&bit_vec);
1405         });
1406     }
1407
1408     #[bench]
1409     fn bench_bit_vecset_big(b: &mut Bencher) {
1410         let mut r = rng();
1411         let mut bit_vec = BitSet::new();
1412         b.iter(|| {
1413             for _ in 0..100 {
1414                 bit_vec.insert((r.next_u32() as usize) % BENCH_BITS);
1415             }
1416             black_box(&bit_vec);
1417         });
1418     }
1419
1420     #[bench]
1421     fn bench_bit_vecset_iter(b: &mut Bencher) {
1422         let bit_vec = BitSet::from_bit_vec(BitVec::from_fn(BENCH_BITS,
1423                                               |idx| {idx % 3 == 0}));
1424         b.iter(|| {
1425             let mut sum = 0;
1426             for idx in &bit_vec {
1427                 sum += idx as usize;
1428             }
1429             sum
1430         })
1431     }
1432 }