|
8 | 8 | // option. This file may not be copied, modified, or distributed
|
9 | 9 | // except according to those terms.
|
10 | 10 |
|
| 11 | +use std::iter::FromIterator; |
| 12 | + |
11 | 13 | /// A very simple BitVector type.
|
12 | 14 | #[derive(Clone)]
|
13 | 15 | pub struct BitVector {
|
@@ -51,7 +53,9 @@ impl BitVector {
|
51 | 53 | pub fn grow(&mut self, num_bits: usize) {
|
52 | 54 | let num_words = u64s(num_bits);
|
53 | 55 | let extra_words = self.data.len() - num_words;
|
54 |
| - self.data.extend((0..extra_words).map(|_| 0)); |
| 56 | + if extra_words > 0 { |
| 57 | + self.data.extend((0..extra_words).map(|_| 0)); |
| 58 | + } |
55 | 59 | }
|
56 | 60 |
|
57 | 61 | /// Iterates over indexes of set bits in a sorted order
|
@@ -94,6 +98,27 @@ impl<'a> Iterator for BitVectorIter<'a> {
|
94 | 98 | }
|
95 | 99 | }
|
96 | 100 |
|
| 101 | +impl FromIterator<bool> for BitVector { |
| 102 | + fn from_iter<I>(iter: I) -> BitVector where I: IntoIterator<Item=bool> { |
| 103 | + let iter = iter.into_iter(); |
| 104 | + let (len, _) = iter.size_hint(); |
| 105 | + // Make the minimum length for the bitvector 64 bits since that's |
| 106 | + // the smallest non-zero size anyway. |
| 107 | + let len = if len < 64 { 64 } else { len }; |
| 108 | + let mut bv = BitVector::new(len); |
| 109 | + for (idx, val) in iter.enumerate() { |
| 110 | + if idx > len { |
| 111 | + bv.grow(idx); |
| 112 | + } |
| 113 | + if val { |
| 114 | + bv.insert(idx); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + bv |
| 119 | + } |
| 120 | +} |
| 121 | + |
97 | 122 | /// A "bit matrix" is basically a square matrix of booleans
|
98 | 123 | /// represented as one gigantic bitvector. In other words, it is as if
|
99 | 124 | /// you have N bitvectors, each of length N. Note that `elements` here is `N`/
|
|
0 commit comments