bv/bit_vec/mod.rs
1use super::storage::*;
2use super::slice::*;
3use super::traits::*;
4
5use std::cmp::{max, Ordering};
6use std::ptr;
7
8mod inner;
9use self::inner::Inner;
10
11mod impls;
12
13#[cfg(test)]
14mod test;
15
16/// A bit-vector, akin to `Vec<bool>` but packed.
17///
18/// `BitVec` stores its bits in an array of `Block`s, where `Block` is given as a type parameter
19/// that defaults to `usize`. You might find that a different `Block` size is preferable, but
20/// only benchmarking will tell.
21///
22/// Several useful methods are exported in traits, rather than inherent to `BitVec`. In
23/// particular, see:
24///
25/// - [`Bits::get_bit`](trait.Bits.html#method.get_bit) and
26/// - [`BitsMut::set_bit`](trait.BitsMut.html#method.set_bit).
27///
28/// You will likely want to `use` these traits (or `bv::*`) when you use `BitVec`.
29///
30/// # Examples
31///
32/// ```
33/// use bv::BitVec;
34///
35/// let mut bv: BitVec = BitVec::new();
36/// assert_eq!(bv.len(), 0);
37///
38/// bv.push(true);
39/// bv.push(false);
40/// bv.push(true);
41/// assert_eq!(bv.len(), 3);
42///
43/// assert_eq!(bv[0], true);
44/// assert_eq!(bv[1], false);
45/// assert_eq!(bv[2], true);
46/// ```
47#[derive(Clone)]
48#[cfg_attr(feature = "serde", derive(Serialize))]
49pub struct BitVec<Block: BlockType = usize> {
50 bits: Inner<Block>,
51 len: u64,
52}
53// Invariant: self.invariant()
54
55#[cfg(feature = "serde")]
56impl<'de, Block: BlockType + serde::Deserialize<'de>> serde::Deserialize<'de> for BitVec<Block> {
57 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
58 where
59 D: serde::Deserializer<'de>,
60 {
61 #[derive(Deserialize)]
62 struct Unchecked<Block: BlockType> {
63 bits: Inner<Block>,
64 len: u64,
65 }
66 let unchecked = Unchecked::deserialize(deserializer)?;
67 let unchecked = BitVec {
68 bits: unchecked.bits,
69 len: unchecked.len,
70 };
71 if !unchecked.invariant() {
72 return Err(serde::de::Error::custom("Invalid BitVec"));
73 }
74 Ok(unchecked)
75 }
76}
77
78impl<Block: BlockType> Default for BitVec<Block> {
79 fn default() -> Self {
80 Self::new()
81 }
82}
83
84impl<Block: BlockType> BitVec<Block> {
85 #[allow(dead_code)]
86 fn invariant(&self) -> bool {
87 return self.len <= Block::mul_nbits(self.bits.len());
88 }
89
90 /// Creates a new, empty bit-vector with a capacity of one block.
91 ///
92 /// # Examples
93 ///
94 /// ```
95 /// use bv::BitVec;
96 ///
97 /// let mut bv: BitVec = BitVec::new();
98 /// assert_eq!(bv.len(), 0);
99 ///
100 /// bv.push(true);
101 /// bv.push(false);
102 /// bv.push(true);
103 /// assert_eq!(bv.len(), 3);
104 ///
105 /// assert_eq!(bv[0], true);
106 /// assert_eq!(bv[1], false);
107 /// assert_eq!(bv[2], true);
108 /// ```
109 pub fn new() -> Self {
110 Self::with_block_capacity(0)
111 }
112
113 /// Creates a new, empty bit-vector with the given bit capacity.
114 ///
115 /// # Examples
116 ///
117 /// ```
118 /// use bv::BitVec;
119 ///
120 /// let mut bv: BitVec<u16> = BitVec::with_capacity(20);
121 /// assert_eq!(bv.capacity(), 32);
122 /// ```
123 pub fn with_capacity(nbits: u64) -> Self {
124 Self::with_block_capacity(Block::ceil_div_nbits(nbits))
125 }
126
127 /// Creates a new, empty bit-vector with the given block capacity.
128 ///
129 /// # Examples
130 ///
131 /// ```
132 /// use bv::BitVec;
133 ///
134 /// let mut bv: BitVec<u16> = BitVec::with_block_capacity(8);
135 /// assert_eq!(bv.capacity(), 128);
136 /// ```
137 pub fn with_block_capacity(nblocks: usize) -> Self {
138 let mut result = Self::from_block(Block::zero(), nblocks);
139 result.len = 0;
140 result
141 }
142
143 /// Creates a new bit-vector of size `len`, filled with all 0s or 1s
144 /// depending on `value`.
145 ///
146 /// # Examples
147 ///
148 /// ```
149 /// use bv::*;
150 ///
151 /// let mut bv: BitVec<u64> = BitVec::new_fill(false, 100);
152 ///
153 /// assert_eq!( bv.get(0), false );
154 /// assert_eq!( bv.len(), 100 );
155 /// ```
156 pub fn new_fill(value: bool, len: u64) -> Self {
157 let mut result = Self::new_block_fill(value, Block::ceil_div_nbits(len));
158 result.len = len;
159 result
160 }
161
162 /// Creates a new bit-vector filled with `value`, made up of `nblocks` blocks.
163 #[inline]
164 fn new_block_fill(value: bool, nblocks: usize) -> Self {
165 let block = if value {!Block::zero()} else {Block::zero()};
166 Self::from_block(block, nblocks)
167 }
168
169 #[inline]
170 fn from_block(init: Block, nblocks: usize) -> Self {
171 BitVec {
172 bits: Inner::new(init, nblocks),
173 len: Block::mul_nbits(nblocks),
174 }
175 }
176
177 // Reallocates to have the given capacity.
178 fn reallocate(&mut self, block_cap: usize) {
179 // We know this is safe because the precondition on `close_resize` is
180 // that the first argument gives a valid number of blocks to copy.
181 unsafe {
182 self.bits = self.bits.clone_resize(self.block_len(), block_cap);
183 }
184 }
185
186 /// Creates a new `BitVec` from any value implementing the `Bits` trait with
187 /// the same block type.
188 pub fn from_bits<B: Bits<Block = Block>>(bits: B) -> Self {
189 let block_len = bits.block_len();
190
191 let mut vec: Vec<Block> = Vec::with_capacity(block_len);
192
193 // This is safe because we just allocated the vector to the right size,
194 // and we fully initialize the vector before setting the size.
195 unsafe {
196 let ptr = vec.as_mut_ptr();
197
198 for i in 0 .. block_len {
199 ptr::write(ptr.offset(i as isize), bits.get_raw_block(i));
200 }
201
202 vec.set_len(block_len);
203 }
204
205 let mut result: BitVec<Block> = vec.into();
206 result.resize(bits.bit_len(), false);
207 result
208 }
209
210 /// The number of bits in the bit-vector.
211 ///
212 /// # Examples
213 ///
214 /// ```
215 /// use bv::BitVec;
216 ///
217 /// let mut bv: BitVec = BitVec::new();
218 /// assert_eq!(bv.len(), 0);
219 /// bv.push(false);
220 /// assert_eq!(bv.len(), 1);
221 /// bv.push(false);
222 /// assert_eq!(bv.len(), 2);
223 /// bv.push(false);
224 /// assert_eq!(bv.len(), 3);
225 /// ```
226 #[inline]
227 pub fn len(&self) -> u64 {
228 self.len
229 }
230
231 /// The number of blocks used by this bit-vector.
232 ///
233 /// # Examples
234 ///
235 /// ```
236 /// use bv::*;
237 ///
238 /// let mut bv: BitVec<u64> = BitVec::new_fill(false, 100);
239 ///
240 /// assert_eq!( bv.len(), 100 );
241 /// assert_eq!( bv.block_len(), 2 );
242 /// ```
243 pub fn block_len(&self) -> usize {
244 Block::ceil_div_nbits(self.len())
245 }
246
247 /// The capacity of the bit-vector in bits.
248 ///
249 /// This is the number of bits that can be held without reallocating.
250 ///
251 /// # Examples
252 ///
253 /// ```
254 /// use bv::*;
255 ///
256 /// let bv: BitVec<u64> = bit_vec![false; 100];
257 ///
258 /// assert_eq!( bv.len(), 100 );
259 /// assert_eq!( bv.capacity(), 128 );
260 /// ```
261 ///
262 /// Note that this example holds because `bit_vec!` does not introduces excess
263 /// capacity.
264 pub fn capacity(&self) -> u64 {
265 Block::mul_nbits(self.block_capacity())
266 }
267
268 /// The capacity of the bit-vector in blocks.
269 ///
270 /// # Examples
271 ///
272 /// ```
273 /// use bv::*;
274 ///
275 /// let bv: BitVec<u64> = BitVec::with_capacity(250);
276 ///
277 /// assert_eq!( bv.len(), 0 );
278 /// assert_eq!( bv.block_len(), 0 );
279 /// assert_eq!( bv.capacity(), 256 );
280 /// assert_eq!( bv.block_capacity(), 4 );
281 /// ```
282 ///
283 /// Note that this example holds because `bit_vec!` does not introduces excess
284 /// capacity.
285 pub fn block_capacity(&self) -> usize {
286 self.bits.len()
287 }
288
289 /// Adjust the capacity to hold at least `additional` additional bits.
290 ///
291 /// May reserve more to avoid frequent reallocations.
292 ///
293 /// # Examples
294 ///
295 /// ```
296 /// use bv::*;
297 ///
298 /// let mut bv: BitVec<u32> = bit_vec![ false, false, true ];
299 /// assert_eq!( bv.capacity(), 32 );
300 /// bv.reserve(100);
301 /// assert!( bv.capacity() >= 103 );
302 /// ```
303 pub fn reserve(&mut self, additional: u64) {
304 let old_cap = self.capacity();
305 let req_cap = self.len() + additional;
306 if req_cap > old_cap {
307 self.reserve_exact(max(additional, old_cap));
308 }
309 }
310
311 /// Adjust the capacity to hold at least `additional` additional blocks.
312 ///
313 /// May reserve more to avoid frequent reallocations.
314 ///
315 /// # Examples
316 ///
317 /// ```
318 /// use bv::*;
319 ///
320 /// let mut bv: BitVec<u32> = bit_vec![ false, false, true ];
321 /// assert_eq!( bv.block_capacity(), 1 );
322 /// bv.block_reserve(3);
323 /// assert!( bv.block_capacity() >= 4 );
324 /// ```
325 pub fn block_reserve(&mut self, additional: usize) {
326 let old_cap = self.block_capacity();
327 let req_cap = self.block_len() + additional;
328 if req_cap > old_cap {
329 self.block_reserve_exact(max(additional, old_cap));
330 }
331 }
332
333 /// Adjust the capacity to hold at least `additional` additional bits.
334 ///
335 /// # Examples
336 ///
337 /// ```
338 /// use bv::*;
339 ///
340 /// let mut bv: BitVec<u32> = bit_vec![ false, false, true ];
341 /// assert_eq!( bv.capacity(), 32 );
342 /// bv.reserve_exact(100);
343 /// assert_eq!( bv.capacity(), 128 );
344 /// ```
345 pub fn reserve_exact(&mut self, additional: u64) {
346 let new_cap = Block::ceil_div_nbits(self.len() + additional);
347 if new_cap > self.block_capacity() {
348 self.reallocate(new_cap);
349 }
350 }
351
352 /// Adjusts the capacity to at least `additional` blocks beyond those used.
353 ///
354 /// # Examples
355 ///
356 /// ```
357 /// use bv::*;
358 ///
359 /// let mut bv: BitVec<u32> = bit_vec![ false, false, true ];
360 /// assert_eq!( bv.block_capacity(), 1 );
361 /// bv.block_reserve_exact(3);
362 /// assert_eq!( bv.block_capacity(), 4 );
363 /// ```
364 pub fn block_reserve_exact(&mut self, additional: usize) {
365 let new_cap = self.block_len() + additional;
366 if new_cap > self.block_capacity() {
367 self.reallocate(new_cap);
368 }
369 }
370
371 /// Shrinks the capacity of the vector as much as possible.
372 ///
373 /// # Examples
374 ///
375 /// ```
376 /// use bv::BitVec;
377 ///
378 /// let mut bv: BitVec<u8> = BitVec::new();
379 ///
380 /// for i in 0 .. 23 {
381 /// bv.push(i % 3 == 0);
382 /// }
383 ///
384 /// assert!(bv.capacity() >= 24);
385 ///
386 /// bv.shrink_to_fit();
387 /// assert_eq!(bv.capacity(), 24);
388 /// ```
389 pub fn shrink_to_fit(&mut self) {
390 let block_len = self.block_len();
391 if self.block_capacity() > block_len {
392 self.reallocate(block_len);
393 }
394 }
395
396 /// Converts the vector into `Box<[Block]>`.
397 ///
398 /// Note that this will *not* drop any excess capacity.
399 ///
400 /// # Examples
401 ///
402 /// ```
403 /// use bv::*;
404 ///
405 /// let bv: BitVec<u8> = bit_vec![true, true, false, false, true, false, true, false];
406 /// let bs = bv.into_boxed_slice();
407 ///
408 /// assert!( bs.len() >= 1 );
409 /// assert_eq!( bs[0], 0b01010011 );
410 /// ```
411 pub fn into_boxed_slice(self) -> Box<[Block]> {
412 self.bits.into_boxed_slice()
413 }
414
415 /// Shortens the vector, keeping the first `len` elements and dropping the rest.
416 ///
417 /// If `len` is greater than the vector's current length, this has no effect.
418 ///
419 /// Note that this method has no effect on the capacity of the bit-vector.
420 ///
421 /// # Examples
422 ///
423 /// ```
424 /// use bv::*;
425 ///
426 /// let mut v1: BitVec = bit_vec![ true, true, false, false ];
427 /// let v2: BitVec = bit_vec![ true, true ];
428 ///
429 /// assert_ne!( v1, v2 );
430 ///
431 /// v1.truncate(2);
432 ///
433 /// assert_eq!( v1, v2 );
434 /// ```
435 pub fn truncate(&mut self, len: u64) {
436 if len < self.len {
437 self.len = len;
438 }
439 }
440
441 /// Resizes the bit-vector, filling with `value` if it has to grow.
442 ///
443 /// # Examples
444 ///
445 /// ```
446 /// use bv::*;
447 ///
448 /// let v1: BitVec = bit_vec![ true, true, false, false ];
449 /// let mut v2: BitVec = bit_vec![ true, true ];
450 /// let mut v3: BitVec = bit_vec![ true, true ];
451 ///
452 /// v2.resize(4, false);
453 /// v3.resize(4, true);
454 ///
455 /// assert_eq!( v1, v2 );
456 /// assert_ne!( v1, v3 );
457 /// ```
458 pub fn resize(&mut self, len: u64, value: bool) {
459 match len.cmp(&self.len) {
460 Ordering::Less => {
461 self.len = len
462 },
463 Ordering::Equal => { },
464 Ordering::Greater => {
465 {
466 let growth = len - self.len();
467 self.reserve(growth);
468 }
469
470 self.align_block(value);
471
472 let block = if value {!Block::zero()} else {Block::zero()};
473 while self.len < len {
474 self.push_block(block);
475 }
476
477 self.len = len;
478 },
479 }
480 }
481
482 /// Gets a slice to a `BitVec`.
483 ///
484 /// # Examples
485 ///
486 /// ```
487 /// use bv::*;
488 ///
489 /// let bv: BitVec = bit_vec![true, false, true];
490 /// let slice = bv.as_slice();
491 ///
492 /// assert_eq!( slice.len(), 3 );
493 /// assert_eq!( slice[0], true );
494 /// assert_eq!( slice[1], false );
495 /// assert_eq!( slice[2], true );
496 /// ```
497 pub fn as_slice(&self) -> BitSlice<Block> {
498 // We know this is safe because the precondition on `from_raw_parts` is
499 // that all the bits be in bounds. If `self.len == 0` then there are no
500 // bits to access, so it's okay that the pointer dangles. Otherwise, the
501 // bits from `0 .. self.len` are in bounds.
502 unsafe {
503 BitSlice::from_raw_parts(self.bits.as_ptr(), 0, self.len)
504 }
505 }
506
507 /// Gets a mutable slice to a `BitVec`.
508 ///
509 /// # Examples
510 ///
511 /// ```
512 /// use bv::*;
513 ///
514 /// let mut bv: BitVec = bit_vec![true, false, true];
515 ///
516 /// {
517 /// let mut slice = bv.as_mut_slice();
518 /// slice.set_bit(1, true);
519 /// }
520 ///
521 /// assert_eq!( bv[1], true );
522 /// ```
523 pub fn as_mut_slice(&mut self) -> BitSliceMut<Block> {
524 // We know this is safe for the same reason that `as_slice` is safe.
525 unsafe {
526 BitSliceMut::from_raw_parts(self.bits.as_mut_ptr(), 0, self.len)
527 }
528 }
529
530 /// Gets the value of the bit at the given position.
531 ///
532 /// This is an alias for [`Bits::get_bit`].
533 ///
534 /// # Panics
535 ///
536 /// If the position is out of bounds.
537 ///
538 /// [`Bits::get_bit`]: ../trait.Bits.html#get_bit.method
539 pub fn get(&self, position: u64) -> bool {
540 self.get_bit(position)
541 }
542
543 /// Sets the value of the bit at the given position.
544 ///
545 /// This is an alias for [`BitsMut::set_bit`].
546 ///
547 /// # Panics
548 ///
549 /// If the position is out of bounds.
550 ///
551 /// [`BitsMut::set_bit`]: ../trait.BitsMut.html#set_bit.method
552 pub fn set(&mut self, position: u64, value: bool) {
553 self.set_bit(position, value);
554 }
555
556 /// Adds the given `bool` to the end of the bit-vector.
557 ///
558 /// # Examples
559 ///
560 /// ```
561 /// use bv::*;
562 ///
563 /// let mut bv0: BitVec = bit_vec![ ];
564 /// let bv1: BitVec = bit_vec![ true ];
565 /// let bv2: BitVec = bit_vec![ true, false ];
566 /// let bv3: BitVec = bit_vec![ true, false, true ];
567 ///
568 /// assert_ne!( bv0, bv1 );
569 /// assert_ne!( bv0, bv2 );
570 /// assert_ne!( bv0, bv3 );
571 ///
572 /// bv0.push(true);
573 /// assert_eq!( bv0, bv1 );
574 ///
575 /// bv0.push(false);
576 /// assert_eq!( bv0, bv2 );
577 ///
578 /// bv0.push(true);
579 /// assert_eq!( bv0, bv3 );
580 /// ```
581 pub fn push(&mut self, value: bool) {
582 self.reserve(1);
583 let old_len = self.len;
584 self.len = old_len + 1;
585 self.set_bit(old_len, value);
586 }
587
588 /// Removes and returns the last element of the bit-vector, or `None` if empty.
589 ///
590 /// # Examples
591 ///
592 /// ```
593 /// use bv::*;
594 ///
595 /// let mut bv: BitVec = bit_vec![ true, false, true ];
596 /// assert_eq!( bv.pop(), Some(true) );
597 /// assert_eq!( bv.pop(), Some(false) );
598 /// assert_eq!( bv.pop(), Some(true) );
599 /// assert_eq!( bv.pop(), None );
600 /// ```
601 pub fn pop(&mut self) -> Option<bool> {
602 if self.len > 0 {
603 let new_len = self.len - 1;
604 let result = self.get_bit(new_len);
605 self.len = new_len;
606 Some(result)
607 } else {
608 None
609 }
610 }
611
612 /// Removes all elements from the bit-vector.
613 ///
614 /// Does not change the capacity.
615 ///
616 /// # Examples
617 ///
618 /// ```
619 /// use bv::*;
620 ///
621 /// let mut bv: BitVec<u32> = bit_vec![ true ];
622 /// assert_eq!( bv.len(), 1 );
623 /// assert_eq!( bv.capacity(), 32 );
624 /// bv.clear();
625 /// assert_eq!( bv.len(), 0 );
626 /// assert_eq!( bv.capacity(), 32 );
627 /// ```
628 pub fn clear(&mut self) {
629 self.len = 0;
630 }
631
632 /// Does the bit-vector have no elements?
633 ///
634 /// # Examples
635 ///
636 /// ```
637 /// use bv::*;
638 ///
639 /// let mut bv: BitVec<u32> = bit_vec![ true ];
640 /// assert!( !bv.is_empty() );
641 /// bv.clear();
642 /// assert!( bv.is_empty() );
643 /// ```
644 pub fn is_empty(&self) -> bool {
645 self.len == 0
646 }
647}