1 // Copyright 2015 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.
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.
11 use std::iter::FromIterator;
13 /// A very simple BitVector type.
14 #[derive(Clone, Debug, PartialEq)]
15 pub struct BitVector {
21 pub fn new(num_bits: usize) -> BitVector {
22 let num_words = u64s(num_bits);
23 BitVector { data: vec![0; num_words] }
27 pub fn clear(&mut self) {
28 for p in &mut self.data {
33 pub fn count(&self) -> usize {
34 self.data.iter().map(|e| e.count_ones() as usize).sum()
38 pub fn contains(&self, bit: usize) -> bool {
39 let (word, mask) = word_mask(bit);
40 (self.data[word] & mask) != 0
43 /// Returns true if the bit has changed.
45 pub fn insert(&mut self, bit: usize) -> bool {
46 let (word, mask) = word_mask(bit);
47 let data = &mut self.data[word];
49 let new_value = value | mask;
54 /// Returns true if the bit has changed.
56 pub fn remove(&mut self, bit: usize) -> bool {
57 let (word, mask) = word_mask(bit);
58 let data = &mut self.data[word];
60 let new_value = value & !mask;
66 pub fn insert_all(&mut self, all: &BitVector) -> bool {
67 assert!(self.data.len() == all.data.len());
68 let mut changed = false;
69 for (i, j) in self.data.iter_mut().zip(&all.data) {
80 pub fn grow(&mut self, num_bits: usize) {
81 let num_words = u64s(num_bits);
82 if self.data.len() < num_words {
83 self.data.resize(num_words, 0)
87 /// Iterates over indexes of set bits in a sorted order
89 pub fn iter<'a>(&'a self) -> BitVectorIter<'a> {
91 iter: self.data.iter(),
98 pub struct BitVectorIter<'a> {
99 iter: ::std::slice::Iter<'a, u64>,
104 impl<'a> Iterator for BitVectorIter<'a> {
106 fn next(&mut self) -> Option<usize> {
107 while self.current == 0 {
108 self.current = if let Some(&i) = self.iter.next() {
113 self.idx = u64s(self.idx) * 64;
120 let offset = self.current.trailing_zeros() as usize;
121 self.current >>= offset;
122 self.current >>= 1; // shift otherwise overflows for 0b1000_0000_…_0000
123 self.idx += offset + 1;
124 return Some(self.idx - 1);
128 impl FromIterator<bool> for BitVector {
129 fn from_iter<I>(iter: I) -> BitVector where I: IntoIterator<Item=bool> {
130 let iter = iter.into_iter();
131 let (len, _) = iter.size_hint();
132 // Make the minimum length for the bitvector 64 bits since that's
133 // the smallest non-zero size anyway.
134 let len = if len < 64 { 64 } else { len };
135 let mut bv = BitVector::new(len);
136 for (idx, val) in iter.enumerate() {
149 /// A "bit matrix" is basically a matrix of booleans represented as
150 /// one gigantic bitvector. In other words, it is as if you have
151 /// `rows` bitvectors, each of length `columns`.
152 #[derive(Clone, Debug)]
153 pub struct BitMatrix {
159 /// Create a new `rows x columns` matrix, initially empty.
160 pub fn new(rows: usize, columns: usize) -> BitMatrix {
161 // For every element, we need one bit for every other
162 // element. Round up to an even number of u64s.
163 let u64s_per_row = u64s(columns);
166 vector: vec![0; rows * u64s_per_row],
170 /// The range of bits for a given row.
171 fn range(&self, row: usize) -> (usize, usize) {
172 let u64s_per_row = u64s(self.columns);
173 let start = row * u64s_per_row;
174 (start, start + u64s_per_row)
177 /// Sets the cell at `(row, column)` to true. Put another way, add
178 /// `column` to the bitset for `row`.
180 /// Returns true if this changed the matrix, and false otherwies.
181 pub fn add(&mut self, row: usize, column: usize) -> bool {
182 let (start, _) = self.range(row);
183 let (word, mask) = word_mask(column);
184 let vector = &mut self.vector[..];
185 let v1 = vector[start + word];
187 vector[start + word] = v2;
191 /// Do the bits from `row` contain `column`? Put another way, is
192 /// the matrix cell at `(row, column)` true? Put yet another way,
193 /// if the matrix represents (transitive) reachability, can
194 /// `row` reach `column`?
195 pub fn contains(&self, row: usize, column: usize) -> bool {
196 let (start, _) = self.range(row);
197 let (word, mask) = word_mask(column);
198 (self.vector[start + word] & mask) != 0
201 /// Returns those indices that are true in rows `a` and `b`. This
202 /// is an O(n) operation where `n` is the number of elements
203 /// (somewhat independent from the actual size of the
204 /// intersection, in particular).
205 pub fn intersection(&self, a: usize, b: usize) -> Vec<usize> {
206 let (a_start, a_end) = self.range(a);
207 let (b_start, b_end) = self.range(b);
208 let mut result = Vec::with_capacity(self.columns);
209 for (base, (i, j)) in (a_start..a_end).zip(b_start..b_end).enumerate() {
210 let mut v = self.vector[i] & self.vector[j];
216 result.push(base * 64 + bit);
224 /// Add the bits from row `read` to the bits from row `write`,
225 /// return true if anything changed.
227 /// This is used when computing transitive reachability because if
228 /// you have an edge `write -> read`, because in that case
229 /// `write` can reach everything that `read` can (and
230 /// potentially more).
231 pub fn merge(&mut self, read: usize, write: usize) -> bool {
232 let (read_start, read_end) = self.range(read);
233 let (write_start, write_end) = self.range(write);
234 let vector = &mut self.vector[..];
235 let mut changed = false;
236 for (read_index, write_index) in (read_start..read_end).zip(write_start..write_end) {
237 let v1 = vector[write_index];
238 let v2 = v1 | vector[read_index];
239 vector[write_index] = v2;
240 changed = changed | (v1 != v2);
245 /// Iterates through all the columns set to true in a given row of
247 pub fn iter<'a>(&'a self, row: usize) -> BitVectorIter<'a> {
248 let (start, end) = self.range(row);
250 iter: self.vector[start..end].iter(),
258 fn u64s(elements: usize) -> usize {
263 fn word_mask(index: usize) -> (usize, u64) {
264 let word = index / 64;
265 let mask = 1 << (index % 64);
270 fn bitvec_iter_works() {
271 let mut bitvec = BitVector::new(100);
281 assert_eq!(bitvec.iter().collect::<Vec<_>>(),
282 [1, 10, 19, 62, 63, 64, 65, 66, 99]);
287 fn bitvec_iter_works_2() {
288 let mut bitvec = BitVector::new(319);
294 assert_eq!(bitvec.iter().collect::<Vec<_>>(), [0, 127, 191, 255, 319]);
298 fn union_two_vecs() {
299 let mut vec1 = BitVector::new(65);
300 let mut vec2 = BitVector::new(65);
301 assert!(vec1.insert(3));
302 assert!(!vec1.insert(3));
303 assert!(vec2.insert(5));
304 assert!(vec2.insert(64));
305 assert!(vec1.insert_all(&vec2));
306 assert!(!vec1.insert_all(&vec2));
307 assert!(vec1.contains(3));
308 assert!(!vec1.contains(4));
309 assert!(vec1.contains(5));
310 assert!(!vec1.contains(63));
311 assert!(vec1.contains(64));
316 let mut vec1 = BitVector::new(65);
317 for index in 0 .. 65 {
318 assert!(vec1.insert(index));
319 assert!(!vec1.insert(index));
323 // Check if the bits set before growing are still set
324 for index in 0 .. 65 {
325 assert!(vec1.contains(index));
328 // Check if the new bits are all un-set
329 for index in 65 .. 128 {
330 assert!(!vec1.contains(index));
333 // Check that we can set all new bits without running out of bounds
334 for index in 65 .. 128 {
335 assert!(vec1.insert(index));
336 assert!(!vec1.insert(index));
341 fn matrix_intersection() {
342 let mut vec1 = BitMatrix::new(200, 200);
344 // (*) Elements reachable from both 2 and 65.
348 vec1.add(2, 10); // (*)
349 vec1.add(2, 64); // (*)
352 vec1.add(2, 160); // (*)
358 vec1.add(65, 10); // (*)
359 vec1.add(65, 64); // (*)
362 vec1.add(65, 160); // (*)
364 let intersection = vec1.intersection(2, 64);
365 assert!(intersection.is_empty());
367 let intersection = vec1.intersection(2, 65);
368 assert_eq!(intersection, &[10, 64, 160]);
373 let mut matrix = BitMatrix::new(64, 100);
381 let mut iter = expected.iter();
382 for i in matrix.iter(2) {
383 let j = *iter.next().unwrap();
386 assert!(iter.next().is_none());
388 let expected = [22, 75];
389 let mut iter = expected.iter();
390 for i in matrix.iter(3) {
391 let j = *iter.next().unwrap();
394 assert!(iter.next().is_none());
397 let mut iter = expected.iter();
398 for i in matrix.iter(4) {
399 let j = *iter.next().unwrap();
402 assert!(iter.next().is_none());
404 let expected = [22, 75];
405 let mut iter = expected.iter();
406 for i in matrix.iter(5) {
407 let j = *iter.next().unwrap();
410 assert!(iter.next().is_none());