]> git.lizzy.rs Git - bit-set.git/blob - src/lib.rs
2c44073764b01079e252caf260a9e290a545dbd2
[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 #![feature(core)]
12
13 /// An implementation of a set using a bit vector as an underlying
14 /// representation for holding unsigned numerical elements.
15 ///
16 /// It should also be noted that the amount of storage necessary for holding a
17 /// set of objects is proportional to the maximum of the objects when viewed
18 /// as a `usize`.
19 ///
20 /// # Examples
21 ///
22 /// ```
23 /// # #![feature(collections)]
24 /// use std::collections::{BitSet, BitVec};
25 ///
26 /// // It's a regular set
27 /// let mut s = BitSet::new();
28 /// s.insert(0);
29 /// s.insert(3);
30 /// s.insert(7);
31 ///
32 /// s.remove(&7);
33 ///
34 /// if !s.contains(&7) {
35 ///     println!("There is no 7");
36 /// }
37 ///
38 /// // Can initialize from a `BitVec`
39 /// let other = BitSet::from_bit_vec(BitVec::from_bytes(&[0b11010000]));
40 ///
41 /// s.union_with(&other);
42 ///
43 /// // Print 0, 1, 3 in some order
44 /// for x in s.iter() {
45 ///     println!("{}", x);
46 /// }
47 ///
48 /// // Can convert back to a `BitVec`
49 /// let bv: BitVec = s.into_bit_vec();
50 /// assert!(bv[3]);
51 /// ```
52
53
54
55 extern crate bit_vec;
56
57 use bit_vec::{BitVec, Blocks, BitBlock};
58 use std::cmp::Ordering;
59 use std::cmp;
60 use std::fmt;
61 use std::hash;
62 use std::iter::{Chain, Enumerate, Repeat, Skip, Take, repeat};
63 use std::iter::{self, FromIterator};
64
65 type MatchWords<'a, B> = Chain<Enumerate<Blocks<'a, B>>, Skip<Take<Enumerate<Repeat<B>>>>>;
66
67 /// Computes how many blocks are needed to store that many bits
68 fn blocks_for_bits<B: BitBlock>(bits: usize) -> usize {
69     // If we want 17 bits, dividing by 32 will produce 0. So we add 1 to make sure we
70     // reserve enough. But if we want exactly a multiple of 32, this will actually allocate
71     // one too many. So we need to check if that's the case. We can do that by computing if
72     // bitwise AND by `32 - 1` is 0. But LLVM should be able to optimize the semantically
73     // superior modulo operator on a power of two to this.
74     //
75     // Note that we can technically avoid this branch with the expression
76     // `(nbits + u32::BITS - 1) / 32::BITS`, but if nbits is almost usize::MAX this will overflow.
77     if bits % B::bits() == 0 {
78         bits / B::bits()
79     } else {
80         bits / B::bits() + 1
81     }
82 }
83
84 // Take two BitVec's, and return iterators of their words, where the shorter one
85 // has been padded with 0's
86 fn match_words<'a,'b, B: BitBlock>(a: &'a BitVec<B>, b: &'b BitVec<B>)
87                 -> (MatchWords<'a, B>, MatchWords<'b, B>) {
88     let a_len = a.storage().len();
89     let b_len = b.storage().len();
90
91     // have to uselessly pretend to pad the longer one for type matching
92     if a_len < b_len {
93         (a.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(b_len).skip(a_len)),
94          b.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(0).skip(0)))
95     } else {
96         (a.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(0).skip(0)),
97          b.blocks().enumerate().chain(iter::repeat(B::zero()).enumerate().take(a_len).skip(b_len)))
98     }
99 }
100
101 pub struct BitSet<B=u32> {
102     bit_vec: BitVec<B>,
103 }
104
105 impl<B: BitBlock> Clone for BitSet<B> {
106         fn clone(&self) -> Self {
107                 BitSet {
108                         bit_vec: self.bit_vec.clone(),
109                 }
110         }
111 }
112
113 impl<B: BitBlock> Default for BitSet<B> {
114     #[inline]
115     fn default() -> Self { BitSet::new() }
116 }
117
118 impl<B: BitBlock> FromIterator<usize> for BitSet<B> {
119     fn from_iter<I: IntoIterator<Item=usize>>(iter: I) -> Self {
120         let mut ret = BitSet::new();
121         ret.extend(iter);
122         ret
123     }
124 }
125
126 impl<B: BitBlock> Extend<usize> for BitSet<B> {
127     #[inline]
128     fn extend<I: IntoIterator<Item=usize>>(&mut self, iter: I) {
129         for i in iter {
130             self.insert(i);
131         }
132     }
133 }
134
135 impl<B: BitBlock> PartialOrd for BitSet<B> {
136     #[inline]
137     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
138         let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
139         iter::order::partial_cmp(a_iter, b_iter)
140     }
141 }
142
143 impl<B: BitBlock> Ord for BitSet<B> {
144     #[inline]
145     fn cmp(&self, other: &Self) -> Ordering {
146         let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
147         iter::order::cmp(a_iter, b_iter)
148     }
149 }
150
151 impl<B: BitBlock> cmp::PartialEq for BitSet<B> {
152     #[inline]
153     fn eq(&self, other: &Self) -> bool {
154         let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref());
155         iter::order::eq(a_iter, b_iter)
156     }
157 }
158
159 impl<B: BitBlock> cmp::Eq for BitSet<B> {}
160
161 impl<B: BitBlock> BitSet<B> {
162     /// Creates a new empty `BitSet`.
163     ///
164     /// # Examples
165     ///
166     /// ```
167     /// # #![feature(collections)]
168     /// use std::collections::BitSet;
169     ///
170     /// let mut s = BitSet::new();
171     /// ```
172     #[inline]
173     pub fn new() -> Self {
174         BitSet { bit_vec: BitVec::new() }
175     }
176
177     /// Creates a new `BitSet` with initially no contents, able to
178     /// hold `nbits` elements without resizing.
179     ///
180     /// # Examples
181     ///
182     /// ```
183     /// # #![feature(collections)]
184     /// use std::collections::BitSet;
185     ///
186     /// let mut s = BitSet::with_capacity(100);
187     /// assert!(s.capacity() >= 100);
188     /// ```
189     #[inline]
190     pub fn with_capacity(nbits: usize) -> Self {
191         let bit_vec = BitVec::from_elem(nbits, false);
192         BitSet::from_bit_vec(bit_vec)
193     }
194
195     /// Creates a new `BitSet` from the given bit vector.
196     ///
197     /// # Examples
198     ///
199     /// ```
200     /// # #![feature(collections)]
201     /// use std::collections::{BitVec, BitSet};
202     ///
203     /// let bv = BitVec::from_bytes(&[0b01100000]);
204     /// let s = BitSet::from_bit_vec(bv);
205     ///
206     /// // Print 1, 2 in arbitrary order
207     /// for x in s.iter() {
208     ///     println!("{}", x);
209     /// }
210     /// ```
211     #[inline]
212     pub fn from_bit_vec(bit_vec: BitVec<B>) -> Self {
213         BitSet { bit_vec: bit_vec }
214     }
215
216     /// Returns the capacity in bits for this bit vector. Inserting any
217     /// element less than this amount will not trigger a resizing.
218     ///
219     /// # Examples
220     ///
221     /// ```
222     /// # #![feature(collections)]
223     /// use std::collections::BitSet;
224     ///
225     /// let mut s = BitSet::with_capacity(100);
226     /// assert!(s.capacity() >= 100);
227     /// ```
228     #[inline]
229     pub fn capacity(&self) -> usize {
230         self.bit_vec.capacity()
231     }
232
233     /// Reserves capacity for the given `BitSet` to contain `len` distinct elements. In the case
234     /// of `BitSet` this means reallocations will not occur as long as all inserted elements
235     /// are less than `len`.
236     ///
237     /// The collection may reserve more space to avoid frequent reallocations.
238     ///
239     ///
240     /// # Examples
241     ///
242     /// ```
243     /// # #![feature(collections)]
244     /// use std::collections::BitSet;
245     ///
246     /// let mut s = BitSet::new();
247     /// s.reserve_len(10);
248     /// assert!(s.capacity() >= 10);
249     /// ```
250     pub fn reserve_len(&mut self, len: usize) {
251         let cur_len = self.bit_vec.len();
252         if len >= cur_len {
253             self.bit_vec.reserve(len - cur_len);
254         }
255     }
256
257     /// Reserves the minimum capacity for the given `BitSet` to contain `len` distinct elements.
258     /// In the case of `BitSet` this means reallocations will not occur as long as all inserted
259     /// elements are less than `len`.
260     ///
261     /// Note that the allocator may give the collection more space than it requests. Therefore
262     /// capacity can not be relied upon to be precisely minimal. Prefer `reserve_len` if future
263     /// insertions are expected.
264     ///
265     ///
266     /// # Examples
267     ///
268     /// ```
269     /// # #![feature(collections)]
270     /// use std::collections::BitSet;
271     ///
272     /// let mut s = BitSet::new();
273     /// s.reserve_len_exact(10);
274     /// assert!(s.capacity() >= 10);
275     /// ```
276     pub fn reserve_len_exact(&mut self, len: usize) {
277         let cur_len = self.bit_vec.len();
278         if len >= cur_len {
279             self.bit_vec.reserve_exact(len - cur_len);
280         }
281     }
282
283
284     /// Consumes this set to return the underlying bit vector.
285     ///
286     /// # Examples
287     ///
288     /// ```
289     /// # #![feature(collections)]
290     /// use std::collections::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     /// # #![feature(collections)]
311     /// use std::collections::BitSet;
312     ///
313     /// let mut s = BitSet::new();
314     /// s.insert(0);
315     ///
316     /// let bv = s.get_ref();
317     /// assert_eq!(bv[0], true);
318     /// ```
319     #[inline]
320     pub fn get_ref(&self) -> &BitVec<B> {
321         &self.bit_vec
322     }
323
324     #[inline]
325     fn other_op<F>(&mut self, other: &Self, mut f: F) where F: FnMut(B, B) -> B {
326         // Unwrap BitVecs
327         let self_bit_vec = &mut self.bit_vec;
328         let other_bit_vec = &other.bit_vec;
329
330         let self_len = self_bit_vec.len();
331         let other_len = other_bit_vec.len();
332
333         // Expand the vector if necessary
334         if self_len < other_len {
335             self_bit_vec.grow(other_len - self_len, false);
336         }
337
338         // virtually pad other with 0's for equal lengths
339         let other_words = {
340             let (_, result) = match_words(self_bit_vec, other_bit_vec);
341             result
342         };
343
344         // Apply values found in other
345         for (i, w) in other_words {
346             let old = self_bit_vec.storage()[i];
347             let new = f(old, w);
348             unsafe {
349                 self_bit_vec.storage_mut()[i] = new;
350             }
351         }
352     }
353
354     /// Truncates the underlying vector to the least length required.
355     ///
356     /// # Examples
357     ///
358     /// ```
359     /// # #![feature(collections)]
360     /// use std::collections::BitSet;
361     ///
362     /// let mut s = BitSet::new();
363     /// s.insert(32183231);
364     /// s.remove(&32183231);
365     ///
366     /// // Internal storage will probably be bigger than necessary
367     /// println!("old capacity: {}", s.capacity());
368     ///
369     /// // Now should be smaller
370     /// s.shrink_to_fit();
371     /// println!("new capacity: {}", s.capacity());
372     /// ```
373     #[inline]
374     pub fn shrink_to_fit(&mut self) {
375         let bit_vec = &mut self.bit_vec;
376         // Obtain original length
377         let old_len = bit_vec.storage().len();
378         // Obtain coarse trailing zero length
379         let n = bit_vec.storage().iter().rev().take_while(|&&n| n == B::zero()).count();
380         // Truncate
381         let trunc_len = cmp::max(old_len - n, 1);
382         unsafe {
383                 bit_vec.storage_mut().truncate(trunc_len);
384                 bit_vec.set_len(trunc_len * B::bits());
385         }
386     }
387
388     /// Iterator over each usize stored in the `BitSet`.
389     ///
390     /// # Examples
391     ///
392     /// ```
393     /// # #![feature(collections)]
394     /// use std::collections::{BitVec, BitSet};
395     ///
396     /// let s = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01001010]));
397     ///
398     /// // Print 1, 4, 6 in arbitrary order
399     /// for x in s.iter() {
400     ///     println!("{}", x);
401     /// }
402     /// ```
403     #[inline]
404     pub fn iter(&self) -> Iter<B> {
405         Iter(BlockIter::from_blocks(self.bit_vec.blocks()))
406     }
407
408     /// Iterator over each usize stored in `self` union `other`.
409     /// See [union_with](#method.union_with) for an efficient in-place version.
410     ///
411     /// # Examples
412     ///
413     /// ```
414     /// # #![feature(collections)]
415     /// use std::collections::{BitVec, BitSet};
416     ///
417     /// let a = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01101000]));
418     /// let b = BitSet::from_bit_vec(BitVec::from_bytes(&[0b10100000]));
419     ///
420     /// // Print 0, 1, 2, 4 in arbitrary order
421     /// for x in a.union(&b) {
422     ///     println!("{}", x);
423     /// }
424     /// ```
425     #[inline]
426     pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, B> {
427         fn or<B: BitBlock>(w1: B, w2: B) -> B { w1 | w2 }
428
429         Union(BlockIter::from_blocks(TwoBitPositions {
430             set: self.bit_vec.blocks(),
431             other: other.bit_vec.blocks(),
432             merge: or,
433         }))
434     }
435
436     /// Iterator over each usize stored in `self` intersect `other`.
437     /// See [intersect_with](#method.intersect_with) for an efficient in-place version.
438     ///
439     /// # Examples
440     ///
441     /// ```
442     /// # #![feature(collections)]
443     /// use std::collections::{BitVec, BitSet};
444     ///
445     /// let a = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01101000]));
446     /// let b = BitSet::from_bit_vec(BitVec::from_bytes(&[0b10100000]));
447     ///
448     /// // Print 2
449     /// for x in a.intersection(&b) {
450     ///     println!("{}", x);
451     /// }
452     /// ```
453     #[inline]
454     pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, B> {
455         fn bitand<B: BitBlock>(w1: B, w2: B) -> B { w1 & w2 }
456         let min = cmp::min(self.bit_vec.len(), other.bit_vec.len());
457
458         Intersection(BlockIter::from_blocks(TwoBitPositions {
459             set: self.bit_vec.blocks(),
460             other: other.bit_vec.blocks(),
461             merge: bitand,
462         }).take(min))
463     }
464
465     /// Iterator over each usize stored in the `self` setminus `other`.
466     /// See [difference_with](#method.difference_with) for an efficient in-place version.
467     ///
468     /// # Examples
469     ///
470     /// ```
471     /// # #![feature(collections)]
472     /// use std::collections::{BitSet, BitVec};
473     ///
474     /// let a = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01101000]));
475     /// let b = BitSet::from_bit_vec(BitVec::from_bytes(&[0b10100000]));
476     ///
477     /// // Print 1, 4 in arbitrary order
478     /// for x in a.difference(&b) {
479     ///     println!("{}", x);
480     /// }
481     ///
482     /// // Note that difference is not symmetric,
483     /// // and `b - a` means something else.
484     /// // This prints 0
485     /// for x in b.difference(&a) {
486     ///     println!("{}", x);
487     /// }
488     /// ```
489     #[inline]
490     pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, B> {
491         fn diff<B: BitBlock>(w1: B, w2: B) -> B { w1 & !w2 }
492
493         Difference(BlockIter::from_blocks(TwoBitPositions {
494             set: self.bit_vec.blocks(),
495             other: other.bit_vec.blocks(),
496             merge: diff,
497         }))
498     }
499
500     /// Iterator over each usize stored in the symmetric difference of `self` and `other`.
501     /// See [symmetric_difference_with](#method.symmetric_difference_with) for
502     /// an efficient in-place version.
503     ///
504     /// # Examples
505     ///
506     /// ```
507     /// # #![feature(collections)]
508     /// use std::collections::{BitSet, BitVec};
509     ///
510     /// let a = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01101000]));
511     /// let b = BitSet::from_bit_vec(BitVec::from_bytes(&[0b10100000]));
512     ///
513     /// // Print 0, 1, 4 in arbitrary order
514     /// for x in a.symmetric_difference(&b) {
515     ///     println!("{}", x);
516     /// }
517     /// ```
518     #[inline]
519     pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> SymmetricDifference<'a, B> {
520         fn bitxor<B: BitBlock>(w1: B, w2: B) -> B { w1 ^ w2 }
521
522         SymmetricDifference(BlockIter::from_blocks(TwoBitPositions {
523             set: self.bit_vec.blocks(),
524             other: other.bit_vec.blocks(),
525             merge: bitxor,
526         }))
527     }
528
529     /// Unions in-place with the specified other bit vector.
530     ///
531     /// # Examples
532     ///
533     /// ```
534     /// # #![feature(collections)]
535     /// use std::collections::{BitSet, BitVec};
536     ///
537     /// let a   = 0b01101000;
538     /// let b   = 0b10100000;
539     /// let res = 0b11101000;
540     ///
541     /// let mut a = BitSet::from_bit_vec(BitVec::from_bytes(&[a]));
542     /// let b = BitSet::from_bit_vec(BitVec::from_bytes(&[b]));
543     /// let res = BitSet::from_bit_vec(BitVec::from_bytes(&[res]));
544     ///
545     /// a.union_with(&b);
546     /// assert_eq!(a, res);
547     /// ```
548     #[inline]
549     pub fn union_with(&mut self, other: &Self) {
550         self.other_op(other, |w1, w2| w1 | w2);
551     }
552
553     /// Intersects in-place with the specified other bit vector.
554     ///
555     /// # Examples
556     ///
557     /// ```
558     /// # #![feature(collections)]
559     /// use std::collections::{BitSet, BitVec};
560     ///
561     /// let a   = 0b01101000;
562     /// let b   = 0b10100000;
563     /// let res = 0b00100000;
564     ///
565     /// let mut a = BitSet::from_bit_vec(BitVec::from_bytes(&[a]));
566     /// let b = BitSet::from_bit_vec(BitVec::from_bytes(&[b]));
567     /// let res = BitSet::from_bit_vec(BitVec::from_bytes(&[res]));
568     ///
569     /// a.intersect_with(&b);
570     /// assert_eq!(a, res);
571     /// ```
572     #[inline]
573     pub fn intersect_with(&mut self, other: &Self) {
574         self.other_op(other, |w1, w2| w1 & w2);
575     }
576
577     /// Makes this bit vector the difference with the specified other bit vector
578     /// in-place.
579     ///
580     /// # Examples
581     ///
582     /// ```
583     /// # #![feature(collections)]
584     /// use std::collections::{BitSet, BitVec};
585     ///
586     /// let a   = 0b01101000;
587     /// let b   = 0b10100000;
588     /// let a_b = 0b01001000; // a - b
589     /// let b_a = 0b10000000; // b - a
590     ///
591     /// let mut bva = BitSet::from_bit_vec(BitVec::from_bytes(&[a]));
592     /// let bvb = BitSet::from_bit_vec(BitVec::from_bytes(&[b]));
593     /// let bva_b = BitSet::from_bit_vec(BitVec::from_bytes(&[a_b]));
594     /// let bvb_a = BitSet::from_bit_vec(BitVec::from_bytes(&[b_a]));
595     ///
596     /// bva.difference_with(&bvb);
597     /// assert_eq!(bva, bva_b);
598     ///
599     /// let bva = BitSet::from_bit_vec(BitVec::from_bytes(&[a]));
600     /// let mut bvb = BitSet::from_bit_vec(BitVec::from_bytes(&[b]));
601     ///
602     /// bvb.difference_with(&bva);
603     /// assert_eq!(bvb, bvb_a);
604     /// ```
605     #[inline]
606     pub fn difference_with(&mut self, other: &Self) {
607         self.other_op(other, |w1, w2| w1 & !w2);
608     }
609
610     /// Makes this bit vector the symmetric difference with the specified other
611     /// bit vector in-place.
612     ///
613     /// # Examples
614     ///
615     /// ```
616     /// # #![feature(collections)]
617     /// use std::collections::{BitSet, BitVec};
618     ///
619     /// let a   = 0b01101000;
620     /// let b   = 0b10100000;
621     /// let res = 0b11001000;
622     ///
623     /// let mut a = BitSet::from_bit_vec(BitVec::from_bytes(&[a]));
624     /// let b = BitSet::from_bit_vec(BitVec::from_bytes(&[b]));
625     /// let res = BitSet::from_bit_vec(BitVec::from_bytes(&[res]));
626     ///
627     /// a.symmetric_difference_with(&b);
628     /// assert_eq!(a, res);
629     /// ```
630     #[inline]
631     pub fn symmetric_difference_with(&mut self, other: &Self) {
632         self.other_op(other, |w1, w2| w1 ^ w2);
633     }
634
635 /*
636     /// Moves all elements from `other` into `Self`, leaving `other` empty.
637     ///
638     /// # Examples
639     ///
640     /// ```
641     /// # #![feature(collections, bit_set_append_split_off)]
642     /// use std::collections::{BitVec, BitSet};
643     ///
644     /// let mut a = BitSet::new();
645     /// a.insert(2);
646     /// a.insert(6);
647     ///
648     /// let mut b = BitSet::new();
649     /// b.insert(1);
650     /// b.insert(3);
651     /// b.insert(6);
652     ///
653     /// a.append(&mut b);
654     ///
655     /// assert_eq!(a.len(), 4);
656     /// assert_eq!(b.len(), 0);
657     /// assert_eq!(a, BitSet::from_bit_vec(BitVec::from_bytes(&[0b01110010])));
658     /// ```
659     pub fn append(&mut self, other: &mut Self) {
660         self.union_with(other);
661         other.clear();
662     }
663
664     /// Splits the `BitSet` into two at the given key including the key.
665     /// Retains the first part in-place while returning the second part.
666     ///
667     /// # Examples
668     ///
669     /// ```
670     /// # #![feature(collections, bit_set_append_split_off)]
671     /// use std::collections::{BitSet, BitVec};
672     /// let mut a = BitSet::new();
673     /// a.insert(2);
674     /// a.insert(6);
675     /// a.insert(1);
676     /// a.insert(3);
677     ///
678     /// let b = a.split_off(3);
679     ///
680     /// assert_eq!(a.len(), 2);
681     /// assert_eq!(b.len(), 2);
682     /// assert_eq!(a, BitSet::from_bit_vec(BitVec::from_bytes(&[0b01100000])));
683     /// assert_eq!(b, BitSet::from_bit_vec(BitVec::from_bytes(&[0b00010010])));
684     /// ```
685     pub fn split_off(&mut self, at: usize) -> Self {
686         let mut other = BitSet::new();
687
688         if at == 0 {
689             swap(self, &mut other);
690             return other;
691         } else if at >= self.bit_vec.len() {
692             return other;
693         }
694
695         // Calculate block and bit at which to split
696         let w = at / u32::BITS;
697         let b = at % u32::BITS;
698
699         // Pad `other` with `w` zero blocks,
700         // append `self`'s blocks in the range from `w` to the end to `other`
701         other.bit_vec.storage_mut().extend(repeat(0u32).take(w)
702                                      .chain(self.bit_vec.storage()[w..].iter().cloned()));
703         other.bit_vec.nbits = self.bit_vec.nbits;
704
705         if b > 0 {
706             other.bit_vec.storage_mut()[w] &= !0 << b;
707         }
708
709         // Sets `bit_vec.len()` and fixes the last block as well
710         self.bit_vec.truncate(at);
711
712         other
713     }
714 */
715
716     /// Returns the number of set bits in this set.
717     #[inline]
718     pub fn len(&self) -> usize  {
719         self.bit_vec.blocks().fold(0, |acc, n| acc + n.count_ones() as usize)
720     }
721
722     /// Returns whether there are no bits set in this set
723     #[inline]
724     pub fn is_empty(&self) -> bool {
725         self.bit_vec.none()
726     }
727
728     /// Clears all bits in this set
729     #[inline]
730     pub fn clear(&mut self) {
731         self.bit_vec.clear();
732     }
733
734     /// Returns `true` if this set contains the specified integer.
735     #[inline]
736     pub fn contains(&self, value: &usize) -> bool {
737         let bit_vec = &self.bit_vec;
738         *value < bit_vec.len() && bit_vec[*value]
739     }
740
741     /// Returns `true` if the set has no elements in common with `other`.
742     /// This is equivalent to checking for an empty intersection.
743     #[inline]
744     pub fn is_disjoint(&self, other: &Self) -> bool {
745         self.intersection(other).next().is_none()
746     }
747
748     /// Returns `true` if the set is a subset of another.
749     #[inline]
750     pub fn is_subset(&self, other: &Self) -> bool {
751         let self_bit_vec = &self.bit_vec;
752         let other_bit_vec = &other.bit_vec;
753         let other_blocks = blocks_for_bits::<B>(other_bit_vec.len());
754
755         // Check that `self` intersect `other` is self
756         self_bit_vec.blocks().zip(other_bit_vec.blocks()).all(|(w1, w2)| w1 & w2 == w1) &&
757         // Make sure if `self` has any more blocks than `other`, they're all 0
758         self_bit_vec.blocks().skip(other_blocks).all(|w| w == B::zero())
759     }
760
761     /// Returns `true` if the set is a superset of another.
762     #[inline]
763     pub fn is_superset(&self, other: &Self) -> bool {
764         other.is_subset(self)
765     }
766
767     /// Adds a value to the set. Returns `true` if the value was not already
768     /// present in the set.
769     pub fn insert(&mut self, value: usize) -> bool {
770         if self.contains(&value) {
771             return false;
772         }
773
774         // Ensure we have enough space to hold the new element
775         let len = self.bit_vec.len();
776         if value >= len {
777             self.bit_vec.grow(value - len + 1, false)
778         }
779
780         self.bit_vec.set(value, true);
781         return true;
782     }
783
784     /// Removes a value from the set. Returns `true` if the value was
785     /// present in the set.
786     pub fn remove(&mut self, value: &usize) -> bool {
787         if !self.contains(value) {
788             return false;
789         }
790
791         self.bit_vec.set(*value, false);
792
793         return true;
794     }
795 }
796
797 impl<B: BitBlock> fmt::Debug for BitSet<B> {
798     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
799         try!(write!(fmt, "{{"));
800         let mut first = true;
801         for n in self {
802             if !first {
803                 try!(write!(fmt, ", "));
804             }
805             try!(write!(fmt, "{:?}", n));
806             first = false;
807         }
808         write!(fmt, "}}")
809     }
810 }
811
812 impl<B: BitBlock> hash::Hash for BitSet<B> {
813     fn hash<H: hash::Hasher>(&self, state: &mut H) {
814         for pos in self {
815             pos.hash(state);
816         }
817     }
818 }
819
820 #[derive(Clone)]
821 struct BlockIter<T, B> {
822     head: B,
823     head_offset: usize,
824     tail: T,
825 }
826
827 impl<T, B: BitBlock> BlockIter<T, B> where T: Iterator<Item=B> {
828     fn from_blocks(mut blocks: T) -> BlockIter<T, B> {
829         let h = blocks.next().unwrap_or(B::zero());
830         BlockIter {tail: blocks, head: h, head_offset: 0}
831     }
832 }
833
834 /// An iterator combining two `BitSet` iterators.
835 #[derive(Clone)]
836 struct TwoBitPositions<'a, B: 'a> {
837     set: Blocks<'a, B>,
838     other: Blocks<'a, B>,
839     merge: fn(B, B) -> B,
840 }
841
842 /// An iterator for `BitSet`.
843 #[derive(Clone)]
844 pub struct Iter<'a, B: 'a>(BlockIter<Blocks<'a, B>, B>);
845 #[derive(Clone)]
846 pub struct Union<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
847 #[derive(Clone)]
848 pub struct Intersection<'a, B: 'a>(Take<BlockIter<TwoBitPositions<'a, B>, B>>);
849 #[derive(Clone)]
850 pub struct Difference<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
851 #[derive(Clone)]
852 pub struct SymmetricDifference<'a, B: 'a>(BlockIter<TwoBitPositions<'a, B>, B>);
853
854 impl<'a, T, B: BitBlock> Iterator for BlockIter<T, B> where T: Iterator<Item=B> {
855     type Item = usize;
856
857     fn next(&mut self) -> Option<usize> {
858         while self.head == B::zero() {
859             match self.tail.next() {
860                 Some(w) => self.head = w,
861                 None => return None
862             }
863             self.head_offset += B::bits();
864         }
865
866         // from the current block, isolate the
867         // LSB and subtract 1, producing k:
868         // a block with a number of set bits
869         // equal to the index of the LSB
870         let k = (self.head & (!self.head + B::one())) - B::one();
871         // update block, removing the LSB
872         self.head = self.head & (self.head - B::one());
873         // return offset + (index of LSB)
874         Some(self.head_offset + (B::count_ones(k) as usize))
875     }
876
877     #[inline]
878     fn size_hint(&self) -> (usize, Option<usize>) {
879         match self.tail.size_hint() {
880             (_, Some(h)) => (0, Some(1 + h * B::bits())),
881             _ => (0, None)
882         }
883     }
884 }
885
886 impl<'a, B: BitBlock> Iterator for TwoBitPositions<'a, B> {
887     type Item = B;
888
889     fn next(&mut self) -> Option<B> {
890         match (self.set.next(), self.other.next()) {
891             (Some(a), Some(b)) => Some((self.merge)(a, b)),
892             (Some(a), None) => Some((self.merge)(a, B::zero())),
893             (None, Some(b)) => Some((self.merge)(B::zero(), b)),
894             _ => return None
895         }
896     }
897
898     #[inline]
899     fn size_hint(&self) -> (usize, Option<usize>) {
900         let (a, au) = self.set.size_hint();
901         let (b, bu) = self.other.size_hint();
902
903         let upper = match (au, bu) {
904             (Some(au), Some(bu)) => Some(cmp::max(au, bu)),
905             _ => None
906         };
907
908         (cmp::max(a, b), upper)
909     }
910 }
911
912 impl<'a, B: BitBlock> Iterator for Iter<'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 Union<'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> Iterator for Intersection<'a, B> {
927     type Item = usize;
928
929     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
930     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
931 }
932
933 impl<'a, B: BitBlock> Iterator for Difference<'a, B> {
934     type Item = usize;
935
936     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
937     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
938 }
939
940 impl<'a, B: BitBlock> Iterator for SymmetricDifference<'a, B> {
941     type Item = usize;
942
943     #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
944     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
945 }
946
947 impl<'a, B: BitBlock> IntoIterator for &'a BitSet<B> {
948     type Item = usize;
949     type IntoIter = Iter<'a, B>;
950
951     fn into_iter(self) -> Iter<'a, B> {
952         self.iter()
953     }
954 }