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