deepmesa_collections/bitvec/bitvec.rs
1/*
2 BitVector: A fast contiguous growable array of bits allocated
3 on the heap that allows storing and manipulating an arbitrary
4 number of bits. This collection is backed by a Vector<u8> which
5 manages the underlying memory.
6
7 Copyright 2021 "Rahul Singh <rsingh@arrsingh.com>"
8
9 Licensed under the Apache License, Version 2.0 (the "License");
10 you may not use this file except in compliance with the License.
11 You may obtain a copy of the License at
12
13 http://www.apache.org/licenses/LICENSE-2.0
14
15 Unless required by applicable law or agreed to in writing, software
16 distributed under the License is distributed on an "AS IS" BASIS,
17 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 See the License for the specific language governing permissions and
19 limitations under the License.
20*/
21
22use crate::bitvec::{
23 bitops,
24 bitref::{BitRef, BitRefMut},
25 bitslice::BitSlice,
26 bytes,
27 iter::{Iter, IterMut, IterOnes, IterU128, IterU16, IterU32, IterU64, IterU8, IterZeros},
28 traits::{AsMsb0, BitwiseClear, BitwiseClearAssign},
29 BitCount, BitOrder,
30};
31use core::fmt;
32use core::fmt::Debug;
33use core::ops::BitAnd;
34use core::ops::BitAndAssign;
35use core::ops::BitOr;
36use core::ops::BitOrAssign;
37use core::ops::BitXor;
38use core::ops::BitXorAssign;
39use core::ops::Index;
40use core::ops::IndexMut;
41use core::ops::Not;
42use core::ops::Range;
43use core::ops::RangeFrom;
44use core::ops::RangeFull;
45use core::ops::RangeInclusive;
46use core::ops::RangeTo;
47use core::ops::RangeToInclusive;
48
49/// A fast contiguous growable array of bits allocated on the heap
50/// that allows storing and manipulating an arbitrary number of
51/// bits. This collection is backed by a [`Vector<u8>`](https://doc.rust-lang.org/std/vec/struct.Vec.html) which
52/// manages the underlying memory.
53///
54/// # Getting Started
55/// To get started add the deepmesa dependency to Cargo.toml and the
56/// use declaration in your source.
57///
58/// ```text
59/// [dependencies]
60/// deepmesa = "0.6.0"
61/// ```
62///
63/// ```
64/// use deepmesa_collections::BitVector;
65///
66/// let mut bv = BitVector::with_capacity(128);
67/// bv.push(true);
68/// bv.push(false);
69/// bv.push(true);
70///
71/// assert_eq!(bv.get(0), Some(true));
72/// assert_eq!(bv.get(1), Some(false));
73/// assert_eq!(bv.get(2), Some(true));
74/// ```
75///
76/// In addition to the [`new()`](#method.new) and
77/// [`with_capacity()`](#method.with_capacity) methods, the
78/// [`bitvector!`](macro.bitvector.html) macro is also provided for convenient
79/// initialization.
80///
81/// # Examples
82/// ```
83/// use deepmesa_collections::BitVector;
84/// use deepmesa_collections::bitvector;
85///
86/// let bv = bitvector![0,1,1,0];
87/// assert_eq!(bv.len(), 4);
88/// ```
89///
90/// # Memory Management
91///
92/// Memory is managed by an underlying [`Vec<u8>`](https://doc.rust-lang.org/std/vec/struct.Vec.html) and all
93/// methods operate on bytes whenever possible for
94/// efficiency. Internally the BitVector maintains a count of the
95/// number of bits currently held by the BitVector and the actual
96/// number of bytes stored maybe greater than eight times the number
97/// of bits. All bits stored past the number of active bits are zeroed
98/// out but this is not guaranteed to be true in future versions of
99/// the BitVector and should be relied up for correctness.
100///
101/// The BitVector can also return mutable and immutable pointers and
102/// slices to the underlying [`Vec<u8>`](https://doc.rust-lang.org/std/vec/struct.Vec.html). Modifying
103/// the underlying Vector can cause undefined behavior in the
104/// BitVector.
105///
106/// # Slices
107///
108/// Slices are implemented by the [`BitSlice`](BitSlice) which is a
109/// view into a range within the [`BitVector`](BitVector). A BitSlice
110/// is a wrapper around a slice of bytes with the 4 most significant
111/// bits of the slice length used to store the bit offset into the
112/// first byte of the slice. The rest of the bits of the length are
113/// used to store the length of the slice in bits.
114///
115/// Here is an illustrative example for BitVector with 16 bits:
116///
117/// ```text
118/// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
119/// bitvec: [ 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1 ]
120/// slice start = 10 len = 6 ^ ^
121/// byte = 10/8 = 1 , offset = 10 % 8 = 2
122/// offset bits = 0010
123/// Slice pointer: 0011_0000 [ 48 bits ] 0000_0110
124/// ```
125///
126/// The MSB of the offset is unused and must be always set to zero
127/// because there is a
128/// [constraint](https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html#safety)
129/// that the length must be no greater than [`isize::MAX`] and hence
130/// cannot use more than 63 bits.
131///
132pub struct BitVector {
133 pub(super) bits: Vec<u8>,
134 pub(super) capacity_bits: usize,
135 pub(super) bit_len: usize,
136}
137
138//Set the bits after bit_len in the last byte to 0
139macro_rules! clr_lsb_last_byte {
140 ($self: ident) => {
141 ($self.bits[($self.bit_len - 1) / 8]).clear_lsb_assign((7 - ($self.bit_len - 1) % 8) as u8)
142 };
143}
144
145macro_rules! iter_unsigned {
146 (
147 $(#[$outer:meta])*
148 $iter_fn: ident, $iter_type: ident
149 ) => {
150 $(#[$outer])*
151 pub fn $iter_fn(&self) -> $iter_type {
152 $iter_type::new(&self.bits, 0, self.bit_len)
153 }
154 };
155}
156
157macro_rules! check_push_bounds {
158 ($t: ty, $sz:literal, $bit_count: expr) => {
159 if $bit_count > $sz {
160 panic!(
161 concat!(
162 "cannot push more than ",
163 $sz,
164 " bits from a ",
165 stringify!($t),
166 ". bit_count={}"
167 ),
168 $bit_count
169 );
170 }
171 };
172}
173
174macro_rules! push_bits_unsigned {
175 (
176 $(#[$outer:meta])*
177 $i:ident, $sz: literal, $push_bits_fn: ident
178 ) => {
179 $(#[$outer])*
180 pub fn $push_bits_fn(&mut self, val: $i, bit_count: BitCount, order: BitOrder) -> BitCount {
181 if bit_count == 0 {
182 return 0;
183 }
184
185 check_push_bounds!($i, $sz, bit_count);
186
187 match order {
188 BitOrder::Msb0 => self.push_bits_msb0((val as u128).as_msb0($sz), bit_count),
189 BitOrder::Lsb0 => {
190 self.push_bits_msb0((val as u128).as_msb0(bit_count), bit_count)
191 }
192 }
193 }
194 };
195}
196
197macro_rules! push_unsigned {
198 (
199 $(#[$outer:meta])*
200 $i:ident, $b: literal, $push_fn: ident
201 ) => {
202 $(#[$outer])*
203 pub fn $push_fn(&mut self, val: $i, min_width: Option<BitCount>) -> BitCount {
204 let mut count = $b - val.leading_zeros() as usize;
205 match min_width {
206 None => {}
207 Some(width) => {
208 if width > count {
209 if width > $b {
210 self.fill(false, width - $b);
211 //fill with zeros (width - $b)
212 count = $b;
213 //bits = $b
214 } else {
215 //implicit: if width <= $b
216 count = width;
217 //bits = width
218 }
219 }
220 }
221 }
222
223 self.push_bits_msb0((val as u128).as_msb0(count), count)
224 }
225 };
226}
227
228macro_rules! read_unsigned {
229 (
230 $(#[$outer:meta])*
231 $i:ident, $max_bits: literal, $read_fn: ident
232 ) => {
233 $(#[$outer])*
234 pub fn $read_fn(&self, start: usize) -> ($i, BitCount) {
235 start_bounds_check!(start, self.bit_len);
236 let (val, bit_count) = bytes::read_bits(&self.bits, start, self.bit_len, $max_bits, BitOrder::Lsb0);
237 (val as $i, bit_count)
238 }
239 };
240}
241
242macro_rules! read_bits_unsigned {
243 (
244 $(#[$outer:meta])*
245 $i:ident, $max_bits: literal, $read_bits_fn: ident
246 ) => {
247 $(#[$outer])*
248 pub fn $read_bits_fn(&self, start: usize, max_bits: BitCount) -> ($i, BitCount) {
249 start_bounds_check!(start, self.bit_len);
250
251 if max_bits > $max_bits {
252 panic!(
253 "cannot read more than $b bits into a $i. max_bits={}",
254 max_bits
255 );
256 }
257
258 match max_bits {
259 0=> (0,0),
260 _ => {
261 let (val, bit_count) =
262 bytes::read_bits(&self.bits, start, self.bit_len, max_bits, BitOrder::Lsb0);
263 (val as $i, bit_count)
264 }
265 }
266 }
267 };
268}
269
270const U128_BITS: u8 = 128;
271
272impl BitVector {
273 /// Creates an empty BitVector with a capacity or 128 bits.
274 ///
275 /// # Examples
276 /// ```
277 /// use deepmesa_collections::BitVector;
278 /// let bv = BitVector::new();
279 /// assert_eq!(bv.capacity(), 128);
280 /// ```
281 pub fn new() -> BitVector {
282 BitVector::with_capacity(128)
283 }
284
285 /// Creates an empty BitVector with the specified capacity. If the
286 /// specified capacity is not a multiple of 8, it is increased to
287 /// be a multiple of 8
288 ///
289 /// # Examples
290 /// ```
291 /// use deepmesa_collections::BitVector;
292 /// let bv = BitVector::with_capacity(6);
293 /// assert_eq!(bv.capacity(), 8);
294 /// ```
295 pub fn with_capacity(capacity_bits: usize) -> BitVector {
296 BitVector {
297 bits: Vec::with_capacity((capacity_bits + 7) / 8),
298 capacity_bits: ((capacity_bits + 7) / 8) * 8,
299 bit_len: 0,
300 }
301 }
302 /// Returns the number of bits this BitVector can hold before new
303 /// memory is allocated.
304 ///
305 /// # Examples
306 /// ```
307 /// use deepmesa_collections::BitVector;
308 /// let bv = BitVector::with_capacity(22);
309 /// assert_eq!(bv.capacity(), 24);
310 /// ```
311 pub fn capacity(&self) -> usize {
312 self.capacity_bits
313 }
314
315 /// Returns the number of bits in the [`BitVector`](BitVector)
316 ///
317 /// # Examples
318 /// ```
319 /// use deepmesa_collections::BitVector;
320 /// let mut bv = BitVector::with_capacity(22);
321 /// for _ in 0..5 {
322 /// bv.push(true);
323 /// }
324 /// assert_eq!(bv.len(), 5);
325 /// ```
326 pub fn len(&self) -> usize {
327 self.bit_len
328 }
329
330 /// Returns true if the [`BitVector`](BitVector) contains no bits.
331 ///
332 /// # Examples
333 /// ```
334 /// use deepmesa_collections::BitVector;
335 /// let mut bv = BitVector::with_capacity(22);
336 /// assert!(bv.is_empty());
337 /// bv.push(true);
338 /// assert!(!bv.is_empty());
339 /// ```
340 pub fn is_empty(&self) -> bool {
341 self.bit_len == 0
342 }
343
344 /// Clears the [`BitVector`](BitVector), removing all the
345 /// bits. This method has no effect on the allocated capacity of
346 /// the [`BitVector`](BitVector).
347 ///
348 /// # Examples
349 /// ```
350 /// use deepmesa_collections::BitVector;
351 /// let mut bv = BitVector::with_capacity(22);
352 /// for _ in 0..5 {
353 /// bv.push(true);
354 /// }
355 /// assert_eq!(bv.len(), 5);
356 /// bv.clear();
357 /// assert_eq!(bv.len(), 0);
358 /// ```
359 pub fn clear(&mut self) {
360 self.bits.clear();
361 self.bit_len = 0;
362 }
363
364 pub fn truncate(&mut self, len: usize) {
365 if len == 0 {
366 self.clear();
367 return;
368 }
369 if len >= self.bit_len {
370 return;
371 }
372 self.bits.truncate(((len - 1) / 8) + 1);
373 self.bit_len = len;
374 clr_lsb_last_byte!(self)
375 }
376
377 /// Returns an iterator over the bits of this
378 /// [`BitVector`](BitVector)
379 ///
380 /// # Examples
381 /// ```
382 /// use deepmesa_collections::BitVector;
383 ///
384 /// let mut bv = BitVector::new();
385 /// bv.push_u8(0b101, None);
386 ///
387 /// let mut iter = bv.iter();
388 /// assert_eq!(iter.next(), Some(true));
389 /// assert_eq!(iter.next(), Some(false));
390 /// assert_eq!(iter.next(), Some(true));
391 /// assert_eq!(iter.next(), None);
392 /// ```
393 pub fn iter(&self) -> Iter {
394 Iter::new(&self.bits, 0, self.bit_len)
395 }
396
397 /// Returns a mutable iterator that allows modifyingthe bits of
398 /// this [`BitVector`](BitVector)
399 ///
400 /// # Examples
401 /// ```
402 /// use deepmesa_collections::BitVector;
403 ///
404 /// let mut bv = BitVector::with_capacity(20);
405 /// bv.push_u8(0b1011_1100, Some(8));
406 /// bv.push_u8(0b0011_1001, Some(8));
407 /// let iter = bv.iter_mut();
408 /// for mut bit in iter {
409 /// *bit = true;
410 /// }
411 /// assert_eq!(bv.read_u16(0), (0b1111_1111_1111_1111, 16));
412 /// ```
413 pub fn iter_mut(&mut self) -> IterMut {
414 let len = self.len();
415 IterMut::new(&mut self.bits, 0, len)
416 }
417
418 /// Counts the number of bits from the specified `start` index to
419 /// the first bit set to `0`. Panics if start is non-zero and
420 /// greater than or equal to the length of the `BitVector`.
421 ///
422 /// Returns `0` if the `BitVector` is empty.
423 ///
424 /// # Examples
425 /// ```
426 /// use deepmesa_collections::BitVector;
427 ///
428 /// let mut bv = BitVector::with_capacity(20);
429 /// assert_eq!(bv.leading_ones(0), 0);
430 ///
431 /// bv.push_u8(0b1111_1000, Some(8));
432 /// bv.push_u8(0b0011_1101, Some(8));
433 ///
434 /// assert_eq!(bv.leading_ones(0), 5);
435 /// assert_eq!(bv.leading_ones(8), 0);
436 /// assert_eq!(bv.leading_ones(10), 4);
437 /// ```
438 pub fn leading_ones(&self, start: usize) -> usize {
439 match self.bit_len {
440 0 => 0,
441 _ => {
442 start_bounds_check!(start, self.bit_len);
443 bytes::leading_ones(&self.bits, start, self.bit_len)
444 }
445 }
446 }
447
448 /// Counts the number of bits from the specified `start` index to
449 /// the first bit set to `1`. Panics if start is non-zero and
450 /// greater than or equal to the length of the `BitVector`.
451 ///
452 /// Returns `0` if the `BitVector` is empty.
453 ///
454 /// # Examples
455 /// ```
456 /// use deepmesa_collections::BitVector;
457 ///
458 /// let mut bv = BitVector::with_capacity(20);
459 /// assert_eq!(bv.leading_zeros(0), 0);
460 ///
461 /// bv.push_u8(0b0000_0111, Some(8));
462 /// bv.push_u8(0b1100_0010, Some(8));
463 ///
464 /// assert_eq!(bv.leading_zeros(0), 5);
465 /// assert_eq!(bv.leading_zeros(8), 0);
466 /// assert_eq!(bv.leading_zeros(10), 4);
467 /// ```
468 pub fn leading_zeros(&self, start: usize) -> usize {
469 match self.bit_len {
470 0 => 0,
471 _ => {
472 start_bounds_check!(start, self.bit_len);
473 bytes::leading_zeros(&self.bits, start, self.bit_len)
474 }
475 }
476 }
477
478 /// Counts the number of bits from end of the BitVector to the
479 /// specified `start` index or to the first bit set to `0`
480 /// whichever is smaller. Panics if start is non-zero and greater
481 /// than or equal to the length of the `BitVector`.
482 ///
483 /// Returns `0` if the `BitVector` is empty.
484 ///
485 /// # Examples
486 /// ```
487 /// use deepmesa_collections::BitVector;
488 ///
489 /// let mut bv = BitVector::with_capacity(20);
490 /// assert_eq!(bv.trailing_ones(0), 0);
491 ///
492 /// bv.push_u8(0b1111_1000, Some(8));
493 /// bv.push_u8(0b0011_1111, Some(8));
494 ///
495 /// assert_eq!(bv.trailing_ones(0), 6);
496 /// assert_eq!(bv.trailing_ones(8), 6);
497 /// assert_eq!(bv.leading_ones(12), 4);
498 /// ```
499 pub fn trailing_ones(&self, start: usize) -> usize {
500 match self.bit_len {
501 0 => 0,
502 _ => {
503 start_bounds_check!(start, self.bit_len);
504 bytes::trailing_ones(&self.bits, start, self.bit_len)
505 }
506 }
507 }
508
509 /// Counts the number of bits from end of the BitVector to the
510 /// specified `start` index or to the first bit set to `1`
511 /// whichever is smaller. Panics if start is non-zero and greater
512 /// than or equal to the length of the `BitVector`.
513 ///
514 /// Returns `0` if the `BitVector` is empty.
515 ///
516 /// # Examples
517 /// ```
518 /// use deepmesa_collections::BitVector;
519 ///
520 /// let mut bv = BitVector::with_capacity(20);
521 /// assert_eq!(bv.trailing_zeros(0), 0);
522 ///
523 /// bv.push_u8(0b1111_1000, Some(8));
524 /// bv.push_u8(0b1100_0000, Some(8));
525 ///
526 /// assert_eq!(bv.trailing_zeros(0), 6);
527 /// //assert_eq!(bv.trailing_zeros(8), 6);
528 /// //assert_eq!(bv.trailing_zeros(12), 4);
529 /// ```
530 pub fn trailing_zeros(&self, start: usize) -> usize {
531 match self.bit_len {
532 0 => 0,
533 _ => {
534 start_bounds_check!(start, self.bit_len);
535 bytes::trailing_zeros(&self.bits, start, self.bit_len)
536 }
537 }
538 }
539
540 /// Counts the number of bits from the specified `start` that are
541 /// set to `1` in the BitVector. Panics if start is non-zero and
542 /// greater than or equal to the length of the `BitVector`.
543 ///
544 /// Returns `0` if the `BitVector` is empty.
545 ///
546 /// # Examples
547 /// ```
548 /// use deepmesa_collections::BitVector;
549 ///
550 /// let mut bv = BitVector::with_capacity(20);
551 /// assert_eq!(bv.count_ones(0), 0);
552 ///
553 /// bv.push_u8(0b1111_1000, Some(8));
554 /// bv.push_u8(0b1100_0000, Some(8));
555 ///
556 /// assert_eq!(bv.count_ones(0), 7);
557 /// assert_eq!(bv.count_ones(8), 2);
558 /// assert_eq!(bv.count_ones(12), 0);
559 /// ```
560 pub fn count_ones(&self, start: usize) -> usize {
561 match self.bit_len {
562 0 => 0,
563 _ => {
564 start_bounds_check!(start, self.bit_len);
565 bytes::count_ones(&self.bits, start, self.bit_len)
566 }
567 }
568 }
569
570 /// Counts the number of bits from the specified `start` that are
571 /// set to `0` in the BitVector. Panics if start is non-zero and
572 /// greater than or equal to the length of the `BitVector`.
573 ///
574 /// Returns `0` if the `BitVector` is empty.
575 ///
576 /// # Examples
577 /// ```
578 /// use deepmesa_collections::BitVector;
579 ///
580 /// let mut bv = BitVector::with_capacity(20);
581 /// assert_eq!(bv.count_zeros(0), 0);
582 ///
583 /// bv.push_u8(0b1111_1000, Some(8));
584 /// bv.push_u8(0b0000_1111, Some(8));
585 ///
586 /// assert_eq!(bv.count_zeros(0), 7);
587 /// assert_eq!(bv.count_zeros(8), 4);
588 /// assert_eq!(bv.count_zeros(12), 0);
589 /// ```
590 pub fn count_zeros(&self, start: usize) -> usize {
591 match self.bit_len {
592 0 => 0,
593 _ => {
594 start_bounds_check!(start, self.bit_len);
595 bytes::count_zeros(&self.bits, start, self.bit_len)
596 }
597 }
598 }
599
600 /// Returns the index of the first bit after the specified `start`
601 /// that is set to `0`. Returns `None` if the `BitVector` is empty
602 /// or if there are no zero bits.
603 ///
604 /// # Examples
605 /// ```
606 /// use deepmesa_collections::BitVector;
607 ///
608 /// let mut bv = BitVector::with_capacity(20);
609 /// assert_eq!(bv.first_zero(0), None);
610 ///
611 /// bv.push_u8(0b1111_1000, Some(8));
612 /// bv.push_u8(0b0000_1011, Some(8));
613 ///
614 /// assert_eq!(bv.first_zero(0), Some(5));
615 /// assert_eq!(bv.first_zero(8), Some(8));
616 /// assert_eq!(bv.first_zero(12), Some(13));
617 /// assert_eq!(bv.first_zero(14), None);
618 /// ```
619 pub fn first_zero(&self, start: usize) -> Option<usize> {
620 match self.bit_len {
621 0 => None,
622 _ => {
623 start_bounds_check!(start, self.bit_len);
624 bytes::first_zero(&self.bits, start, self.bit_len)
625 }
626 }
627 }
628
629 /// Returns the index of the first bit after the specified `start`
630 /// that is set to `1`. Returns `None` if the `BitVector` is empty
631 /// or if there are no one bits.
632 ///
633 /// # Examples
634 /// ```
635 /// use deepmesa_collections::BitVector;
636 ///
637 /// let mut bv = BitVector::with_capacity(20);
638 /// assert_eq!(bv.first_one(0), None);
639 ///
640 /// bv.push_u8(0b0000_0111, Some(8));
641 /// bv.push_u8(0b1111_0100, Some(8));
642 ///
643 /// assert_eq!(bv.first_one(0), Some(5));
644 /// assert_eq!(bv.first_one(8), Some(8));
645 /// assert_eq!(bv.first_one(12), Some(13));
646 /// assert_eq!(bv.first_one(14), None);
647 /// ```
648 pub fn first_one(&self, start: usize) -> Option<usize> {
649 match self.bit_len {
650 0 => None,
651 _ => {
652 start_bounds_check!(start, self.bit_len);
653 bytes::first_one(&self.bits, start, self.bit_len)
654 }
655 }
656 }
657
658 /// Returns the index of the last bit set to `0` after the
659 /// specified `start`. Returns `None` if the `BitVector` is empty
660 /// or if there are no zero bits.
661 ///
662 /// # Examples
663 /// ```
664 /// use deepmesa_collections::BitVector;
665 ///
666 /// let mut bv = BitVector::with_capacity(20);
667 /// assert_eq!(bv.last_zero(0), None);
668 ///
669 /// bv.push_u8(0b1101_1011, Some(8));
670 ///
671 /// assert_eq!(bv.last_zero(0), Some(5));
672 /// assert_eq!(bv.last_zero(6), None);
673 /// ```
674 pub fn last_zero(&self, start: usize) -> Option<usize> {
675 match self.bit_len {
676 0 => None,
677 _ => {
678 start_bounds_check!(start, self.bit_len);
679 bytes::last_zero(&self.bits, start, self.bit_len)
680 }
681 }
682 }
683
684 /// Returns the index of the last bit set to `1` after the
685 /// specified `start`. Returns `None` if the `BitVector` is empty
686 /// or if there are no one bits.
687 ///
688 /// # Examples
689 /// ```
690 /// use deepmesa_collections::BitVector;
691 ///
692 /// let mut bv = BitVector::with_capacity(20);
693 /// assert_eq!(bv.last_one(0), None);
694 ///
695 /// bv.push_u8(0b0010_0100, Some(8));
696 ///
697 /// assert_eq!(bv.last_one(0), Some(5));
698 /// assert_eq!(bv.last_one(6), None);
699 /// ```
700 pub fn last_one(&self, start: usize) -> Option<usize> {
701 match self.bit_len {
702 0 => None,
703 _ => {
704 start_bounds_check!(start, self.bit_len);
705 bytes::last_one(&self.bits, start, self.bit_len)
706 }
707 }
708 }
709
710 /// Returns an immutable reference to the first bit in the
711 /// `BitVector` or None if the `BitVector` is empty.
712 ///
713 /// # Examples
714 /// ```
715 /// use deepmesa_collections::BitVector;
716 ///
717 /// let mut bv = BitVector::with_capacity(20);
718 /// assert_eq!(bv.first(), None);
719 ///
720 /// bv.push_u8(0b0010_0100, Some(8));
721 ///
722 /// assert_eq!(bv.first().as_deref(), Some(&false));
723 /// ```
724 pub fn first(&self) -> Option<BitRef<bool>> {
725 match self.bit_len {
726 0 => None,
727 _ => {
728 let bit = bit_at_unchecked!(0, self.bits);
729 Some(BitRef::<bool>::new(bit))
730 }
731 }
732 }
733
734 /// Returns a mutable reference to the first bit in the
735 /// `BitVector` or None if the `BitVector` is empty.
736 ///
737 /// # Examples
738 /// ```
739 /// use deepmesa_collections::BitVector;
740 ///
741 /// let mut bv = BitVector::with_capacity(20);
742 /// assert_eq!(bv.first(), None);
743 ///
744 /// bv.push_u8(0b0010_0100, Some(8));
745 ///
746 /// assert_eq!(bv.first_mut().as_deref(), Some(&false));
747 /// *bv.first_mut().unwrap() = true;
748 /// assert_eq!(bv.first_mut().as_deref(), Some(&true));
749 /// ```
750 pub fn first_mut(&mut self) -> Option<BitRefMut<bool>> {
751 match self.bit_len {
752 0 => None,
753 _ => {
754 let bit = bit_at_unchecked!(0, self.bits);
755
756 let byte_ptr = self.bits[0..0].as_mut_ptr();
757 return Some(BitRefMut::<bool>::new(bit, byte_ptr, 0));
758 }
759 }
760 }
761
762 /// Returns an immutable reference to the last bit in the
763 /// `BitVector` or None if the `BitVector` is empty.
764 ///
765 /// # Examples
766 /// ```
767 /// use deepmesa_collections::BitVector;
768 ///
769 /// let mut bv = BitVector::with_capacity(20);
770 /// assert_eq!(bv.last(), None);
771 ///
772 /// bv.push_u8(0b0010_0101, Some(8));
773 ///
774 /// assert_eq!(bv.last().as_deref(), Some(&true));
775 /// ```
776 pub fn last(&self) -> Option<BitRef<bool>> {
777 match self.bit_len {
778 0 => None,
779 _ => {
780 let bit = bit_at_unchecked!(self.bit_len - 1, self.bits);
781 Some(BitRef::<bool>::new(bit))
782 }
783 }
784 }
785
786 /// Returns a mutable reference to the last bit in the
787 /// `BitVector` or None if the `BitVector` is empty.
788 ///
789 /// # Examples
790 /// ```
791 /// use deepmesa_collections::BitVector;
792 ///
793 /// let mut bv = BitVector::with_capacity(20);
794 /// assert_eq!(bv.first(), None);
795 ///
796 /// bv.push_u8(0b0010_0101, Some(8));
797 ///
798 /// assert_eq!(bv.last_mut().as_deref(), Some(&true));
799 /// *bv.last_mut().unwrap() = false;
800 /// assert_eq!(bv.last_mut().as_deref(), Some(&false));
801 /// ```
802 pub fn last_mut(&mut self) -> Option<BitRefMut<bool>> {
803 match self.bit_len {
804 0 => None,
805 _ => {
806 let bit_idx = self.len() - 1;
807 let bit = bit_at_unchecked!(bit_idx, self.bits);
808
809 let byte_idx = bit_idx / 8;
810 let byte_ptr = self.bits[byte_idx..byte_idx].as_mut_ptr();
811 return Some(BitRefMut::<bool>::new(bit, byte_ptr, bit_idx));
812 }
813 }
814 }
815
816 /// Iterates over all the bits in the `BitVector` that are set to
817 /// `1`.
818 ///
819 /// # Examples
820 /// ```
821 /// use deepmesa_collections::BitVector;
822 ///
823 /// let mut bv = BitVector::with_capacity(20);
824 /// bv.push_u8(0b0010_0101, Some(8));
825 ///
826 /// let mut iter = bv.iter_ones();
827 /// assert_eq!(iter.next(), Some(2));
828 /// assert_eq!(iter.next(), Some(5));
829 /// assert_eq!(iter.next(), Some(7));
830 /// assert_eq!(iter.next(), None);
831 /// ```
832 pub fn iter_ones(&self) -> IterOnes {
833 IterOnes::new(&self.bits, 0, self.bit_len)
834 }
835
836 /// Iterates over all the bits in the `BitVector` that are set to
837 /// `0`.
838 ///
839 /// # Examples
840 /// ```
841 /// use deepmesa_collections::BitVector;
842 ///
843 /// let mut bv = BitVector::with_capacity(20);
844 /// bv.push_u8(0b1101_1010, Some(8));
845 ///
846 /// let mut iter = bv.iter_zeros();
847 /// assert_eq!(iter.next(), Some(2));
848 /// assert_eq!(iter.next(), Some(5));
849 /// assert_eq!(iter.next(), Some(7));
850 /// assert_eq!(iter.next(), None);
851 /// ```
852 pub fn iter_zeros(&self) -> IterZeros {
853 IterZeros::new(&self.bits, 0, self.bit_len)
854 }
855
856 iter_unsigned!(
857 /// Returns an iterator that iterates over the
858 /// [`BitVector`](BitVector) 8 bits at a time. Each invocation
859 /// of `iter.next` returns a [`u8`] value and the number of bits
860 /// read.
861 ///
862 /// The bits are read from the lower to the higher index from
863 /// the BitVector and shifted right, so the bit at the lower
864 /// index is the MSB of returned value while the bit at the
865 /// highest index is the LSB.
866 ///
867 /// The iterator returns None if there are no more bits to
868 /// return
869 ///
870 /// # Examples
871 /// ```
872 /// use deepmesa_collections::BitVector;
873 /// let mut bv = BitVector::new();
874 /// bv.push_u16(0b0101_1101_0011_1010, Some(16));
875 ///
876 /// let mut iter = bv.iter_u8();
877 /// assert_eq!(iter.next(), Some((0b0101_1101, 8)));
878 /// assert_eq!(iter.next(), Some((0b0011_1010, 8)));
879 /// assert_eq!(iter.next(), None);
880 /// ```
881 iter_u8,
882 IterU8
883 );
884 iter_unsigned!(
885 /// Returns an iterator that iterates over the bitvector 16
886 /// bits at a time. Each invocation of `iter.next` returns a
887 /// [`u16`] value and the number of bits read.
888 ///
889 /// The bits are read from the lower to the higher index from
890 /// the BitVector and shifted right, so the bit at the lower
891 /// index is the MSB of returned value while the bit at the
892 /// highest index is the LSB.
893 ///
894 /// The iterator returns None if there are no more bits to
895 /// return
896 ///
897 /// # Examples
898 /// ```
899 /// use deepmesa_collections::BitVector;
900 /// let mut bv = BitVector::new();
901 /// bv.push_u16(0b0101_1101_0011_1010, Some(16));
902 ///
903 /// let mut iter = bv.iter_u16();
904 /// assert_eq!(iter.next(), Some((0b0101_1101_0011_1010, 16)));
905 /// assert_eq!(iter.next(), None);
906 /// ```
907 iter_u16,
908 IterU16
909 );
910 iter_unsigned!(
911 /// Returns an iterator that iterates over the bitvector 32
912 /// bits at a time. Each invocation of `iter.next` returns a
913 /// [`u32`] value and the number of bits read.
914 ///
915 /// The bits are read from the lower to the higher index from
916 /// the BitVector and shifted right, so the bit at the lower
917 /// index is the MSB of returned value while the bit at the
918 /// highest index is the LSB.
919 ///
920 /// The iterator returns None if there are no more bits to
921 /// return
922 ///
923 /// # Examples
924 /// ```
925 /// use deepmesa_collections::BitVector;
926 /// let mut bv = BitVector::new();
927 /// bv.push_u16(0b0101_1101_0011_1010, Some(16));
928 /// bv.push_u16(0b1111_0011_1100_0000, Some(16));
929 ///
930 /// let mut iter = bv.iter_u32();
931 /// assert_eq!(iter.next(), Some((0b0101_1101_0011_1010_1111_0011_1100_0000, 32)));
932 /// assert_eq!(iter.next(), None);
933 /// ```
934 iter_u32,
935 IterU32
936 );
937 iter_unsigned!(
938 /// Returns an iterator that iterates over the bitvector 64
939 /// bits at a time. Each invocation of `iter.next` returns a
940 /// [`u64`] value and the number of bits read.
941 ///
942 /// The bits are read from the lower to the higher index from
943 /// the BitVector and shifted right, so the bit at the lower
944 /// index is the MSB of returned value while the bit at the
945 /// highest index is the LSB.
946 ///
947 /// The iterator returns None if there are no more bits to
948 /// return
949 ///
950 /// # Examples
951 /// ```
952 /// use deepmesa_collections::BitVector;
953 /// let mut bv = BitVector::new();
954 /// bv.push_u64(u64::MAX, Some(64));
955 ///
956 /// let mut iter = bv.iter_u64();
957 /// assert_eq!(iter.next(), Some((u64::MAX, 64)));
958 /// assert_eq!(iter.next(), None);
959 /// ```
960 iter_u64,
961 IterU64
962 );
963 iter_unsigned!(
964 /// Returns an iterator that iterates over the bitvector 128
965 /// bits at a time. Each invocation of `iter.next` returns a
966 /// [`u128`] value and the number of bits read.
967 ///
968 /// The bits are read from the lower to the higher index from
969 /// the BitVector and shifted right, so the bit at the lower
970 /// index is the MSB of returned value while the bit at the
971 /// highest index is the LSB.
972 ///
973 /// The iterator returns None if there are no more bits to
974 /// return
975 ///
976 /// # Examples
977 /// ```
978 /// use deepmesa_collections::BitVector;
979 /// let mut bv = BitVector::new();
980 /// bv.push_u64(u64::MAX, Some(64));
981 /// bv.push_u64(u64::MAX, Some(64));
982 ///
983 /// let mut iter = bv.iter_u128();
984 /// assert_eq!(iter.next(), Some((u128::MAX, 128)));
985 /// assert_eq!(iter.next(), None);
986 /// ```
987 iter_u128,
988 IterU128
989 );
990
991 read_unsigned!(
992 /// Reads upto 8 bits from this [`BitVector`](BitVector) into
993 /// a [`u8`] starting at the specified `start` position. This
994 /// method will panic if `start` is greater than or equal to
995 /// the length of the BitVector.
996 ///
997 /// The bits are read from the lower to the higher index from
998 /// the BitVector and shifted right, so the bit at the lower
999 /// index is the MSB of returned value while the bit at the
1000 /// highest index is the LSB.
1001 ///
1002 /// # Examples
1003 /// ```
1004 /// use deepmesa_collections::BitVector;
1005 /// let mut bv = BitVector::new();
1006 /// bv.push_u8(0b0011_0110, Some(8));
1007 ///
1008 /// let (val, read) = bv.read_u8(0);
1009 /// assert_eq!(read, 8);
1010 /// assert_eq!(val, 0b0011_0110);
1011 ///
1012 /// let (val, read) = bv.read_u8(4);
1013 /// assert_eq!(read, 4);
1014 /// assert_eq!(val, 0b0000_0110);
1015 /// ```
1016 u8,
1017 8,
1018 read_u8
1019 );
1020 read_unsigned!(
1021 /// Reads upto 16 bits from this [`BitVector`](BitVector) into
1022 /// a [`u16`] starting at the specified `start` position. This
1023 /// method will panic if `start` is greater than or equal to
1024 /// the length of the BitVector.
1025 ///
1026 /// The bits are read from the lower to the higher index from
1027 /// the BitVector and shifted right, so the bit at the lower
1028 /// index is the MSB of returned value while the bit at the
1029 /// highest index is the LSB.
1030 ///
1031 /// # Examples
1032 /// ```
1033 /// use deepmesa_collections::BitVector;
1034 /// let mut bv = BitVector::new();
1035 /// bv.push_u16(0b0011_0110_1100_0011, Some(16));
1036 ///
1037 /// let (val, read) = bv.read_u16(0);
1038 /// assert_eq!(read, 16);
1039 /// assert_eq!(val, 0b0011_0110_1100_0011);
1040 ///
1041 /// let (val, read) = bv.read_u16(4);
1042 /// assert_eq!(read, 12);
1043 /// assert_eq!(val, 0b0000_0110_1100_0011);
1044 /// ```
1045 u16,
1046 16,
1047 read_u16
1048 );
1049 read_unsigned!(
1050 /// Reads upto 32 bits from this [`BitVector`](BitVector) into
1051 /// a [`u32`] starting at the specified `start` position. This
1052 /// method will panic if `start` is greater than or equal to
1053 /// the length of the BitVector.
1054 ///
1055 /// The bits are read from the lower to the higher index from
1056 /// the BitVector and shifted right, so the bit at the lower
1057 /// index is the MSB of returned value while the bit at the
1058 /// highest index is the LSB.
1059 ///
1060 /// # Examples
1061 /// ```
1062 /// use deepmesa_collections::BitVector;
1063 /// let mut bv = BitVector::new();
1064 /// bv.push_u16(0b0011_0110_1100_0011, Some(16));
1065 /// bv.push_u16(0b1100_1010_0100_1100, Some(16));
1066 ///
1067 /// let (val, read) = bv.read_u32(0);
1068 /// assert_eq!(read, 32);
1069 //
1070 /// assert_eq!(val, 0b0011_0110_1100_0011_1100_1010_0100_1100);
1071 ///
1072 /// let (val, read) = bv.read_u16(16);
1073 /// assert_eq!(read, 16);
1074 /// assert_eq!(val, 0b1100_1010_0100_1100);
1075 /// ```
1076 u32,
1077 32,
1078 read_u32
1079 );
1080 read_unsigned!(
1081 /// Reads upto 64 bits from this [`BitVector`](BitVector) into
1082 /// a [`u64`] starting at the specified `start` position. This
1083 /// method will panic if `start` is greater than or equal to
1084 /// the length of the BitVector.
1085 ///
1086 /// The bits are read from the lower to the higher index from
1087 /// the BitVector and shifted right, so the bit at the lower
1088 /// index is the MSB of returned value while the bit at the
1089 /// highest index is the LSB.
1090 ///
1091 /// # Examples
1092 /// ```
1093 /// use deepmesa_collections::BitVector;
1094 /// let mut bv = BitVector::new();
1095 /// bv.push_u16(0b0011_0110_1100_0011, Some(16));
1096 /// bv.push_u16(0b1100_1010_0100_1100, Some(16));
1097 ///
1098 /// let (val, read) = bv.read_u64(20);
1099 /// assert_eq!(read, 12);
1100 //
1101 /// assert_eq!(val, 0b1010_0100_1100);
1102 ///
1103 /// let (val, read) = bv.read_u64(16);
1104 /// assert_eq!(read, 16);
1105 /// assert_eq!(val, 0b1100_1010_0100_1100);
1106 /// ```
1107 u64,
1108 64,
1109 read_u64
1110 );
1111 read_unsigned!(
1112 /// Reads upto 128 bits from this [`BitVector`](BitVector)
1113 /// into a [`u128`] starting at the specified `start`
1114 /// position. This method will panic if `start` is greater
1115 /// than or equal to the length of the BitVector.
1116 ///
1117 /// The bits are read from the lower to the higher index from
1118 /// the BitVector and shifted right, so the bit at the lower
1119 /// index is the MSB of returned value while the bit at the
1120 /// highest index is the LSB.
1121 ///
1122 /// # Examples
1123 /// ```
1124 /// use deepmesa_collections::BitVector;
1125 /// let mut bv = BitVector::new();
1126 /// bv.push_u16(0b0011_0110_1100_0011, Some(16));
1127 /// bv.push_u16(0b1100_1010_0100_1100, Some(16));
1128 ///
1129 /// let (val, read) = bv.read_u128(20);
1130 /// assert_eq!(read, 12);
1131 //
1132 /// assert_eq!(val, 0b1010_0100_1100);
1133 ///
1134 /// let (val, read) = bv.read_u128(16);
1135 /// assert_eq!(read, 16);
1136 /// assert_eq!(val, 0b1100_1010_0100_1100);
1137 /// ```
1138 u128,
1139 128,
1140 read_u128
1141 );
1142
1143 read_bits_unsigned!(
1144 /// Reads upto `max_bits` bits from this
1145 /// [`BitVector`](BitVector) into a [`u8`] starting at the
1146 /// specified `start` position. This method will panic if
1147 /// `max_bits` is greater than 8 or if `start` is greater than
1148 /// or equal to the length of the BitVector.
1149 ///
1150 /// The bits are read from the lower to the higher index from
1151 /// the BitVector and shifted right, so the bit at the lower
1152 /// index is the MSB of returned value while the bit at the
1153 /// highest index is the LSB.
1154 ///
1155 /// Here is an illustrative example for a bitvector with 8
1156 /// bits.
1157 ///
1158 /// ```text
1159 /// 0 1 2 3 4 5 6 7
1160 /// [ 0,0,1,1,0,1,1,0 ]
1161 /// MSB [_______] LSB
1162 /// ^ Start = 2
1163 ///
1164 /// value read = 0b1101
1165 /// ```
1166 /// Reading 4 bits from the start position of 2, results in a
1167 /// u8 value of decimal 13.
1168 ///
1169 /// This method returns the read value as well as the number of
1170 /// bits read as a tuple.
1171 ///
1172 /// # Examples
1173 /// ```
1174 /// use deepmesa_collections::BitVector;
1175 /// let mut bv = BitVector::new();
1176 /// // Push 8 bits: 0b0011_0110
1177 /// bv.push_u8(0b0011_0110, Some(8));
1178 ///
1179 /// let (val, read) = bv.read_bits_u8(2, 4);
1180 /// assert_eq!(read,4);
1181 /// assert_eq!(val, 0b0000_1101);
1182 /// assert_eq!(val, 13);
1183 /// ```
1184 u8,
1185 8,
1186 read_bits_u8
1187 );
1188 read_bits_unsigned!(
1189 /// Reads upto `max_bits` bits from this
1190 /// [`BitVector`](BitVector) into a [`u16`] starting at the
1191 /// specified `start` position. This method will panic if
1192 /// `max_bits` is greater than 16 or if `start` is greater
1193 /// than or equal to the length of the BitVector.
1194 ///
1195 /// The bits are read from the lower to the higher index from
1196 /// the BitVector and shifted right, so the bit at the lower
1197 /// index is the MSB of returned value while the bit at the
1198 /// highest index is the LSB.
1199 ///
1200 /// Here is an illustrative example for a bitvector with 8
1201 /// bits.
1202 ///
1203 /// ```text
1204 /// 0 1 2 3 4 5 6 7
1205 /// [ 0,0,1,1,0,1,1,0 ]
1206 /// MSB [_______] LSB
1207 /// ^ Start = 2
1208 ///
1209 /// value read = 0b1101
1210 /// ```
1211 /// Reading 4 bits from the start position of 2, results in a
1212 /// u16 value of decimal 13.
1213 ///
1214 /// This method returns the read value as well as the number of
1215 /// bits read as a tuple.
1216 ///
1217 /// # Examples
1218 /// ```
1219 /// use deepmesa_collections::BitVector;
1220 /// let mut bv = BitVector::new();
1221 /// // Push 8 bits: 0b0011_0110
1222 /// bv.push_u8(0b0011_0110, Some(8));
1223 ///
1224 /// let (val, read) = bv.read_bits_u16(2, 4);
1225 /// assert_eq!(read,4);
1226 /// assert_eq!(val, 0b0000_1101);
1227 /// assert_eq!(val, 13);
1228 /// ```
1229 u16,
1230 16,
1231 read_bits_u16
1232 );
1233
1234 read_bits_unsigned!(
1235 /// Reads upto `max_bits` bits from this
1236 /// [`BitVector`](BitVector) into a [`u32`] starting at the
1237 /// specified `start` position. This method will panic if
1238 /// `max_bits` is greater than 32 or if `start` is greater
1239 /// than or equal to the length of the BitVector.
1240 ///
1241 /// The bits are read from the lower to the higher index from
1242 /// the BitVector and shifted right, so the bit at the lower
1243 /// index is the MSB of returned value while the bit at the
1244 /// highest index is the LSB.
1245 ///
1246 /// Here is an illustrative example for a bitvector with 8
1247 /// bits.
1248 ///
1249 /// ```text
1250 /// 0 1 2 3 4 5 6 7
1251 /// [ 0,0,1,1,0,1,1,0 ]
1252 /// MSB [_______] LSB
1253 /// ^ Start = 2
1254 ///
1255 /// value read = 0b1101
1256 /// ```
1257 /// Reading 4 bits from the start position of 2, results in a
1258 /// u32 value of decimal 13.
1259 ///
1260 /// This method returns the read value as well as the number of
1261 /// bits read as a tuple.
1262 ///
1263 /// # Examples
1264 /// ```
1265 /// use deepmesa_collections::BitVector;
1266 /// let mut bv = BitVector::new();
1267 /// // Push 8 bits: 0b0011_0110
1268 /// bv.push_u8(0b0011_0110, Some(8));
1269 ///
1270 /// let (val, read) = bv.read_bits_u32(2, 4);
1271 /// assert_eq!(read,4);
1272 /// assert_eq!(val, 0b0000_1101);
1273 /// assert_eq!(val, 13);
1274 /// ```
1275 u32,
1276 32,
1277 read_bits_u32
1278 );
1279 read_bits_unsigned!(
1280 /// Reads upto `max_bits` bits from this
1281 /// [`BitVector`](BitVector) into a [`u64`] starting at the
1282 /// specified `start` position. This method will panic if
1283 /// `max_bits` is greater than 64 or if `start` is greater
1284 /// than or equal to the length of the BitVector.
1285 ///
1286 /// The bits are read from the lower to the higher index from
1287 /// the BitVector and shifted right, so the bit at the lower
1288 /// index is the MSB of returned value while the bit at the
1289 /// highest index is the LSB.
1290 ///
1291 /// Here is an illustrative example for a bitvector with 8
1292 /// bits.
1293 ///
1294 /// ```text
1295 /// 0 1 2 3 4 5 6 7
1296 /// [ 0,0,1,1,0,1,1,0 ]
1297 /// MSB [_______] LSB
1298 /// ^ Start = 2
1299 ///
1300 /// value read = 0b1101
1301 /// ```
1302 /// Reading 4 bits from the start position of 2, results in a
1303 /// u64 value of decimal 13.
1304 ///
1305 /// This method returns the read value as well as the number of
1306 /// bits read as a tuple.
1307 ///
1308 /// # Examples
1309 /// ```
1310 /// use deepmesa_collections::BitVector;
1311 /// let mut bv = BitVector::new();
1312 /// // Push 8 bits: 0b0011_0110
1313 /// bv.push_u8(0b0011_0110, Some(8));
1314 ///
1315 /// let (val, read) = bv.read_bits_u64(2, 4);
1316 /// assert_eq!(read,4);
1317 /// assert_eq!(val, 0b0000_1101);
1318 /// assert_eq!(val, 13);
1319 /// ```
1320 u64,
1321 64,
1322 read_bits_u64
1323 );
1324 read_bits_unsigned!(
1325 /// Reads upto `max_bits` bits from this
1326 /// [`BitVector`](BitVector) into a [`u128`] starting at the
1327 /// specified `start` position. This method will panic if
1328 /// `max_bits` is greater than 128 or if `start` is greater
1329 /// than or equal to the length of the BitVector.
1330 ///
1331 /// The bits are read from the lower to the higher index from
1332 /// the BitVector and shifted right, so the bit at the lower
1333 /// index is the MSB of returned value while the bit at the
1334 /// highest index is the LSB.
1335 ///
1336 /// Here is an illustrative example for a bitvector with 8
1337 /// bits.
1338 ///
1339 /// ```text
1340 /// 0 1 2 3 4 5 6 7
1341 /// [ 0,0,1,1,0,1,1,0 ]
1342 /// MSB [_______] LSB
1343 /// ^ Start = 2
1344 ///
1345 /// value read = 0b1101
1346 /// ```
1347 /// Reading 4 bits from the start position of 2, results in a
1348 /// u128 value of decimal 13.
1349 ///
1350 /// This method returns the read value as well as the number of
1351 /// bits read as a tuple.
1352 ///
1353 /// # Examples
1354 /// ```
1355 /// use deepmesa_collections::BitVector;
1356 /// let mut bv = BitVector::new();
1357 /// // Push 8 bits: 0b0011_0110
1358 /// bv.push_u8(0b0011_0110, Some(8));
1359 ///
1360 /// let (val, read) = bv.read_bits_u128(2, 4);
1361 /// assert_eq!(read,4);
1362 /// assert_eq!(val, 0b0000_1101);
1363 /// assert_eq!(val, 13);
1364 /// ```
1365 ///
1366 u128,
1367 128,
1368 read_bits_u128
1369 );
1370
1371 push_bits_unsigned!(
1372 /// Pushes at most `count` bits from the specified [`u8`] `val` to
1373 /// the end of the BitVector. The bits to be pushed are
1374 /// counted depending on the `order`. If the `count` is equal
1375 /// to 8 the order is ignored and all bits are pushed from the
1376 /// MSB (bit position 7) to the LSB (bit position 0). If the
1377 /// count is less than 8, then the bits are pushed in the
1378 /// specified Order as follows:
1379 ///
1380 /// If the order is Msb0, the leading `count` bits starting from the
1381 /// MSB (from bit position 7) are pushed to the end of the
1382 /// BitVector
1383 ///
1384 /// If the order is Lsb0, then trailing `count` bits starting from
1385 /// the LSB (from bit position 0) are pushed to the end of the
1386 /// BitVector.
1387 ///
1388 /// This method will panic, if the count is greater than 8. If
1389 /// the `count` is 0, then no bits are pushed and the method
1390 /// has no effect.
1391 ///
1392 /// # Examples
1393 /// ```
1394 /// use deepmesa_collections::BitVector;
1395 /// use deepmesa_collections::bitvec::BitOrder;
1396 ///
1397 /// let mut bv = BitVector::new();
1398 /// let val:u8 = 0b1100_0101;
1399 /// bv.push_bits_u8(val, 3, BitOrder::Msb0);
1400 /// assert_eq!(bv.len(), 3);
1401 /// assert_eq!(bv[0], true);
1402 /// assert_eq!(bv[1], true);
1403 /// assert_eq!(bv[2], false);
1404 ///
1405 /// bv.clear();
1406 /// bv.push_bits_u8(val, 3, BitOrder::Lsb0);
1407 /// assert_eq!(bv.len(), 3);
1408 /// assert_eq!(bv[0], true);
1409 /// assert_eq!(bv[1], false);
1410 /// assert_eq!(bv[2], true);
1411 ///
1412 /// ```
1413 u8,
1414 8,
1415 push_bits_u8
1416 );
1417
1418 push_bits_unsigned!(
1419 /// Pushes at most `count` bits from the specified [`u16`]
1420 /// `val` to the end of the BitVector. The bits to be pushed
1421 /// are counted depending on the `order`. If the `count` is
1422 /// equal to 16 the order is ignored and all bits are pushed
1423 /// from the MSB (bit position 15) to the LSB (bit position
1424 /// 0). If the count is less than 16, then the bits are pushed
1425 /// in the specified Order as follows:
1426 ///
1427 /// If the order is Msb0, the leading `count` bits starting from the
1428 /// MSB (from bit position 15) are pushed to the end of the
1429 /// BitVector
1430 ///
1431 /// If the order is Lsb0, then trailing `count` bits starting from
1432 /// the LSB (from bit position 0) are pushed to the end of the
1433 /// BitVector.
1434 ///
1435 /// This method will panic, if the count is greater than
1436 /// 16. If the `count` is 0, then no bits are pushed and the
1437 /// method has no effect.
1438 ///
1439 /// # Examples
1440 /// ```
1441 /// use deepmesa_collections::BitVector;
1442 /// use deepmesa_collections::bitvec::BitOrder;
1443 ///
1444 /// let mut bv = BitVector::new();
1445 /// let val:u16 = 0b1100_0000_0000_0101;
1446 /// bv.push_bits_u16(val, 3, BitOrder::Msb0);
1447 /// assert_eq!(bv.len(), 3);
1448 /// assert_eq!(bv[0], true);
1449 /// assert_eq!(bv[1], true);
1450 /// assert_eq!(bv[2], false);
1451 ///
1452 /// bv.clear();
1453 /// bv.push_bits_u16(val, 3, BitOrder::Lsb0);
1454 /// assert_eq!(bv.len(), 3);
1455 /// assert_eq!(bv[0], true);
1456 /// assert_eq!(bv[1], false);
1457 /// assert_eq!(bv[2], true);
1458 ///
1459 /// ```
1460 u16,
1461 16,
1462 push_bits_u16
1463 );
1464 push_bits_unsigned!(
1465 /// Pushes at most `count` bits from the specified [`u32`]
1466 /// `val` to the end of the BitVector. The bits to be pushed
1467 /// are counted depending on the `order`. If the `count` is
1468 /// equal to 32 the order is ignored and all bits are pushed
1469 /// from the MSB (bit position 31) to the LSB (bit position
1470 /// 0). If the count is less than 32, then the bits are pushed
1471 /// in the specified Order as follows:
1472 ///
1473 /// If the order is Msb0, the leading `count` bits starting from the
1474 /// MSB (from bit position 31) are pushed to the end of the
1475 /// BitVector
1476 ///
1477 /// If the order is Lsb0, then trailing `count` bits starting from
1478 /// the LSB (from bit position 0) are pushed to the end of the
1479 /// BitVector.
1480 ///
1481 /// This method will panic, if the count is greater than
1482 /// 32. If the `count` is 0, then no bits are pushed and the
1483 /// method has no effect.
1484 ///
1485 /// # Examples
1486 /// ```
1487 /// use deepmesa_collections::BitVector;
1488 /// use deepmesa_collections::bitvec::BitOrder;
1489 ///
1490 /// let mut bv = BitVector::new();
1491 /// let val:u32 = 0b1100_0000_0000_0000_0000_0000_0000_0101;
1492 /// bv.push_bits_u32(val, 3, BitOrder::Msb0);
1493 /// assert_eq!(bv.len(), 3);
1494 /// assert_eq!(bv[0], true);
1495 /// assert_eq!(bv[1], true);
1496 /// assert_eq!(bv[2], false);
1497 ///
1498 /// bv.clear();
1499 /// bv.push_bits_u32(val, 3, BitOrder::Lsb0);
1500 /// assert_eq!(bv.len(), 3);
1501 /// assert_eq!(bv[0], true);
1502 /// assert_eq!(bv[1], false);
1503 /// assert_eq!(bv[2], true);
1504 ///
1505 /// ```
1506 u32,
1507 32,
1508 push_bits_u32
1509 );
1510 push_bits_unsigned!(
1511 /// Pushes at most `count` bits from the specified [`u64`] `val` to
1512 /// the end of the BitVector. The bits to be pushed are
1513 /// counted depending on the `order`. If the `count` is equal
1514 /// to 64 the order is ignored and all bits are pushed from the
1515 /// MSB (bit position 63) to the LSB (bit position 0). If the
1516 /// count is less than 64, then the bits are pushed in the
1517 /// specified Order as follows:
1518 ///
1519 /// If the order is Msb0, the leading `count` bits starting from the
1520 /// MSB (from bit position 63) are pushed to the end of the
1521 /// BitVector
1522 ///
1523 /// If the order is Lsb0, then trailing `count` bits starting from
1524 /// the LSB (from bit position 0) are pushed to the end of the
1525 /// BitVector.
1526 ///
1527 /// This method will panic, if the count is greater than
1528 /// 64. If the `count` is 0, then no bits are pushed and the
1529 /// method has no effect.
1530 ///
1531 /// # Examples
1532 /// ```
1533 /// use deepmesa_collections::BitVector;
1534 /// use deepmesa_collections::bitvec::BitOrder;
1535 ///
1536 /// let mut bv = BitVector::new();
1537 /// // 4 MSB bits are 1100 and 4 LSB bits are 0101
1538 /// let val:u64 = 0xc0_00_00_00_00_00_00_05;
1539 /// bv.push_bits_u64(val, 3, BitOrder::Msb0);
1540 /// assert_eq!(bv.len(), 3);
1541 /// assert_eq!(bv[0], true);
1542 /// assert_eq!(bv[1], true);
1543 /// assert_eq!(bv[2], false);
1544 ///
1545 /// bv.clear();
1546 /// bv.push_bits_u64(val, 3, BitOrder::Lsb0);
1547 /// assert_eq!(bv.len(), 3);
1548 /// assert_eq!(bv[0], true);
1549 /// assert_eq!(bv[1], false);
1550 /// assert_eq!(bv[2], true);
1551 ///
1552 /// ```
1553 u64,
1554 64,
1555 push_bits_u64
1556 );
1557 push_bits_unsigned!(
1558 /// Pushes at most `count` bits from the specified [`u128`]
1559 /// `val` to the end of the BitVector. The bits to be pushed
1560 /// are counted depending on the `order`. If the `count` is
1561 /// equal to 128 the order is ignored and all bits are pushed
1562 /// from the MSB (bit position 127) to the LSB (bit position
1563 /// 0). If the count is less than 128, then the bits are
1564 /// pushed in the specified Order as follows:
1565 ///
1566 /// If the order is Msb0, the leading `count` bits starting from the
1567 /// MSB (from bit position 127) are pushed to the end of the
1568 /// BitVector
1569 ///
1570 /// If the order is Lsb0, then trailing `count` bits starting from
1571 /// the LSB (from bit position 0) are pushed to the end of the
1572 /// BitVector.
1573 ///
1574 /// This method will panic, if the count is greater than
1575 /// 128. If the `count` is 0, then no bits are pushed and the
1576 /// method has no effect.
1577 ///
1578 /// # Examples
1579 /// ```
1580 /// use deepmesa_collections::BitVector;
1581 /// use deepmesa_collections::bitvec::BitOrder;
1582 ///
1583 /// let mut bv = BitVector::new();
1584 /// // 4 MSB bits are 1100 and 4 LSB bits are 0101
1585 /// let val:u128 = 0xc0_00_00_00_00_00_00_00_00_00_00_00_00_00_00_05;
1586 /// bv.push_bits_u128(val, 3, BitOrder::Msb0);
1587 /// assert_eq!(bv.len(), 3);
1588 /// assert_eq!(bv[0], true);
1589 /// assert_eq!(bv[1], true);
1590 /// assert_eq!(bv[2], false);
1591 ///
1592 /// bv.clear();
1593 /// bv.push_bits_u128(val, 3, BitOrder::Lsb0);
1594 /// assert_eq!(bv.len(), 3);
1595 /// assert_eq!(bv[0], true);
1596 /// assert_eq!(bv[1], false);
1597 /// assert_eq!(bv[2], true);
1598 ///
1599 /// ```
1600 u128,
1601 128,
1602 push_bits_u128
1603 );
1604
1605 push_unsigned!(
1606 /// Pushes bits from the specified [`u8`] `val` excluding the
1607 /// leading zeros unless the `min_width` is specified. The
1608 /// `min_width` is the minimum number of bits to push
1609 /// (including leading zeros for padding). If the `min_width`
1610 /// is specified, then leading zeros are pushed before pushing
1611 /// the bits in the u8 to the BitVector.
1612 ///
1613 /// # Examples
1614 /// ```
1615 /// use deepmesa_collections::BitVector;
1616 ///
1617 /// let mut bv = BitVector::new();
1618 /// let val:u8 = 0b101;
1619 /// bv.push_u8(val, None);
1620 /// assert_eq!(bv.len(), 3);
1621 /// assert_eq!(bv[0], true);
1622 /// assert_eq!(bv[1], false);
1623 /// assert_eq!(bv[2], true);
1624 ///
1625 /// bv.clear();
1626 /// bv.push_u8(val, Some(5));
1627 /// assert_eq!(bv.len(), 5);
1628 /// assert_eq!(bv[0], false);
1629 /// assert_eq!(bv[1], false);
1630 /// assert_eq!(bv[2], true);
1631 /// assert_eq!(bv[3], false);
1632 /// assert_eq!(bv[4], true);
1633 /// ```
1634 u8,
1635 8,
1636 push_u8
1637 );
1638 push_unsigned!(
1639 /// Pushes bits from the specified [`u16`] `val` excluding the
1640 /// leading zeros unless the `min_width` is specified. The
1641 /// `min_width` is the minimum number of bits to push
1642 /// (including leading zeros for padding). If the `min_width`
1643 /// is specified, then leading zeros are pushed before pushing
1644 /// the bits in the u16 to the BitVector.
1645 ///
1646 /// # Examples
1647 /// ```
1648 /// use deepmesa_collections::BitVector;
1649 ///
1650 /// let mut bv = BitVector::new();
1651 /// let val:u16 = 0b101;
1652 /// bv.push_u16(val, None);
1653 /// assert_eq!(bv.len(), 3);
1654 /// assert_eq!(bv[0], true);
1655 /// assert_eq!(bv[1], false);
1656 /// assert_eq!(bv[2], true);
1657 ///
1658 /// bv.clear();
1659 /// bv.push_u16(val, Some(5));
1660 /// assert_eq!(bv.len(), 5);
1661 /// assert_eq!(bv[0], false);
1662 /// assert_eq!(bv[1], false);
1663 /// assert_eq!(bv[2], true);
1664 /// assert_eq!(bv[3], false);
1665 /// assert_eq!(bv[4], true);
1666 /// ```
1667 u16,
1668 16,
1669 push_u16
1670 );
1671 push_unsigned!(
1672 /// Pushes bits from the specified [`u32`] `val` excluding the
1673 /// leading zeros unless the `min_width` is specified. The
1674 /// `min_width` is the minimum number of bits to push
1675 /// (including leading zeros for padding). If the `min_width`
1676 /// is specified, then leading zeros are pushed before pushing
1677 /// the bits in the u32 to the BitVector.
1678 ///
1679 /// # Examples
1680 /// ```
1681 /// use deepmesa_collections::BitVector;
1682 ///
1683 /// let mut bv = BitVector::new();
1684 /// let val:u32 = 0b101;
1685 /// bv.push_u32(val, None);
1686 /// assert_eq!(bv.len(), 3);
1687 /// assert_eq!(bv[0], true);
1688 /// assert_eq!(bv[1], false);
1689 /// assert_eq!(bv[2], true);
1690 ///
1691 /// bv.clear();
1692 /// bv.push_u32(val, Some(5));
1693 /// assert_eq!(bv.len(), 5);
1694 /// assert_eq!(bv[0], false);
1695 /// assert_eq!(bv[1], false);
1696 /// assert_eq!(bv[2], true);
1697 /// assert_eq!(bv[3], false);
1698 /// assert_eq!(bv[4], true);
1699 /// ```
1700 u32,
1701 32,
1702 push_u32
1703 );
1704 push_unsigned!(
1705 /// Pushes bits from the specified [`u64`] `val` excluding the
1706 /// leading zeros unless the `min_width` is specified. The
1707 /// `min_width` is the minimum number of bits to push
1708 /// (including leading zeros for padding). If the `min_width`
1709 /// is specified, then leading zeros are pushed before pushing
1710 /// the bits in the u64 to the BitVector.
1711 ///
1712 /// # Examples
1713 /// ```
1714 /// use deepmesa_collections::BitVector;
1715 ///
1716 /// let mut bv = BitVector::new();
1717 /// let val:u64 = 0b101;
1718 /// bv.push_u64(val, None);
1719 /// assert_eq!(bv.len(), 3);
1720 /// assert_eq!(bv[0], true);
1721 /// assert_eq!(bv[1], false);
1722 /// assert_eq!(bv[2], true);
1723 ///
1724 /// bv.clear();
1725 /// bv.push_u64(val, Some(5));
1726 /// assert_eq!(bv.len(), 5);
1727 /// assert_eq!(bv[0], false);
1728 /// assert_eq!(bv[1], false);
1729 /// assert_eq!(bv[2], true);
1730 /// assert_eq!(bv[3], false);
1731 /// assert_eq!(bv[4], true);
1732 /// ```
1733 u64,
1734 64,
1735 push_u64
1736 );
1737 push_unsigned!(
1738 /// Pushes bits from the specified [`u128`] `val` excluding the
1739 /// leading zeros unless the `min_width` is specified. The
1740 /// `min_width` is the minimum number of bits to push
1741 /// (including leading zeros for padding). If the `min_width`
1742 /// is specified, then leading zeros are pushed before pushing
1743 /// the bits in the u128 to the BitVector.
1744 ///
1745 /// # Examples
1746 /// ```
1747 /// use deepmesa_collections::BitVector;
1748 ///
1749 /// let mut bv = BitVector::new();
1750 /// let val:u128 = 0b101;
1751 /// bv.push_u128(val, None);
1752 /// assert_eq!(bv.len(), 3);
1753 /// assert_eq!(bv[0], true);
1754 /// assert_eq!(bv[1], false);
1755 /// assert_eq!(bv[2], true);
1756 ///
1757 /// bv.clear();
1758 /// bv.push_u128(val, Some(5));
1759 /// assert_eq!(bv.len(), 5);
1760 /// assert_eq!(bv[0], false);
1761 /// assert_eq!(bv[1], false);
1762 /// assert_eq!(bv[2], true);
1763 /// assert_eq!(bv[3], false);
1764 /// assert_eq!(bv[4], true);
1765 /// ```
1766 u128,
1767 128,
1768 push_u128
1769 );
1770
1771 /// Returns an immutable reference to a [BitSlice](BitSlice)
1772 /// containing all the bits of the BitVector. This call is
1773 /// equivalent to &bv[..].
1774 ///
1775 /// # Examples
1776 /// ```
1777 /// use deepmesa_collections::BitVector;
1778 ///
1779 /// let mut bv = BitVector::new();
1780 /// bv.push_u8(0b1011_1100, None);
1781 /// let slice = bv.as_bitslice();
1782 /// assert_eq!(slice.len(), 8);
1783 /// let slice = &bv[..];
1784 /// assert_eq!(slice.len(), 8);
1785 /// ```
1786 pub fn as_bitslice(&self) -> &BitSlice {
1787 self.index(0..self.bit_len)
1788 }
1789
1790 /// Returns a mutable reference to a [BitSlice](BitSlice)
1791 /// containing all the bits of the BitVector. This call is
1792 /// equivalent to &mut bv[..].
1793 ///
1794 /// # Examples
1795 /// ```
1796 /// use deepmesa_collections::BitVector;
1797 ///
1798 /// let mut bv = BitVector::new();
1799 /// bv.push_u8(0b1011_1100, None);
1800 /// let slice = bv.as_mut_bitslice();
1801 /// assert_eq!(slice.len(), 8);
1802 /// let slice = &mut bv[..];
1803 /// assert_eq!(slice.len(), 8);
1804 /// ```
1805 pub fn as_mut_bitslice(&mut self) -> &mut BitSlice {
1806 self.index_mut(0..self.bit_len)
1807 }
1808
1809 /// Returns an immutable slice of the underlying [`Vec<u8>`](https://doc.rust-lang.org/std/vec/struct.Vec.html)
1810 /// containing the u8 values that encode the bits of the
1811 /// BitVector. Reading the bytes directly from this raw slice is
1812 /// not recommended since the BitVector manages the bytes in the
1813 /// underlying [`Vector`](https://doc.rust-lang.org/std/vec/struct.Vec.html).
1814 ///
1815 /// # Examples
1816 /// ```
1817 /// use deepmesa_collections::BitVector;
1818 ///
1819 /// let mut bv = BitVector::new();
1820 /// bv.push_u8(0b0100_1101, Some(8));
1821 /// let raw_slice = bv.as_raw_slice();
1822 /// assert_eq!(raw_slice.len(), 1);
1823 /// assert_eq!(raw_slice, &[0x4D]);
1824 /// ```
1825 pub fn as_raw_slice(&self) -> &[u8] {
1826 unsafe {
1827 let ptr = self.bits.as_ptr();
1828 std::slice::from_raw_parts(ptr, self.bits.len())
1829 }
1830 }
1831
1832 /// Returns a mutable slice of the underlying [`Vec<u8>`](https://doc.rust-lang.org/std/vec/struct.Vec.html)
1833 /// containing the u8 values that encode the bits of the
1834 /// BitVector. Reading from or modifying the bytes directly in
1835 /// this raw slice is not recommended since the BitVector manages
1836 /// the bytes in the underlying [`Vector`](https://doc.rust-lang.org/std/vec/struct.Vec.html).
1837 ///
1838 /// # Examples
1839 /// ```
1840 /// use deepmesa_collections::BitVector;
1841 ///
1842 /// let mut bv = BitVector::new();
1843 /// bv.push_u8(0b0100_1101, Some(8));
1844 /// let raw_slice = bv.as_mut_raw_slice();
1845 /// assert_eq!(raw_slice.len(), 1);
1846 /// assert_eq!(raw_slice, &[0x4D]);
1847 /// ```
1848 pub fn as_mut_raw_slice(&mut self) -> &mut [u8] {
1849 unsafe {
1850 let ptr = self.bits.as_mut_ptr();
1851 std::slice::from_raw_parts_mut(ptr, self.bits.len())
1852 }
1853 }
1854
1855 /// Returns a raw pointer to the underlying [`Vec<u8>`](https://doc.rust-lang.org/std/vec/struct.Vec.html) containing
1856 /// the u8 values that encode the bits of the BitVector. Reading
1857 /// from the bytes directly from this raw pointer is not
1858 /// recommended since the BitVector manages the bytes in the
1859 /// underlying [`Vector`](https://doc.rust-lang.org/std/vec/struct.Vec.html).
1860 ///
1861 /// # Examples
1862 /// ```
1863 /// use deepmesa_collections::BitVector;
1864 ///
1865 /// let mut bv = BitVector::new();
1866 /// bv.push_u8(0b0100_1101, Some(8));
1867 /// let raw_ptr = bv.as_raw_ptr();
1868 /// ```
1869 pub fn as_raw_ptr(&self) -> *const u8 {
1870 self.bits.as_ptr()
1871 }
1872
1873 /// Returns a mutable raw pointer to the underlying [`Vec<u8>`](https://doc.rust-lang.org/std/vec/struct.Vec.html)
1874 /// containing the u8 values that encode the bits of the
1875 /// BitVector. Reading from or writing to the bytes directly in
1876 /// this raw pointer is not recommended since the BitVector
1877 /// manages the bytes in the underlying [`Vector`](https://doc.rust-lang.org/std/vec/struct.Vec.html).
1878 ///
1879 /// # Examples
1880 /// ```
1881 /// use deepmesa_collections::BitVector;
1882 ///
1883 /// let mut bv = BitVector::new();
1884 /// bv.push_u8(0b0100_1101, Some(8));
1885 /// let raw_ptr = bv.as_mut_raw_ptr();
1886 /// ```
1887 pub fn as_mut_raw_ptr(&mut self) -> *mut u8 {
1888 self.bits.as_mut_ptr()
1889 }
1890
1891 /// Moves all the bits of `other` into `self`, leaving `other`
1892 /// empty.
1893 ///
1894 /// # Examples
1895 /// ```
1896 /// use deepmesa_collections::BitVector;
1897 ///
1898 /// let mut bv = BitVector::new();
1899 /// bv.push_u8(0b1101, None);
1900 /// let mut other = BitVector::new();
1901 /// other.push_u8(0b1111_0011, Some(8));
1902 /// bv.append(&mut other);
1903 /// assert_eq!(bv.len(), 12);
1904 /// assert_eq!(other.len(), 0);
1905 /// ```
1906 pub fn append(&mut self, other: &mut BitVector) {
1907 let mut iter = other.iter_u8();
1908 while let Some((val, bitcount)) = iter.next() {
1909 self.push_u8(val, Some(bitcount));
1910 }
1911
1912 other.clear()
1913 }
1914
1915 /// Copies all the bits from the specified [BitSlice] into the
1916 /// BitVector.
1917 ///
1918 /// # Examples
1919 /// ```
1920 /// use deepmesa_collections::BitVector;
1921 ///
1922 /// let mut bv = BitVector::new();
1923 /// bv.push_u8(0b1101, None);
1924 /// let mut other = BitVector::new();
1925 /// other.push_u8(0b1111_0011, Some(8));
1926 /// let other_slice = &other[..];
1927 /// bv.extend_from_bitslice(other_slice);
1928 /// assert_eq!(bv.len(), 12);
1929 /// ```
1930 pub fn extend_from_bitslice(&mut self, other: &BitSlice) {
1931 let mut iter = other.iter_u8();
1932 while let Some((val, bitcount)) = iter.next() {
1933 self.push_u8(val, Some(bitcount));
1934 }
1935 }
1936
1937 /// Creates a new BitVector by copying the contents of the
1938 /// specified [BitSlice].
1939 ///
1940 /// # Examples
1941 /// ```
1942 /// use deepmesa_collections::BitVector;
1943 ///
1944 /// let mut bv = BitVector::new();
1945 /// bv.push_u8(0b1101, None);
1946 ///
1947 /// let bv2 = BitVector::from_bitslice(&bv[..]);
1948 /// assert_eq!(bv2.len(), 4);
1949 /// ```
1950 pub fn from_bitslice(slice: &BitSlice) -> Self {
1951 let mut bv = BitVector::with_capacity(slice.len());
1952 let mut iter = slice.iter_u8();
1953 while let Some((val, bitcount)) = iter.next() {
1954 bv.push_u8(val, Some(bitcount));
1955 }
1956 bv
1957 }
1958
1959 /// Creates a new BitVector with a bit repeated `len` times
1960 ///
1961 /// # Examples
1962 /// ```
1963 /// use deepmesa_collections::BitVector;
1964 ///
1965 /// let bv = BitVector::repeat(true, 4);
1966 /// assert_eq!(bv.len(), 4);
1967 /// ```
1968 pub fn repeat(bit: bool, len: usize) -> Self {
1969 let mut bv = BitVector::with_capacity(len);
1970 bv.fill(bit, len);
1971 bv
1972 }
1973 /// Sets the bit at the given index to 1 if bit is true, otherwise
1974 /// clears it. Panic if the index exceeds the length
1975 /// # Examples
1976 /// ```
1977 /// use deepmesa_collections::BitVector;
1978 ///
1979 /// let mut bv = BitVector::with_capacity(22);
1980 /// bv.push(true);
1981 /// bv.push(false);
1982 /// bv.push(true);
1983 /// assert_eq!(bv[0], true);
1984 /// assert_eq!(bv[1], false);
1985 /// assert_eq!(bv[2], true);
1986 /// bv.set(0, false);
1987 /// bv.set(1, true);
1988 /// bv.set(2, false);
1989 /// assert_eq!(bv[0], false);
1990 /// assert_eq!(bv[1], true);
1991 /// assert_eq!(bv[2], false);
1992 /// ```
1993 pub fn set(&mut self, index: usize, value: bool) {
1994 if index >= self.len() {
1995 panic!(
1996 "index out of bounds: the len is {} but the index is {}",
1997 self.len(),
1998 index
1999 );
2000 }
2001
2002 set_unchecked!(index, value, &mut self.bits);
2003 }
2004
2005 /// Returns a boolean value indicating whether the bit at the
2006 /// specified index is set or `None` if the index is greater than
2007 /// or equal to the number of bits in the BitVector.
2008 ///
2009 /// # Examples
2010 /// ```
2011 /// use deepmesa_collections::BitVector;
2012 ///
2013 /// let mut bv = BitVector::with_capacity(22);
2014 /// bv.push(true);
2015 /// bv.push(true);
2016 /// bv.push(false);
2017 /// assert_eq!(bv.get(0), Some(true));
2018 /// assert_eq!(bv.get(1), Some(true));
2019 /// assert_eq!(bv.get(2), Some(false));
2020 /// assert_eq!(bv.get(3), None);
2021 /// ```
2022 pub fn get(&self, index: usize) -> Option<bool> {
2023 if index >= self.len() {
2024 return None;
2025 }
2026
2027 return Some(bit_at_unchecked!(index, self.bits));
2028 }
2029
2030 pub fn get_mut(&mut self, index: usize) -> Option<BitRefMut<bool>> {
2031 if index >= self.bit_len {
2032 return None;
2033 }
2034 let bit = bit_at_unchecked!(index, self.bits);
2035
2036 let byte_idx = index / 8;
2037 let byte_ptr = self.bits[byte_idx..byte_idx].as_mut_ptr();
2038 return Some(BitRefMut::<bool>::new(bit, byte_ptr, index));
2039 }
2040
2041 /// Pushes a single bit to the end of the BitVector.
2042 ///
2043 /// # Examples
2044 /// ```
2045 /// use deepmesa_collections::BitVector;
2046 ///
2047 /// let mut bv = BitVector::with_capacity(22);
2048 /// bv.push(true);
2049 /// bv.push(false);
2050 /// assert_eq!(bv[0], true);
2051 /// assert_eq!(bv[1], false);
2052 /// ```
2053 pub fn push(&mut self, bit: bool) {
2054 if bit {
2055 self.push_bits_msb0(u128::MAX, 1);
2056 } else {
2057 self.push_bits_msb0(0, 1);
2058 }
2059 }
2060
2061 /// Removes the last bit from the BitVector or None if its empty.
2062 ///
2063 /// # Examples
2064 /// ```
2065 /// use deepmesa_collections::BitVector;
2066 ///
2067 /// let mut bv = BitVector::with_capacity(22);
2068 /// bv.push(true);
2069 /// bv.push(false);
2070 /// bv.push(true);
2071 /// assert_eq!(bv.get(0), Some(true));
2072 /// assert_eq!(bv.get(1), Some(false));
2073 /// assert_eq!(bv.get(2), Some(true));
2074 /// assert_eq!(bv.pop(), Some(true));
2075 /// assert_eq!(bv.get(2), None);
2076 /// ```
2077 pub fn pop(&mut self) -> Option<bool> {
2078 if self.bit_len == 0 {
2079 return None;
2080 }
2081 let retval = self.get(self.bit_len - 1);
2082 let pos: u8 = ((self.bit_len - 1) % 8) as u8;
2083
2084 if pos == 0 {
2085 self.bits.pop();
2086 } else {
2087 self.bits[(self.bit_len - 1) / 8].clear_msb_nth_assign(pos);
2088 }
2089 self.bit_len -= 1;
2090 retval
2091 }
2092
2093 /// Extends the BitVector by pushing the specified `bit`, `count`
2094 /// times to the end of the BitVector.
2095 ///
2096 /// # Examples
2097 /// ```
2098 /// use deepmesa_collections::BitVector;
2099 ///
2100 /// let mut bv = BitVector::new();
2101 /// bv.fill(true, 4);
2102 /// assert_eq!(bv.len(), 4);
2103 /// ```
2104 pub fn fill(&mut self, bit: bool, count: usize) -> BitCount {
2105 let mut push_val: u128 = 0;
2106 if bit {
2107 push_val = u128::MAX;
2108 }
2109 let mut rem = count;
2110 let mut total_pushed = 0;
2111 while rem > 0 {
2112 let mut push_ct = rem;
2113 if push_ct > 128 {
2114 push_ct = 128;
2115 }
2116 let pushed = self.push_bits_msb0(push_val, push_ct);
2117 total_pushed += pushed;
2118 rem -= pushed;
2119 }
2120 total_pushed
2121 }
2122}
2123
2124impl Debug for BitVector {
2125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2126 write!(
2127 f,
2128 "BitVector {{ bit_len: {}, capacity_bits: {}, bits:\n",
2129 self.bit_len, self.capacity_bits
2130 )?;
2131
2132 let mut count = 0;
2133 write!(f, "{{")?;
2134 for byte in self.bits.iter() {
2135 if count % 4 == 0 {
2136 write!(f, "\n ")?;
2137 }
2138 write!(f, "{:08b} ", byte)?;
2139 count += 1;
2140 }
2141 write!(f, "\n}}}}")?;
2142 Ok(())
2143 }
2144}
2145
2146impl Index<usize> for BitVector {
2147 type Output = bool;
2148 fn index(&self, index: usize) -> &Self::Output {
2149 match self.get(index) {
2150 None => {
2151 panic!(
2152 "index out of bounds: the len is {} but the index is {}",
2153 self.bit_len, index
2154 );
2155 }
2156 Some(true) => &true,
2157 Some(false) => &false,
2158 }
2159 }
2160}
2161
2162impl Not for BitVector {
2163 type Output = Self;
2164 fn not(mut self) -> Self::Output {
2165 if self.bit_len == 0 {
2166 return self;
2167 }
2168
2169 for byte in self.bits.iter_mut() {
2170 *byte = !*byte;
2171 }
2172
2173 clr_lsb_last_byte!(self);
2174 self
2175 }
2176}
2177
2178macro_rules! impl_bitwise {
2179 ($t_name: ident, $fn_name: ident, $rhs: ty, $for: ty, $op: tt) => {
2180 impl $t_name<$rhs> for $for {
2181 type Output = Self;
2182 fn $fn_name(mut self, rhs: $rhs) -> Self::Output {
2183 b_expr!(self $op rhs);
2184 self
2185 }
2186 }
2187 };
2188}
2189
2190// impl BitAnd<BitVector> for BitVector
2191impl_bitwise!(BitAnd, bitand, BitVector, BitVector, &=);
2192// impl BitAnd<&BitVector> for BitVector
2193impl_bitwise!(BitAnd, bitand, &BitVector, BitVector, &=);
2194// impl BitAnd<&BitSlice> for BitVector
2195impl_bitwise!(BitAnd, bitand, &BitSlice, BitVector, &=);
2196
2197// impl BitOr<BitVector> for BitVector
2198impl_bitwise!(BitOr, bitor, BitVector, BitVector, |=);
2199// impl BitOr<&BitVector> for BitVector
2200impl_bitwise!(BitOr, bitor, &BitVector, BitVector, |=);
2201// impl BitOr<&BitSlice> for BitVector
2202impl_bitwise!(BitOr, bitor, &BitSlice, BitVector, |=);
2203
2204// impl BitXor<BitVector> for BitVector
2205impl_bitwise!(BitXor, bitxor, BitVector, BitVector, ^=);
2206// impl BitXor<&BitVector> for BitVector
2207impl_bitwise!(BitXor, bitxor, &BitVector, BitVector, ^=);
2208// impl BitXor<&BitSlice> for BitVector
2209impl_bitwise!(BitXor, bitxor, &BitSlice, BitVector, ^=);
2210
2211macro_rules! impl_bitwise_bool {
2212 ($t_name: ident, $fn_name: ident, $for: ty, $op:tt) => {
2213 impl $t_name<bool> for $for {
2214 type Output = Self;
2215 fn $fn_name(mut self, rhs: bool) -> Self::Output {
2216 b_expr!(self $op rhs);
2217 self
2218 }
2219 }
2220 };
2221}
2222
2223impl_bitwise_bool!(BitOr, bitor, BitVector, |=);
2224impl_bitwise_bool!(BitAnd, bitand, BitVector, &=);
2225impl_bitwise_bool!(BitXor, bitxor, BitVector, ^=);
2226
2227macro_rules! impl_bitwise_assign {
2228 ($t_name: ident, $fn_name: ident, $rhs: ty, $for: ty, $op: tt) => {
2229 impl $t_name<$rhs> for $for {
2230 fn $fn_name(&mut self, rhs: $rhs) {
2231 if self.bit_len == 0 {
2232 return;
2233 }
2234
2235 let mut s_iter = rhs.iter_u8();
2236 for byte in self.bits.iter_mut() {
2237 if let Some((s_byte, s_bits)) = s_iter.next() {
2238 if s_bits == 8 {
2239 b_expr!(*byte $op s_byte);
2240 } else {
2241 b_expr!(*byte $op (s_byte).as_msb0(s_bits));
2242 }
2243 } else {
2244 break;
2245 }
2246 }
2247
2248 clr_lsb_last_byte!(self);
2249 }
2250 }
2251 };
2252}
2253
2254//impl BitAndAssign<BitVector> for BitVector
2255impl_bitwise_assign!(BitAndAssign, bitand_assign, BitVector, BitVector, &=);
2256//impl BitAndAssign<&BitVector> for BitVector
2257impl_bitwise_assign!(BitAndAssign, bitand_assign, &BitVector, BitVector, &=);
2258//impl BitAndAssign<&BitSlice> for BitVector
2259impl_bitwise_assign!(BitAndAssign, bitand_assign, &BitSlice, BitVector, &=);
2260
2261//impl BitOrAssign<BitVector> for BitVector {
2262impl_bitwise_assign!(BitOrAssign, bitor_assign, BitVector, BitVector, |=);
2263//impl BitOrAssign<&BitVector> for BitVector {
2264impl_bitwise_assign!(BitOrAssign, bitor_assign, &BitVector, BitVector, |=);
2265//impl BitOrAssign<&BitSlice> for BitVector {
2266impl_bitwise_assign!(BitOrAssign, bitor_assign, &BitSlice, BitVector, |=);
2267
2268//impl BitXorAssign<BitVector> for BitVector {
2269impl_bitwise_assign!(BitXorAssign, bitxor_assign, BitVector, BitVector, ^=);
2270//impl BitXorAssign<&BitVector> for BitVector {
2271impl_bitwise_assign!(BitXorAssign, bitxor_assign, &BitVector, BitVector, ^=);
2272//impl BitXorAssign<&BitSlice> for BitVector {
2273impl_bitwise_assign!(BitXorAssign, bitxor_assign, &BitSlice, BitVector, ^=);
2274
2275macro_rules! impl_bitwise_assign_bool {
2276 ($t_name: ident, $fn_name: ident, $for: ty, $op: tt) => {
2277 impl $t_name<bool> for $for {
2278 fn $fn_name(&mut self, rhs: bool) {
2279 if self.bit_len == 0 {
2280 return;
2281 }
2282 let mut and_val: u8 = 0;
2283 if rhs {
2284 and_val = u8::MAX;
2285 }
2286 for byte in self.bits.iter_mut() {
2287 b_expr!(*byte $op and_val);
2288 }
2289
2290 clr_lsb_last_byte!(self);
2291 }
2292 }
2293 };
2294}
2295
2296impl_bitwise_assign_bool!(BitAndAssign, bitand_assign, BitVector, &=);
2297impl_bitwise_assign_bool!(BitOrAssign, bitor_assign, BitVector, |=);
2298impl_bitwise_assign_bool!(BitXorAssign, bitxor_assign, BitVector, ^=);
2299
2300impl AsMut<BitSlice> for BitVector {
2301 fn as_mut(&mut self) -> &mut BitSlice {
2302 self.index_mut(0..self.bit_len)
2303 }
2304}
2305
2306impl AsRef<BitSlice> for BitVector {
2307 fn as_ref(&self) -> &BitSlice {
2308 self.index(0..self.bit_len)
2309 }
2310}
2311
2312impl Default for BitVector {
2313 fn default() -> Self {
2314 Self::new()
2315 }
2316}
2317
2318impl_index_range!(BitVector, BitVector, bits);
2319impl_index_range_mut!(BitVector, BitVector, bits);
2320
2321//Private and Helper methods
2322impl BitVector {
2323 /// Pushes `bit_count` bits in the specified u128 into the vector
2324 /// starting from the msb.
2325 fn push_bits_msb0(&mut self, val: u128, bit_count: BitCount) -> BitCount {
2326 debug_assert!(
2327 bit_count <= 128,
2328 "cannot push more than 128 bits from a u128. count={}",
2329 bit_count
2330 );
2331
2332 if bit_count == 0 {
2333 return 0;
2334 }
2335 let mut len_b = U128_BITS;
2336 let mut rem = bit_count as u8;
2337
2338 // Calculate the number of partial bits in the last byte.
2339 let partial_bits = (self.bit_len % 8) as u8;
2340
2341 //if push_ct is 1 thru 7 then do this. If its 0 then push a
2342 // whole byte, if its 8 then push 8 bits (aka whole byte)
2343
2344 if partial_bits > 0 {
2345 let push_ct = 8 - partial_bits;
2346 let mut byte: u8 = bitops::ls_byte(val >> (len_b - 8));
2347 if push_ct > rem {
2348 byte.clear_lsb_assign(8 - rem);
2349 rem = 0;
2350 } else {
2351 len_b -= push_ct;
2352 rem -= push_ct;
2353 }
2354 bitops::shl_into(&mut self.bits[(self.bit_len - 1) / 8], byte, push_ct);
2355 }
2356
2357 while rem >= 8 {
2358 // Get the 8 bits of val from the MSB end (shift val right
2359 // then get the LSB 8 bits)
2360 let byte: u8 = bitops::ls_byte(val >> (len_b - 8));
2361 len_b -= 8;
2362 rem -= 8;
2363 self.bits.push(byte);
2364 }
2365
2366 if rem > 0 {
2367 // Get the 8 bits of val from the MSB end (shift val right
2368 // then get the LSB 8 bits)
2369 let byte: u8 = bitops::ls_byte(val >> (len_b - 8));
2370 //clear out the 8-rem lsb bits of the byte
2371 self.bits.push(byte.clear_lsb(8 - rem));
2372 }
2373 self.bit_len += bit_count as usize;
2374 bit_count
2375 }
2376}
2377
2378#[cfg(test)]
2379impl BitVector {
2380 #[cfg(test)]
2381 fn len_bytes(&self) -> usize {
2382 self.bits.len()
2383 }
2384
2385 #[cfg(test)]
2386 fn byte_at(&self, byte_index: usize) -> Option<u8> {
2387 self.bits.get(byte_index).cloned()
2388 }
2389}
2390
2391#[cfg(test)]
2392mod tests {
2393 use super::*;
2394 use crate::bitvector;
2395 #[test]
2396 fn test_bit_at() {
2397 let mut bv = BitVector::with_capacity(32);
2398 //push a byte = 0101_0011
2399 bv.push_bits_u8(0b0101_0011, 8, BitOrder::Lsb0);
2400 assert_eq!(bv.get(0).unwrap(), false);
2401 assert_eq!(bv.get(1).unwrap(), true);
2402 assert_eq!(bv.get(2).unwrap(), false);
2403 assert_eq!(bv.get(3).unwrap(), true);
2404 assert_eq!(bv.get(4).unwrap(), false);
2405 assert_eq!(bv.get(5).unwrap(), false);
2406 assert_eq!(bv.get(6).unwrap(), true);
2407 assert_eq!(bv.get(7).unwrap(), true);
2408
2409 //push another byte = 1100_1011
2410 bv.push_bits_u8(0b1100_1011, 8, BitOrder::Lsb0);
2411 assert_eq!(bv.get(8).unwrap(), true);
2412 assert_eq!(bv.get(9).unwrap(), true);
2413 assert_eq!(bv.get(10).unwrap(), false);
2414 assert_eq!(bv.get(11).unwrap(), false);
2415 assert_eq!(bv.get(12).unwrap(), true);
2416 assert_eq!(bv.get(13).unwrap(), false);
2417 assert_eq!(bv.get(14).unwrap(), true);
2418 assert_eq!(bv.get(15).unwrap(), true);
2419
2420 assert_eq!(bv.get(18), None);
2421 }
2422
2423 #[test]
2424 fn test_push_byte() {
2425 let mut bv = BitVector::with_capacity(32);
2426 assert_eq!(bv.len(), 0);
2427 assert_eq!(bv.len_bytes(), 0);
2428 assert_eq!(bv.bit_len, 0);
2429 bv.push_bits_u8(0b0110_0000, 8, BitOrder::Lsb0);
2430 assert_eq!(bv.len(), 8);
2431 assert_eq!(bv.bit_len, 8);
2432 assert_eq!(bv.len(), 8);
2433 assert_eq!(bv.len_bytes(), 1);
2434 //now artifically set the bit_len to 3 to indicate that
2435 // there are only 3 buts in the bitvec
2436 bv.bit_len = 3;
2437 assert_eq!(bv.len(), 3);
2438 assert_eq!(bv.len_bytes(), 1);
2439 assert_eq!(bv.bit_len, 3);
2440
2441 //now push another byte and ensure that the correct bits are
2442 // set
2443 bv.push_bits_u8(0b0110_1001, 8, BitOrder::Lsb0);
2444 assert_eq!(bv.len(), 11);
2445 assert_eq!(bv.len_bytes(), 2);
2446 assert_eq!(bv.bit_len, 11);
2447 assert!(bv.byte_at(0).is_some());
2448 assert!(bv.byte_at(1).is_some());
2449 assert_eq!(
2450 bv.byte_at(0).unwrap(), //Goober
2451 0b0110_1101,
2452 "Found {:08b}",
2453 bv.byte_at(0).unwrap()
2454 );
2455
2456 assert_eq!(
2457 bv.byte_at(1).unwrap(),
2458 0b0010_0000,
2459 "Found {:08b} at byte(1)",
2460 bv.byte_at(1).unwrap()
2461 );
2462 }
2463
2464 //test pushing bits in 8 bit multiples
2465 #[test]
2466 fn test_push_bits_8_multiple() {
2467 let mut bv = BitVector::with_capacity(32);
2468 assert_eq!(bv.len(), 0);
2469 assert_eq!(bv.bit_len, 0);
2470 bv.fill(true, 8);
2471 assert_eq!(bv.len(), 8);
2472 assert_eq!(bv.bit_len, 8);
2473 for i in 0..8 {
2474 assert_eq!(bv.get(i).unwrap(), true);
2475 }
2476 assert_eq!(bv.byte_at(0).unwrap(), 0b1111_1111);
2477 assert_eq!(bv.byte_at(1), None);
2478 //now push a byte of zeros
2479 bv.fill(false, 8);
2480 assert_eq!(bv.len(), 16);
2481 assert_eq!(bv.bit_len, 16);
2482 for i in 8..16 {
2483 assert_eq!(bv.get(i).unwrap(), false);
2484 }
2485 assert_eq!(bv.byte_at(1).unwrap(), 0b0000_0000);
2486 assert_eq!(bv.byte_at(2), None);
2487 }
2488
2489 #[test]
2490 fn test_fill() {
2491 let mut bv = BitVector::with_capacity(32);
2492 assert_eq!(bv.len(), 0);
2493 assert_eq!(bv.bit_len, 0);
2494 bv.fill(true, 1);
2495 assert_eq!(bv.len(), 1);
2496 assert_eq!(bv.get(0).unwrap(), true);
2497 assert_eq!(bv.get(1), None);
2498 assert_eq!(bv.byte_at(0).unwrap(), 0b1000_0000);
2499 assert_eq!(bv.byte_at(1), None);
2500
2501 bv.fill(false, 2);
2502 assert_eq!(bv.len(), 3);
2503 assert_eq!(bv.get(0).unwrap(), true);
2504 assert_eq!(bv.get(1).unwrap(), false);
2505 assert_eq!(bv.get(2).unwrap(), false);
2506 assert_eq!(bv.get(3), None);
2507 assert_eq!(bv.byte_at(0).unwrap(), 0b1000_0000);
2508 assert_eq!(bv.byte_at(1), None, "Found {:08b}", bv.byte_at(1).unwrap());
2509
2510 let val = 0b0110_0011;
2511 bv.push_bits_u8(val, 8, BitOrder::Lsb0);
2512 assert_eq!(bv.byte_at(0).unwrap(), 0b1000_1100);
2513 assert_eq!(bv.byte_at(1).unwrap(), 0b0110_0000);
2514 assert_eq!(bv.byte_at(2), None);
2515 // assert_eq!(val << 3, 0b0001_1000);
2516 // lts3 = 011 0001_1000
2517 assert_eq!(bv.len(), 11);
2518 assert_eq!(bv.bit_len, 11);
2519
2520 assert_eq!(bv.get(0).unwrap(), true);
2521 assert_eq!(bv.get(1).unwrap(), false);
2522 assert_eq!(bv.get(2).unwrap(), false);
2523
2524 assert_eq!(bv.get(3).unwrap(), false);
2525 assert_eq!(bv.get(4).unwrap(), true);
2526 assert_eq!(bv.get(5).unwrap(), true);
2527 assert_eq!(bv.get(6).unwrap(), false);
2528
2529 assert_eq!(bv.get(7).unwrap(), false);
2530 assert_eq!(bv.get(8).unwrap(), false);
2531 assert_eq!(bv.get(9).unwrap(), true);
2532 assert_eq!(bv.get(10).unwrap(), true);
2533 assert_eq!(bv.get(11), None);
2534 assert_eq!(bv.get(12), None);
2535 assert_eq!(bv.get(9282), None);
2536 }
2537
2538 #[test]
2539 fn test_push_100_bits() {
2540 let mut bv = BitVector::with_capacity(1);
2541 assert_eq!(bv.len(), 0);
2542 assert_eq!(bv.bit_len, 0);
2543 bv.fill(true, 100);
2544 assert_eq!(bv.len(), 100);
2545 for i in 0..100 {
2546 assert_eq!(bv.get(i).unwrap(), true);
2547 }
2548 assert_eq!(bv.get(100), None);
2549 }
2550
2551 #[test]
2552 #[should_panic(expected = "cannot push more than 8 bits from a u8. bit_count=10")]
2553 fn test_push_bits_u8_panic() {
2554 let mut bv = BitVector::with_capacity(20);
2555 let val = 0b1010_1000;
2556
2557 bv.push_bits_u8(val, 10, BitOrder::Msb0);
2558 }
2559
2560 #[test]
2561 fn test_push_bits() {
2562 let mut bv = BitVector::with_capacity(20);
2563 let val: u8 = 0b1100_1010;
2564 bv.push_bits_u8(val, 0, BitOrder::Msb0);
2565 assert_eq!(bv.len(), 0);
2566 assert_eq!(bv.byte_at(0), None);
2567
2568 bv.push_bits_u8(val, 3, BitOrder::Msb0);
2569 assert_eq!(bv.len(), 3);
2570 assert_eq!(bv.byte_at(0).unwrap(), 0b1100_0000);
2571
2572 //now push 3 more
2573 bv.push_bits_u8(val, 3, BitOrder::Msb0);
2574 assert_eq!(bv.len(), 6);
2575 assert_eq!(bv.byte_at(0).unwrap(), 0b1101_1000);
2576
2577 //now push 0 bits of a byte again
2578 bv.push_bits_u8(val, 0, BitOrder::Msb0);
2579 assert_eq!(bv.len(), 6);
2580 assert_eq!(bv.byte_at(0).unwrap(), 0b1101_1000);
2581
2582 let val: u8 = 0b1010_0011;
2583 bv.push_bits_u8(val, 8, BitOrder::Msb0);
2584 assert_eq!(bv.len(), 14);
2585 assert_eq!(bv.byte_at(0).unwrap(), 0b1101_1010);
2586 assert_eq!(bv.byte_at(1).unwrap(), 0b1000_1100);
2587 assert_eq!(bv.byte_at(2), None);
2588 }
2589
2590 #[test]
2591 #[should_panic(expected = "cannot push more than 8 bits from a u8. bit_count=11")]
2592 fn test_push_bits_u8_trailing_panic() {
2593 let mut bv = BitVector::with_capacity(20);
2594 let val = 0b1010_1000;
2595
2596 bv.push_bits_u8(val, 11, BitOrder::Lsb0);
2597 }
2598
2599 #[test]
2600 fn test_push_bits_u8_trailing() {
2601 let mut bv = BitVector::with_capacity(20);
2602 let val = 0b1010_0011;
2603
2604 bv.push_bits_u8(val, 0, BitOrder::Lsb0);
2605 assert_eq!(bv.len(), 0);
2606
2607 bv.push_bits_u8(val, 3, BitOrder::Lsb0);
2608 assert_eq!(bv.len(), 3);
2609 assert_eq!(bv.byte_at(0).unwrap(), 0b0110_0000);
2610
2611 //Now push another 8 bits
2612 let val = 0b0101_1100;
2613 bv.push_bits_u8(val, 8, BitOrder::Lsb0);
2614 assert_eq!(bv.len(), 11);
2615 assert_eq!(bv.byte_at(0).unwrap(), 0b0110_1011);
2616 assert_eq!(bv.byte_at(1).unwrap(), 0b1000_0000);
2617 assert_eq!(bv.byte_at(2), None);
2618 }
2619
2620 #[test]
2621 #[should_panic(expected = "cannot push more than 128 bits from a u128. bit_count=300")]
2622 fn test_push_u128_panic() {
2623 let mut bv = BitVector::with_capacity(20);
2624 let val = 0b0110_1000;
2625 bv.push_bits_u128(val, 300, BitOrder::Msb0);
2626 }
2627
2628 #[test]
2629 fn test_push_usize_trailing() {
2630 let mut bv = BitVector::with_capacity(20);
2631 let val = 0b0110_1010;
2632
2633 //first push 0 bits
2634 bv.push_bits_u128(val, 0, BitOrder::Lsb0);
2635
2636 assert_eq!(bv.len(), 0);
2637
2638 //first push only 3 bits
2639 bv.push_bits_u128(val, 3, BitOrder::Lsb0);
2640 assert_eq!(bv.len(), 3);
2641 assert_eq!(
2642 bv.byte_at(0).unwrap(),
2643 0b0100_0000,
2644 "val={}/{:08b}, enc={}/{:08b}",
2645 val,
2646 val,
2647 bv.byte_at(0).unwrap(),
2648 bv.byte_at(0).unwrap()
2649 );
2650 assert_eq!(bv.byte_at(1), None);
2651 }
2652
2653 #[test]
2654 fn test_push_bits_u8() {
2655 let mut bv = BitVector::with_capacity(20);
2656 let val = 0b0110_1000;
2657
2658 //first push 0 bits
2659 assert_eq!(bv.push_bits_u8(val, 0, BitOrder::Msb0), 0);
2660 assert_eq!(bv.len(), 0);
2661
2662 //first push only 3 bits
2663 assert_eq!(bv.push_bits_u8(val, 3, BitOrder::Msb0), 3);
2664 assert_eq!(bv.len(), 3);
2665 assert_eq!(bv.byte_at(0).unwrap(), 0b01100_000);
2666 assert_eq!(bv.byte_at(1), None);
2667
2668 //now push 8 bits
2669 let val2 = 0b1100_0011;
2670 assert_eq!(bv.push_bits_u8(val2, 8, BitOrder::Msb0), 8);
2671 assert_eq!(bv.len(), 11); //0111_1000_011
2672 assert_eq!(bv.byte_at(0).unwrap(), 0b0111_1000);
2673 assert_eq!(bv.byte_at(1).unwrap(), 0b0110_0000);
2674 assert_eq!(bv.byte_at(2), None);
2675
2676 //now push 11 bits
2677 let val3 = 0b1100_0011_1010_0101;
2678 assert_eq!(bv.push_bits_u16(val3, 11, BitOrder::Msb0), 11);
2679 assert_eq!(bv.len(), 22); //0111_1000 0111_1000 0111_01
2680 assert_eq!(bv.byte_at(0).unwrap(), 0b0111_1000);
2681 assert_eq!(bv.byte_at(1).unwrap(), 0b0111_1000);
2682 assert_eq!(bv.byte_at(2).unwrap(), 0b0111_0100);
2683 assert_eq!(bv.byte_at(3), None);
2684
2685 //now push 5 bits out of a u128
2686 let val4 = 0b1011_1010 << U128_BITS - 8;
2687 assert_eq!(bv.push_bits_u128(val4, 5, BitOrder::Msb0), 5);
2688 assert_eq!(bv.byte_at(0).unwrap(), 0b0111_1000);
2689 assert_eq!(bv.byte_at(1).unwrap(), 0b0111_1000);
2690 assert_eq!(bv.byte_at(2).unwrap(), 0b0111_0110);
2691 assert_eq!(bv.byte_at(3).unwrap(), 0b1110_0000);
2692 assert_eq!(bv.byte_at(4), None);
2693 }
2694
2695 #[test]
2696 fn test_read_bits_u16() {
2697 let mut bv = BitVector::with_capacity(20);
2698 //push 3 bits 110
2699 bv.push(true);
2700 bv.push(true);
2701 bv.push(false);
2702 let (val, read) = bv.read_bits_u16(0, 3);
2703 assert_eq!(read, 3);
2704 assert_eq!(val, 6);
2705
2706 // Push another 8 bits for a total bitvector of:
2707 //1101_0011 110
2708 bv.push_bits_u8(0b1001_1110, 8, BitOrder::Msb0);
2709 assert_eq!(bv.len(), 11);
2710 let (val, read) = bv.read_bits_u16(0, 11);
2711 assert_eq!(read, 11);
2712 assert_eq!(val, 0b0000_0110_1001_1110);
2713 }
2714
2715 #[test]
2716 fn test_read_bits_u8() {
2717 let mut bv = BitVector::with_capacity(20);
2718 bv.push_bits_u8(0b1100_1011, 8, BitOrder::Msb0);
2719 bv.push_bits_u8(0b1010_0101, 8, BitOrder::Msb0);
2720 assert_eq!(bv.len(), 16);
2721
2722 //Read a byte from start = 0
2723 let (byte, numbits) = bv.read_bits_u8(0, 8);
2724 assert_eq!(numbits, 8);
2725 assert_eq!(byte, 0b1100_1011);
2726
2727 //Read a byte from start = 4
2728 let (byte, numbits) = bv.read_bits_u8(4, 8);
2729 assert_eq!(numbits, 8);
2730 assert_eq!(byte, 0b1011_1010);
2731
2732 //Read a byte from start = 12
2733 let (byte, numbits) = bv.read_bits_u8(12, 8);
2734 assert_eq!(numbits, 4);
2735 assert_eq!(byte, 0b0000_0101);
2736
2737 //Read a byte from start = 15
2738 let (byte, numbits) = bv.read_bits_u8(15, 8);
2739 assert_eq!(numbits, 1);
2740 assert_eq!(byte, 0b0000_0001);
2741 }
2742
2743 #[test]
2744 fn test_read_2bits() {
2745 let mut bv = BitVector::with_capacity(20);
2746 bv.push_bits_u8(0b1011_0111, 8, BitOrder::Msb0);
2747 bv.push_bits_u8(0b00001_0001, 8, BitOrder::Msb0);
2748 bv.push_bits_u8(0b1100_0011, 8, BitOrder::Msb0);
2749 bv.push_bits_u8(0b1111_1100, 6, BitOrder::Msb0);
2750 assert_eq!(bv.bit_len, 30);
2751 let (val, read) = bv.read_bits_u128(9, 2);
2752 assert_eq!(read, 2);
2753 assert_eq!(val, 0b0000_0000);
2754 }
2755
2756 #[test]
2757 fn test_slice() {
2758 let mut bv = BitVector::with_capacity(20);
2759 bv.push_u8(0b0001_0110, Some(8));
2760 let s = &bv[0..4];
2761 assert_eq!(s.len(), 4);
2762 let s = &bv[0..];
2763 assert_eq!(s.len(), 8);
2764 let s = &bv[0..=4];
2765 assert_eq!(s.len(), 5);
2766 let s = &bv[0..=7];
2767 assert_eq!(s.len(), 8);
2768 let s = &bv[..];
2769 assert_eq!(s.len(), 8);
2770 let s = &bv[..=6];
2771 assert_eq!(s.len(), 7);
2772 }
2773
2774 #[test]
2775 fn test_pop() {
2776 let mut bv = BitVector::with_capacity(20);
2777 bv.push_bits_u8(23, 8, BitOrder::Lsb0);
2778 assert_eq!(bv.get(7), Some(true));
2779 assert_eq!(bv.pop(), Some(true));
2780 assert_eq!(bv.get(7), None);
2781 bv.clear();
2782 bv.push(true);
2783 assert_eq!(bv.get(0), Some(true));
2784 assert_eq!(bv.pop(), Some(true));
2785 assert_eq!(bv.get(0), None);
2786 }
2787
2788 #[test]
2789 fn test_set() {
2790 let mut bv = BitVector::with_capacity(20);
2791 bv.push_bits_u8(0b1010_1100, 8, BitOrder::Lsb0);
2792 assert_eq!(bv.get(3), Some(false));
2793 assert_eq!(bv.get(7), Some(false));
2794 assert_eq!(bv.get(6), Some(false));
2795 bv.set(3, true);
2796 assert_eq!(bv.get(3), Some(true));
2797 bv.set(7, true);
2798 bv.set(6, true);
2799 assert_eq!(bv.get(6), Some(true));
2800 assert_eq!(bv.get(7), Some(true));
2801 bv.set(6, false);
2802 assert_eq!(bv.get(6), Some(false));
2803 bv.set(7, false);
2804 assert_eq!(bv.get(7), Some(false));
2805 }
2806
2807 #[test]
2808 fn test_push_bits_u64() {
2809 let mut bv = BitVector::with_capacity(512);
2810 bv.push_bits_u64(u64::MAX, 64, BitOrder::Msb0);
2811 let (val, bit_count) = bv.read_bits_u64(0, 64);
2812 assert_eq!(bit_count, 64);
2813 assert_eq!(val, u64::MAX);
2814 }
2815
2816 #[test]
2817 fn test_push_bits_u128() {
2818 let mut bv = BitVector::with_capacity(512);
2819 assert_eq!(bv.push_bits_u128(u64::MAX as u128, 64, BitOrder::Lsb0), 64);
2820 assert_eq!(bv.len(), 64);
2821 let (val, bit_count) = bv.read_bits_u128(0, 64);
2822 assert_eq!(bit_count, 64);
2823 assert_eq!(val, u64::MAX as u128);
2824 }
2825
2826 #[test]
2827 fn test_push_u8() {
2828 let mut bv = BitVector::with_capacity(20);
2829 let val: u8 = 0b0011_0000;
2830 bv.push_u8(val, None);
2831 assert_eq!(bv.len(), 6);
2832 assert_eq!(bv.get(0), Some(true));
2833 assert_eq!(bv.get(1), Some(true));
2834 assert_eq!(bv.get(2), Some(false));
2835 assert_eq!(bv.get(3), Some(false));
2836 assert_eq!(bv.get(4), Some(false));
2837 assert_eq!(bv.get(5), Some(false));
2838 assert_eq!(bv.get(6), None);
2839
2840 let (val2, bit_count) = bv.read_u8(0);
2841 assert_eq!(bit_count, 6);
2842 assert_eq!(val2, 0b0011_0000);
2843 }
2844
2845 #[test]
2846 fn test_get_mut() {
2847 let mut bv = BitVector::with_capacity(20);
2848 bv.push_u8(0b1011_1100, None);
2849 assert_eq!(bv[2], true);
2850 *bv.get_mut(2).unwrap() = false;
2851 assert_eq!(bv[2], false);
2852
2853 assert_eq!(bv[7], false);
2854 *bv.get_mut(7).unwrap() = true;
2855 assert_eq!(bv[7], true);
2856 }
2857
2858 #[test]
2859 fn test_read_u16() {
2860 let mut bv = BitVector::with_capacity(128);
2861 bv.push(true);
2862 bv.push(false);
2863 bv.push(true);
2864
2865 bv.push_u16(0b1100_1010_0011_0101, None);
2866 let (val, read) = bv.read_u16(3);
2867 assert_eq!(read, 16);
2868 assert_eq!(val, 0b1100_1010_0011_0101);
2869 }
2870
2871 #[test]
2872 fn test_push_u8_width() {
2873 let mut bv = BitVector::with_capacity(128);
2874
2875 bv.push_u8(0b0000_0000, Some(0));
2876 assert_eq!(bv.len(), 0);
2877 bv.clear();
2878
2879 bv.push_u8(0b0000_0000, Some(2));
2880 assert_eq!(bv.len(), 2);
2881 assert_eq!(bv.read_u8(0), (0b0000_0000, 2));
2882 bv.clear();
2883
2884 bv.push_u8(0b0000_0011, Some(2));
2885 assert_eq!(bv.len(), 2);
2886 assert_eq!(bv.read_u8(0), (0b0000_0011, 2));
2887 bv.clear();
2888
2889 bv.push_u8(0b0000_0011, Some(4));
2890 assert_eq!(bv.len(), 4);
2891 assert_eq!(bv.read_u8(0), (0b0000_0011, 4));
2892 bv.clear();
2893
2894 bv.push_u8(0b0111_1000, Some(5));
2895 assert_eq!(bv.len(), 7);
2896 assert_eq!(bv.read_u8(0), (0b0111_1000, 7));
2897 bv.clear();
2898
2899 bv.push_u8(0b0111_1000, Some(20));
2900 assert_eq!(bv.len(), 20);
2901 assert_eq!(bv.read_u8(0), (0b0000_0000, 8));
2902 bv.clear();
2903 }
2904
2905 #[test]
2906 fn test_bit_and() {
2907 let mut bv = BitVector::with_capacity(128);
2908 bv.push_u8(0b0000_0101, None);
2909 assert_eq!(bv.len(), 3);
2910
2911 let bv2 = bv & true;
2912 assert_eq!(bv2.len(), 3);
2913 assert_eq!(bv2.read_u8(0), (0b0000_0101, 3));
2914
2915 let bv3 = bv2 & false;
2916 assert_eq!(bv3.len(), 3);
2917 assert_eq!(bv3.read_u8(0), (0b0000_0000, 3));
2918 }
2919
2920 #[test]
2921 fn test_bit_and_assign() {
2922 let mut bv = BitVector::with_capacity(128);
2923 bv &= true; //should do nothing
2924 bv.push_u8(0b0000_0101, None);
2925 assert_eq!(bv.len(), 3);
2926
2927 bv &= true;
2928 assert_eq!(bv.len(), 3);
2929 assert_eq!(bv.read_u8(0), (0b0000_0101, 3));
2930
2931 bv &= false;
2932 assert_eq!(bv.len(), 3);
2933 assert_eq!(bv.read_u8(0), (0b0000_0000, 3));
2934
2935 bv.clear();
2936 bv.push_u16(0b1001_0011_0101_1010, Some(16));
2937 bv.push_u8(0b0000_0101, None);
2938 assert_eq!(bv.len(), 19);
2939 bv &= true;
2940 assert_eq!(bv.read_u16(0), (0b1001_0011_0101_1010, 16));
2941 assert_eq!(bv.read_u8(16), (0b0000_0101, 3));
2942
2943 bv &= false;
2944 assert_eq!(bv.read_u16(0), (0b0000_0000_0000_0000, 16));
2945 assert_eq!(bv.read_u8(16), (0b0000_0000, 3));
2946
2947 bv &= true;
2948 assert_eq!(bv.read_u16(0), (0b0000_0000_0000_0000, 16));
2949 assert_eq!(bv.read_u8(16), (0b0000_0000, 3));
2950 }
2951
2952 #[test]
2953 fn test_bit_or() {
2954 let mut bv = BitVector::with_capacity(128);
2955 bv.push_u8(0b0000_0101, None);
2956 assert_eq!(bv.len(), 3);
2957
2958 let bv2 = bv | true;
2959 assert_eq!(bv2.len(), 3);
2960 assert_eq!(bv2.read_u8(0), (0b0000_0111, 3));
2961
2962 let bv3 = bv2 | false;
2963 assert_eq!(bv3.len(), 3);
2964 assert_eq!(bv3.read_u8(0), (0b0000_0111, 3));
2965 }
2966
2967 #[test]
2968 fn test_bit_or_assign() {
2969 let mut bv = BitVector::with_capacity(128);
2970 bv |= true; //should do nothing
2971
2972 bv.push_u8(0b0000_0101, None);
2973 assert_eq!(bv.len(), 3);
2974
2975 bv |= true;
2976 assert_eq!(bv.len(), 3);
2977 assert_eq!(bv.read_u8(0), (0b0000_0111, 3));
2978
2979 bv |= false;
2980 assert_eq!(bv.len(), 3);
2981 assert_eq!(bv.read_u8(0), (0b0000_0111, 3));
2982
2983 bv.clear();
2984 bv.push_u16(0b1001_0011_0101_1010, Some(16));
2985 bv.push_u8(0b0000_0101, None);
2986 assert_eq!(bv.len(), 19);
2987 bv |= true;
2988 assert_eq!(bv.read_u16(0), (0b1111_1111_1111_1111, 16));
2989 assert_eq!(bv.read_u8(16), (0b0000_0111, 3));
2990
2991 bv |= false;
2992 assert_eq!(bv.read_u16(0), (0b1111_1111_1111_1111, 16));
2993 assert_eq!(bv.read_u8(16), (0b0000_0111, 3));
2994
2995 bv |= true;
2996 assert_eq!(bv.read_u16(0), (0b1111_1111_1111_1111, 16));
2997 assert_eq!(bv.read_u8(16), (0b0000_0111, 3));
2998 }
2999
3000 #[test]
3001 fn test_bit_not() {
3002 let mut bv = BitVector::with_capacity(128);
3003 bv = !bv; //should do nothing
3004 bv.push_u8(0b0000_0101, None);
3005 assert_eq!(bv.len(), 3);
3006
3007 bv = !bv;
3008 assert_eq!(bv.len(), 3);
3009 assert_eq!(bv.read_u8(0), (0b0000_0010, 3));
3010
3011 bv = !bv;
3012 assert_eq!(bv.len(), 3);
3013 assert_eq!(bv.read_u8(0), (0b0000_0101, 3));
3014 }
3015
3016 #[test]
3017 fn test_bit_xor() {
3018 let mut bv = BitVector::with_capacity(128);
3019 bv.push_u8(0b0000_0101, None);
3020 assert_eq!(bv.len(), 3);
3021
3022 let bv2 = bv ^ true;
3023 assert_eq!(bv2.len(), 3);
3024 assert_eq!(bv2.read_u8(0), (0b0000_0010, 3));
3025
3026 let bv3 = bv2 ^ false;
3027 assert_eq!(bv3.len(), 3);
3028 assert_eq!(bv3.read_u8(0), (0b0000_0010, 3));
3029
3030 let bv4 = bv3 ^ true;
3031 assert_eq!(bv4.len(), 3);
3032 assert_eq!(bv4.read_u8(0), (0b0000_0101, 3));
3033 }
3034
3035 #[test]
3036 fn test_bit_xor_assign() {
3037 let mut bv = BitVector::with_capacity(128);
3038 bv ^= false; // should do nothing
3039 bv.push_u8(0b0000_0101, None);
3040 assert_eq!(bv.len(), 3);
3041
3042 bv ^= true;
3043 assert_eq!(bv.len(), 3);
3044 assert_eq!(bv.read_u8(0), (0b0000_0010, 3));
3045
3046 bv ^= false;
3047 assert_eq!(bv.len(), 3);
3048 assert_eq!(bv.read_u8(0), (0b0000_0010, 3));
3049
3050 bv ^= true;
3051 assert_eq!(bv.len(), 3);
3052 assert_eq!(bv.read_u8(0), (0b0000_0101, 3));
3053
3054 bv.clear();
3055 bv.push_u16(0b1001_0011_0101_1010, Some(16));
3056 bv.push_u8(0b0000_0101, None);
3057 assert_eq!(bv.len(), 19);
3058 bv ^= true;
3059 assert_eq!(bv.read_u16(0), (0b0110_1100_1010_0101, 16));
3060 assert_eq!(bv.read_u8(16), (0b0000_0010, 3));
3061
3062 bv ^= false;
3063 assert_eq!(bv.read_u16(0), (0b0110_1100_1010_0101, 16));
3064 assert_eq!(bv.read_u8(16), (0b0000_0010, 3));
3065 bv ^= true;
3066 assert_eq!(bv.read_u16(0), (0b1001_0011_0101_1010, 16));
3067 assert_eq!(bv.read_u8(16), (0b0000_0101, 3));
3068 }
3069
3070 #[test]
3071 fn test_last_byte_cleared() {
3072 let mut bv = BitVector::with_capacity(128);
3073 bv.push_u8(0b1101_0110, None);
3074 bv.push_u8(0b0000_1001, None);
3075
3076 assert_eq!(bv.len(), 12);
3077 let raw_slice = bv.as_raw_slice();
3078 let last_byte = raw_slice[raw_slice.len() - 1];
3079 assert_eq!(last_byte, 0b1001_0000);
3080
3081 bv |= true;
3082 let raw_slice = bv.as_raw_slice();
3083 let last_byte = raw_slice[raw_slice.len() - 1];
3084 assert_eq!(last_byte, 0b1111_0000);
3085 }
3086
3087 #[test]
3088 fn test_bit_and_slice() {
3089 let mut bv = BitVector::with_capacity(128);
3090 bv.push_u16(0b1011_0101_0011_1100, Some(16));
3091 assert_eq!(bv.len(), 16);
3092 let mut bv2 = BitVector::with_capacity(8);
3093 bv2.push_u8(0b1100_0011, Some(8));
3094
3095 let s = &bv2[..];
3096 assert_eq!(s.len(), 8);
3097 bv = bv & s;
3098 assert_eq!(bv.len(), 16);
3099 assert_eq!(bv.read_u16(0), (0b1000_0001_0011_1100, 16));
3100
3101 bv.clear();
3102 bv.push_u16(0b1011_0101_0011_1100, Some(16));
3103 bv2.push_u8(0b1111_0011, None);
3104 let s = &bv2[..];
3105 assert_eq!(s.len(), 16);
3106 bv = bv & s;
3107 assert_eq!(bv.len(), 16);
3108 assert_eq!(bv.read_u16(0), (0b1000_0001_0011_0000, 16));
3109 bv &= &bv2;
3110 }
3111
3112 #[test]
3113 #[should_panic(expected = "start index 19 out of range for length 16")]
3114 fn test_read_bounds() {
3115 let mut bv = BitVector::with_capacity(128);
3116 bv.push_u16(0b1011_0101_0011_1100, Some(16));
3117 bv.read_u8(19);
3118 }
3119
3120 #[test]
3121 #[should_panic(expected = "start index 19 out of range for length 16")]
3122 fn test_read_bits_bounds_exceeds() {
3123 let mut bv = BitVector::with_capacity(128);
3124 bv.push_u16(0b1011_0101_0011_1100, Some(16));
3125 bv.read_bits_u8(19, 5);
3126 }
3127
3128 #[test]
3129 #[should_panic(expected = "start index 16 out of range for length 16")]
3130 fn test_read_bits_bounds_equals() {
3131 let mut bv = BitVector::with_capacity(128);
3132 bv.push_u16(0b1011_0101_0011_1100, Some(16));
3133 bv.read_bits_u8(16, 5);
3134 }
3135
3136 #[test]
3137 fn test_append() {
3138 let mut bv = BitVector::with_capacity(128);
3139 bv.push_u8(0b1011_0101, Some(8));
3140 let mut other = BitVector::with_capacity(128);
3141 other.push_u16(0b1011_0101_0011_1100, Some(16));
3142 other.push_u16(0b1111_1111_1111_1111, Some(16));
3143 other.push_u16(0b0000_0000_0000_0000, Some(16));
3144 assert_eq!(bv.len(), 8);
3145 assert_eq!(other.len(), 48);
3146 bv.append(&mut other);
3147 assert_eq!(bv.len(), 56);
3148 assert_eq!(other.len(), 0);
3149 assert_eq!(bv.read_u8(0), (0b1011_0101, 8));
3150 assert_eq!(bv.read_u16(8), (0b1011_0101_0011_1100, 16));
3151 assert_eq!(bv.read_u16(24), (0b1111_1111_1111_1111, 16));
3152 assert_eq!(bv.read_u16(40), (0b0000_0000_0000_0000, 16));
3153 }
3154
3155 #[test]
3156 fn test_extend_from_bitslice() {
3157 let mut bv = BitVector::with_capacity(128);
3158 bv.push_u8(0b1011_0101, Some(8));
3159 let mut bv2 = BitVector::with_capacity(128);
3160 bv2.push_u16(0b1011_0101_0011_1100, Some(16));
3161 bv2.push_u16(0b1111_1111_1111_1111, Some(16));
3162 bv2.push_u16(0b0000_0000_0000_0000, Some(16));
3163 let other = &bv2[..];
3164 assert_eq!(bv.len(), 8);
3165 assert_eq!(other.len(), 48);
3166 bv.extend_from_bitslice(other);
3167 assert_eq!(bv.len(), 56);
3168 assert_eq!(other.len(), 48);
3169 assert_eq!(bv.read_u8(0), (0b1011_0101, 8));
3170 assert_eq!(bv.read_u16(8), (0b1011_0101_0011_1100, 16));
3171 assert_eq!(bv.read_u16(24), (0b1111_1111_1111_1111, 16));
3172 assert_eq!(bv.read_u16(40), (0b0000_0000_0000_0000, 16));
3173 }
3174
3175 #[test]
3176 fn test_from_bitslice() {
3177 let mut bv2 = BitVector::with_capacity(128);
3178 bv2.push_u16(0b1011_0101_0011_1100, Some(16));
3179 bv2.push_u16(0b1111_1111_1111_1111, Some(16));
3180 bv2.push_u16(0b0000_0000_0000_0000, Some(16));
3181 let slice = &bv2[..];
3182 assert_eq!(slice.len(), 48);
3183 let bv = BitVector::from_bitslice(slice);
3184 assert_eq!(bv.len(), 48);
3185 assert_eq!(slice.len(), 48);
3186 assert_eq!(bv.read_u16(0), (0b1011_0101_0011_1100, 16));
3187 assert_eq!(bv.read_u16(16), (0b1111_1111_1111_1111, 16));
3188 assert_eq!(bv.read_u16(32), (0b0000_0000_0000_0000, 16));
3189 }
3190
3191 #[test]
3192 fn test_repeat() {
3193 let bv = BitVector::repeat(false, 48);
3194 assert_eq!(bv.read_u16(0), (0b0000_0000_0000_0000, 16));
3195 assert_eq!(bv.read_u16(16), (0b0000_0000_0000_0000, 16));
3196 assert_eq!(bv.read_u16(32), (0b0000_0000_0000_0000, 16));
3197 }
3198
3199 #[test]
3200 fn test_truncate_3() {
3201 //
3202 let mut bv = BitVector::repeat(false, 48);
3203 assert_eq!(bv.read_u16(0), (0b0000_0000_0000_0000, 16));
3204 assert_eq!(bv.read_u16(16), (0b0000_0000_0000_0000, 16));
3205 assert_eq!(bv.read_u16(32), (0b0000_0000_0000_0000, 16));
3206 bv.truncate(3);
3207 assert_eq!(bv.len(), 3);
3208 }
3209
3210 #[test]
3211 fn test_truncate_0() {
3212 let mut bv = BitVector::repeat(false, 48);
3213 assert_eq!(bv.read_u16(0), (0b0000_0000_0000_0000, 16));
3214 assert_eq!(bv.read_u16(16), (0b0000_0000_0000_0000, 16));
3215 assert_eq!(bv.read_u16(32), (0b0000_0000_0000_0000, 16));
3216 bv.truncate(0);
3217 assert_eq!(bv.len(), 0);
3218 }
3219
3220 #[test]
3221 fn test_truncate_greater() {
3222 let mut bv = BitVector::repeat(false, 48);
3223 assert_eq!(bv.read_u16(0), (0b0000_0000_0000_0000, 16));
3224 assert_eq!(bv.read_u16(16), (0b0000_0000_0000_0000, 16));
3225 assert_eq!(bv.read_u16(32), (0b0000_0000_0000_0000, 16));
3226 bv.truncate(100);
3227 assert_eq!(bv.len(), 48);
3228 }
3229
3230 #[test]
3231 fn test_truncate_16() {
3232 let mut bv = BitVector::repeat(false, 48);
3233 assert_eq!(bv.read_u16(0), (0b0000_0000_0000_0000, 16));
3234 assert_eq!(bv.read_u16(16), (0b0000_0000_0000_0000, 16));
3235 assert_eq!(bv.read_u16(32), (0b0000_0000_0000_0000, 16));
3236 bv.truncate(16);
3237 assert_eq!(bv.len(), 16);
3238 }
3239
3240 #[test]
3241 fn test_truncate_48() {
3242 let mut bv = BitVector::repeat(false, 48);
3243 assert_eq!(bv.read_u16(0), (0b0000_0000_0000_0000, 16));
3244 assert_eq!(bv.read_u16(16), (0b0000_0000_0000_0000, 16));
3245 assert_eq!(bv.read_u16(32), (0b0000_0000_0000_0000, 16));
3246 bv.truncate(48);
3247 assert_eq!(bv.len(), 48);
3248 }
3249
3250 #[test]
3251 fn test_bitvec_macro() {
3252 let bv = bitvector!();
3253 assert_eq!(bv.len(), 0);
3254 let bv = bitvector![1, 0, 1, 1];
3255 assert_eq!(bv.len(), 4);
3256 assert_eq!(bv.read_u8(0), (0b1011, 4));
3257 let bv = bitvector![1;100];
3258 assert_eq!(bv.len(), 100);
3259 assert_eq!(bv.read_u64(0), (u64::MAX, 64));
3260 assert_eq!(bv.read_u32(64), (u32::MAX, 32));
3261 assert_eq!(bv.read_u8(96), (0b1111, 4));
3262 }
3263
3264 #[test]
3265 fn test_iter_mut() {
3266 let mut bv = BitVector::with_capacity(20);
3267 bv.push_u8(0b1011_1100, Some(8));
3268 bv.push_u8(0b0011_1001, Some(8));
3269 let iter = bv.iter_mut();
3270 for mut bit in iter {
3271 *bit = true;
3272 }
3273
3274 assert_eq!(bv.read_u8(0), (0b1111_1111, 8));
3275 assert_eq!(bv.read_u8(8), (0b1111_1111, 8));
3276 for mut bit in bv.iter_mut() {
3277 *bit = false;
3278 }
3279 assert_eq!(bv.read_u8(0), (0b0000_0000, 8));
3280 assert_eq!(bv.read_u8(8), (0b0000_0000, 8));
3281 }
3282
3283 #[test]
3284 fn test_first() {
3285 let mut bv = BitVector::with_capacity(20);
3286 assert_eq!(bv.first(), None);
3287
3288 bv.push_u8(0b1011_1100, None);
3289 assert_eq!(bv[0], true);
3290 assert_eq!(*(bv.first().unwrap()), true);
3291 assert_eq!(bv.first().as_deref(), Some(&true));
3292 }
3293
3294 #[test]
3295 fn test_first_mut() {
3296 let mut bv = BitVector::with_capacity(20);
3297 assert_eq!(bv.first_mut(), None);
3298 bv.push_u8(0b1011_1100, None);
3299 assert_eq!(bv[0], true);
3300 assert_eq!(*(bv.first_mut().unwrap()), true);
3301 *bv.first_mut().unwrap() = false;
3302 assert_eq!(*(bv.first_mut().unwrap()), false);
3303 assert_eq!(bv.first().as_deref(), Some(&false));
3304 assert_eq!(bv[0], false);
3305 }
3306
3307 #[test]
3308 fn test_last() {
3309 let mut bv = BitVector::with_capacity(20);
3310 bv.push_u8(0b1011_1100, None);
3311 assert_eq!(bv[7], false);
3312 assert_eq!(*(bv.last().unwrap()), false);
3313 assert_eq!(bv.last().as_deref(), Some(&false));
3314 assert_eq!(bv[7], false);
3315 }
3316
3317 #[test]
3318 fn test_last_mut() {
3319 let mut bv = BitVector::with_capacity(20);
3320 bv.push_u8(0b0000_0000, Some(8));
3321 assert_eq!(bv[7], false);
3322 assert_eq!(*(bv.last_mut().unwrap()), false);
3323 *bv.last_mut().unwrap() = true;
3324 assert_eq!(*(bv.last().unwrap()), true);
3325 assert_eq!(bv.last().as_deref(), Some(&true));
3326 assert_eq!(bv[7], true);
3327 }
3328
3329 #[test]
3330 fn test_count_ones() {
3331 let bv = BitVector::new();
3332 assert_eq!(bv.count_ones(0), 0);
3333 }
3334
3335 #[test]
3336 fn test_count_zeros() {
3337 let bv = BitVector::new();
3338 assert_eq!(bv.count_zeros(0), 0);
3339 }
3340}