Coverage Report

Created: 2025-10-10 06:41

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/bitvec-1.0.1/src/vec/api.rs
Line
Count
Source
1
//! Port of the `Vec<bool>` inherent API.
2
3
use alloc::vec::Vec;
4
use core::{
5
  mem::ManuallyDrop,
6
  ops::RangeBounds,
7
};
8
9
use tap::Pipe;
10
use wyz::{
11
  comu::{
12
    Const,
13
    Mut,
14
  },
15
  range::RangeExt,
16
};
17
18
use super::{
19
  BitVec,
20
  Drain,
21
  Splice,
22
};
23
use crate::{
24
  boxed::BitBox,
25
  index::BitEnd,
26
  mem,
27
  order::BitOrder,
28
  ptr::{
29
    AddressExt,
30
    BitPtr,
31
    BitSpan,
32
  },
33
  slice::BitSlice,
34
  store::BitStore,
35
};
36
37
/// Port of the `Vec<T>` inherent API.
38
impl<T, O> BitVec<T, O>
39
where
40
  T: BitStore,
41
  O: BitOrder,
42
{
43
  /// Constructs a new, empty, bit-vector.
44
  ///
45
  /// This does not allocate until bits are [`.push()`]ed into it, or space is
46
  /// explicitly [`.reserve()`]d.
47
  ///
48
  /// ## Original
49
  ///
50
  /// [`Vec::new`](alloc::vec::Vec::new)
51
  ///
52
  /// ## Examples
53
  ///
54
  /// ```rust
55
  /// use bitvec::prelude::*;
56
  ///
57
  /// let bv = BitVec::<u8, Msb0>::new();
58
  /// assert!(bv.is_empty());
59
  /// ```
60
  ///
61
  /// [`.push()`]: Self::push
62
  /// [`.reserve()`]: Self::reserve
63
  #[inline]
64
0
  pub fn new() -> Self {
65
0
    Self::EMPTY
66
0
  }
67
68
  /// Allocates a new, empty, bit-vector with space for at least `capacity`
69
  /// bits before reallocating.
70
  ///
71
  /// ## Original
72
  ///
73
  /// [`Vec::with_capacity`](alloc::vec::Vec::with_capacity)
74
  ///
75
  /// ## Panics
76
  ///
77
  /// This panics if the requested capacity is longer than what the bit-vector
78
  /// can represent. See [`BitSlice::MAX_BITS`].
79
  ///
80
  /// ## Examples
81
  ///
82
  /// ```rust
83
  /// use bitvec::prelude::*;
84
  ///
85
  /// let mut bv: BitVec = BitVec::with_capacity(128);
86
  ///
87
  /// assert!(bv.is_empty());
88
  /// assert!(bv.capacity() >= 128);
89
  ///
90
  /// for i in 0 .. 128 {
91
  ///   bv.push(i & 0xC0 == i);
92
  /// }
93
  /// assert_eq!(bv.len(), 128);
94
  /// assert!(bv.capacity() >= 128);
95
  ///
96
  /// bv.push(false);
97
  /// assert_eq!(bv.len(), 129);
98
  /// assert!(bv.capacity() >= 129);
99
  /// ```
100
  ///
101
  /// [`BitSlice::MAX_BITS`]: crate::slice::BitSlice::MAX_BITS
102
  #[inline]
103
0
  pub fn with_capacity(capacity: usize) -> Self {
104
0
    Self::assert_len_encodable(capacity);
105
0
    let mut vec = capacity
106
0
      .pipe(crate::mem::elts::<T>)
107
0
      .pipe(Vec::<T>::with_capacity)
108
0
      .pipe(ManuallyDrop::new);
109
0
    let (addr, capacity) = (vec.as_mut_ptr(), vec.capacity());
110
0
    let bitspan = BitSpan::uninhabited(unsafe { addr.into_address() });
111
0
    Self { bitspan, capacity }
112
0
  }
113
114
  /// Constructs a bit-vector handle from its constituent fields.
115
  ///
116
  /// ## Original
117
  ///
118
  /// [`Vec::from_raw_parts`](alloc::vec::Vec::from_raw_parts)
119
  ///
120
  /// ## Safety
121
  ///
122
  /// The **only** acceptable argument values for this function are those that
123
  /// were previously produced by calling [`.into_raw_parts()`]. Furthermore,
124
  /// you may only call this **at most once** on any set of arguments. Using
125
  /// the same arguments in more than one call to this function will result in
126
  /// a double- or use-after free error.
127
  ///
128
  /// Attempting to conjure your own values and pass them into this function
129
  /// will break the allocator state.
130
  ///
131
  /// ## Examples
132
  ///
133
  /// ```rust
134
  /// use bitvec::prelude::*;
135
  ///
136
  /// let bv = bitvec![0, 1, 0, 0, 1];
137
  /// let (bitptr, len, capa) = bv.into_raw_parts();
138
  /// let bv2 = unsafe {
139
  ///   BitVec::from_raw_parts(bitptr, len, capa)
140
  /// };
141
  /// assert_eq!(bv2, bits![0, 1, 0, 0, 1]);
142
  /// ```
143
  ///
144
  /// [`.into_raw_parts()`]: Self::into_raw_parts
145
  #[inline]
146
0
  pub unsafe fn from_raw_parts(
147
0
    bitptr: BitPtr<Mut, T, O>,
148
0
    length: usize,
149
0
    capacity: usize,
150
0
  ) -> Self {
151
0
    let bitspan = bitptr.span_unchecked(length);
152
0
    Self {
153
0
      bitspan,
154
0
      capacity: mem::elts::<T>(
155
0
        capacity.saturating_add(bitspan.head().into_inner() as usize),
156
0
      ),
157
0
    }
158
0
  }
159
160
  /// Decomposes a bit-vector into its constituent member fields.
161
  ///
162
  /// This disarms the destructor. In order to prevent a memory leak, you must
163
  /// pass **these exact values** back into [`::from_raw_parts()`].
164
  ///
165
  /// ## Original
166
  ///
167
  /// [`Vec::into_raw_parts`](alloc::vec::Vec::into_raw_parts)
168
  ///
169
  /// ## API Differences
170
  ///
171
  /// This method is still unstable as of 1.54. It is provided here as a
172
  /// convenience, under the expectation that the standard-library method will
173
  /// stabilize as-is.
174
  ///
175
  /// [`::from_raw_parts()`]: Self::from_raw_parts
176
  #[inline]
177
0
  pub fn into_raw_parts(self) -> (BitPtr<Mut, T, O>, usize, usize) {
178
0
    let this = ManuallyDrop::new(self);
179
0
    (
180
0
      this.bitspan.to_bitptr(),
181
0
      this.bitspan.len(),
182
0
      this.capacity(),
183
0
    )
184
0
  }
185
186
  /// Gets the allocation capacity, measured in bits.
187
  ///
188
  /// This counts how many total bits the bit-vector can store before it must
189
  /// perform a reällocation to acquire more memory.
190
  ///
191
  /// If the capacity is not a multiple of 8, you should call
192
  /// [`.force_align()`].
193
  ///
194
  /// ## Original
195
  ///
196
  /// [`Vec::capacity`](alloc::vec::Vec::capacity)
197
  ///
198
  /// ## Examples
199
  ///
200
  /// ```rust
201
  /// use bitvec::prelude::*;
202
  ///
203
  /// let bv = bitvec![0, 1, 0, 0, 1];
204
  /// ```
205
  ///
206
  /// [`.force_align()`]: Self::force_align
207
  #[inline]
208
0
  pub fn capacity(&self) -> usize {
209
0
    self.capacity
210
0
      .checked_mul(mem::bits_of::<T>())
211
0
      .expect("bit-vector capacity exceeded")
212
0
      .saturating_sub(self.bitspan.head().into_inner() as usize)
213
0
  }
214
215
  /// Ensures that the bit-vector has allocation capacity for *at least*
216
  /// `additional` more bits to be appended to it.
217
  ///
218
  /// For convenience, this method *guarantees* that the underlying memory for
219
  /// `self[.. self.len() + additional]` is initialized, and may be safely
220
  /// accessed directly without requiring use of `.push()` or `.extend()` to
221
  /// initialize it.
222
  ///
223
  /// Newly-allocated memory is always initialized to zero. It is still *dead*
224
  /// until the bit-vector is grown (by `.push()`, `.extend()`, or
225
  /// `.set_len()`), but direct access will not trigger UB.
226
  ///
227
  /// ## Original
228
  ///
229
  /// [`Vec::reserve`](alloc::vec::Vec::reserve)
230
  ///
231
  /// ## Panics
232
  ///
233
  /// This panics if the new capacity exceeds the bit-vector’s maximum.
234
  ///
235
  /// ## Examples
236
  ///
237
  /// ```rust
238
  /// use bitvec::prelude::*;
239
  ///
240
  /// let mut bv: BitVec = BitVec::with_capacity(80);
241
  /// assert!(bv.capacity() >= 80);
242
  /// bv.reserve(800);
243
  /// assert!(bv.capacity() >= 800);
244
  /// ```
245
  #[inline]
246
0
  pub fn reserve(&mut self, additional: usize) {
247
0
    Self::assert_len_encodable(self.len() + additional);
248
0
    self.do_reservation(additional, Vec::<T>::reserve);
249
0
  }
250
251
  /// Ensures that the bit-vector has allocation capacity for *at least*
252
  /// `additional` more bits to be appended to it.
253
  ///
254
  /// This differs from [`.reserve()`] by requesting that the allocator
255
  /// provide the minimum capacity necessary, rather than a potentially larger
256
  /// amount that the allocator may find more convenient.
257
  ///
258
  /// Remember that this is a *request*: the allocator provides what it
259
  /// provides, and you cannot rely on the new capacity to be exactly minimal.
260
  /// You should still prefer `.reserve()`, especially if you expect to append
261
  /// to the bit-vector in the future.
262
  ///
263
  /// ## Original
264
  ///
265
  /// [`Vec::reserve_exact`](alloc::vec::Vec::reserve_exact)
266
  ///
267
  /// ## Panics
268
  ///
269
  /// This panics if the new capacity exceeds the bit-vector’s maximum.
270
  ///
271
  /// ## Examples
272
  ///
273
  /// ```rust
274
  /// use bitvec::prelude::*;
275
  ///
276
  /// let mut bv: BitVec = BitVec::with_capacity(80);
277
  /// assert!(bv.capacity() >= 80);
278
  /// bv.reserve_exact(800);
279
  /// assert!(bv.capacity() >= 800);
280
  /// ```
281
  ///
282
  /// [`.reserve()`]: Self::reserve
283
  #[inline]
284
0
  pub fn reserve_exact(&mut self, additional: usize) {
285
0
    self.do_reservation(additional, Vec::<T>::reserve_exact);
286
0
  }
287
288
  /// Releases excess capacity back to the allocator.
289
  ///
290
  /// Like [`.reserve_exact()`], this is a *request* to the allocator, not a
291
  /// command. The allocator may reclaim excess memory or may not.
292
  ///
293
  /// ## Original
294
  ///
295
  /// [`Vec::shrink_to_fit`](alloc::vec::Vec::shrink_to_fit)
296
  ///
297
  /// ## Examples
298
  ///
299
  /// ```rust
300
  /// use bitvec::prelude::*;
301
  ///
302
  /// let mut bv: BitVec = BitVec::with_capacity(1000);
303
  /// bv.push(true);
304
  /// bv.shrink_to_fit();
305
  /// ```
306
  ///
307
  /// [`.reserve_exact()`]: Self::reserve_exact
308
  #[inline]
309
0
  pub fn shrink_to_fit(&mut self) {
310
0
    self.with_vec(|vec| vec.shrink_to_fit());
311
0
  }
312
313
  #[inline]
314
  #[cfg(not(tarpaulin_include))]
315
  #[deprecated = "prefer `.into_boxed_bitslice() instead"]
316
  #[allow(missing_docs, clippy::missing_docs_in_private_items)]
317
0
  pub fn into_boxed_slice(self) -> BitBox<T, O> {
318
0
    self.into_boxed_bitslice()
319
0
  }
320
321
  /// Shortens the bit-vector, keeping the first `new_len` bits and discarding
322
  /// the rest.
323
  ///
324
  /// If `len` is greater than the bit-vector’s current length, this has no
325
  /// effect.
326
  ///
327
  /// The [`.drain()`] method can emulate `.truncate()`, except that it yields
328
  /// the excess bits rather than discarding them.
329
  ///
330
  /// Note that this has no effect on the allocated capacity of the
331
  /// bit-vector, **nor does it erase truncated memory**. Bits in the
332
  /// allocated memory that are outside of the [`.as_bitslice()`] view are
333
  /// always considered to have *initialized*, but **unspecified**, values,
334
  /// and you cannot rely on them to be zero.
335
  ///
336
  /// ## Original
337
  ///
338
  /// [`Vec::truncate`](alloc::vec::Vec::truncate)
339
  ///
340
  /// ## Examples
341
  ///
342
  /// Truncating a five-bit vector to two bits:
343
  ///
344
  /// ```rust
345
  /// use bitvec::prelude::*;
346
  ///
347
  /// let mut bv = bitvec![0, 1, 0, 0, 1];
348
  /// bv.truncate(2);
349
  /// assert_eq!(bv.len(), 2);
350
  /// assert!(bv.as_raw_slice()[0].count_ones() >= 2);
351
  /// ```
352
  ///
353
  /// No truncation occurs when `len` is greater than the bit-vector’s current
354
  /// length:
355
  ///
356
  /// [`.as_bitslice()`]: Self::as_bitslice
357
  /// [`.drain()`]: Self::drain
358
  #[inline]
359
0
  pub fn truncate(&mut self, new_len: usize) {
360
0
    if new_len < self.len() {
361
0
      unsafe {
362
0
        self.set_len_unchecked(new_len);
363
0
      }
364
0
    }
365
0
  }
366
367
  #[inline]
368
  #[cfg(not(tarpaulin_include))]
369
  #[deprecated = "use `.as_bitslice()` instead"]
370
  #[allow(missing_docs, clippy::missing_docs_in_private_items)]
371
0
  pub fn as_slice(&self) -> &BitSlice<T, O> {
372
0
    self.as_bitslice()
373
0
  }
374
375
  #[inline]
376
  #[cfg(not(tarpaulin_include))]
377
  #[deprecated = "use `.as_mut_bitslice()` instead"]
378
  #[allow(missing_docs, clippy::missing_docs_in_private_items)]
379
0
  pub fn as_mut_slice(&mut self) -> &mut BitSlice<T, O> {
380
0
    self.as_mut_bitslice()
381
0
  }
382
383
  #[inline]
384
  #[cfg(not(tarpaulin_include))]
385
  #[deprecated = "use `.as_bitptr()` instead"]
386
  #[allow(missing_docs, clippy::missing_docs_in_private_items)]
387
0
  pub fn as_ptr(&self) -> BitPtr<Const, T, O> {
388
0
    self.as_bitptr()
389
0
  }
390
391
  #[inline]
392
  #[cfg(not(tarpaulin_include))]
393
  #[deprecated = "use `.as_mut_bitptr()` instead"]
394
  #[allow(missing_docs, clippy::missing_docs_in_private_items)]
395
0
  pub fn as_mut_ptr(&mut self) -> BitPtr<Mut, T, O> {
396
0
    self.as_mut_bitptr()
397
0
  }
398
399
  /// Resizes a bit-vector to a new length.
400
  ///
401
  /// ## Original
402
  ///
403
  /// [`Vec::set_len`](alloc::vec::Vec::set_len)
404
  ///
405
  /// ## Safety
406
  ///
407
  /// **NOT ALL MEMORY IN THE ALLOCATION IS INITIALIZED!**
408
  ///
409
  /// Memory in a bit-vector’s allocation is only initialized when the
410
  /// bit-vector grows into it normally (through [`.push()`] or one of the
411
  /// various `.extend*()` methods). Setting the length to a value beyond what
412
  /// was previously initialized, but still within the allocation, is
413
  /// undefined behavior.
414
  ///
415
  /// The caller is responsible for ensuring that all memory up to (but not
416
  /// including) the new length has already been initialized.
417
  ///
418
  /// ## Panics
419
  ///
420
  /// This panics if `new_len` exceeds the capacity as reported by
421
  /// [`.capacity()`].
422
  ///
423
  /// ## Examples
424
  ///
425
  /// ```rust
426
  /// use bitvec::prelude::*;
427
  ///
428
  /// let mut bv = bitvec![0, 1, 0, 0, 1];
429
  /// unsafe {
430
  ///   // The default storage type, `usize`, is at least 32 bits.
431
  ///   bv.set_len(32);
432
  /// }
433
  /// assert_eq!(bv, bits![
434
  ///   0, 1, 0, 0, 1, 0, 0, 0,
435
  ///   0, 0, 0, 0, 0, 0, 0, 0,
436
  ///   0, 0, 0, 0, 0, 0, 0, 0,
437
  ///   0, 0, 0, 0, 0, 0, 0, 0,
438
  /// ]);
439
  /// //  `BitVec` guarantees that newly-initialized memory is zeroed.
440
  /// ```
441
  ///
442
  /// [`.push()`]: Self::push
443
  /// [`.capacity()`]: Self::capacity
444
  #[inline]
445
0
  pub unsafe fn set_len(&mut self, new_len: usize) {
446
0
    let capa = self.capacity();
447
0
    assert!(
448
0
      new_len <= capa,
449
0
      "bit-vector capacity exceeded: {} > {}",
450
      new_len,
451
      capa,
452
    );
453
0
    self.set_len_unchecked(new_len);
454
0
  }
455
456
  /// Takes a bit out of the bit-vector.
457
  ///
458
  /// The empty slot is filled with the last bit in the bit-vector, rather
459
  /// than shunting `index + 1 .. self.len()` down by one.
460
  ///
461
  /// ## Original
462
  ///
463
  /// [`Vec::swap_remove`](alloc::vec::Vec::swap_remove)
464
  ///
465
  /// ## Panics
466
  ///
467
  /// This panics if `index` is out of bounds (`self.len()` or greater).
468
  ///
469
  /// ## Examples
470
  ///
471
  /// ```rust
472
  /// use bitvec::prelude::*;
473
  ///
474
  /// let mut bv = bitvec![0, 1, 0, 0, 1];
475
  /// assert!(!bv.swap_remove(2));
476
  /// assert_eq!(bv, bits![0, 1, 1, 0]);
477
  /// ```
478
  #[inline]
479
0
  pub fn swap_remove(&mut self, index: usize) -> bool {
480
0
    self.assert_in_bounds(index, 0 .. self.len());
481
0
    let last = self.len() - 1;
482
    unsafe {
483
0
      self.swap_unchecked(index, last);
484
0
      self.set_len(last);
485
0
      *self.get_unchecked(last)
486
    }
487
0
  }
488
489
  /// Inserts a bit at a given position, shifting all bits after it one spot
490
  /// to the right.
491
  ///
492
  /// `index` may be any value up to *and including* `self.len()`. If it is
493
  /// `self.len()`, it behaves equivalently to `.push()`.
494
  ///
495
  /// ## Original
496
  ///
497
  /// [`Vec::insert`](alloc::vec::Vec::insert)
498
  ///
499
  /// ## Panics
500
  ///
501
  /// This panics if `index` is out of bounds (including `self.len()`).
502
  #[inline]
503
0
  pub fn insert(&mut self, index: usize, value: bool) {
504
0
    self.assert_in_bounds(index, 0 ..= self.len());
505
0
    self.push(value);
506
0
    unsafe { self.get_unchecked_mut(index ..) }.rotate_right(1);
507
0
  }
508
509
  /// Removes a bit at a given position, shifting all bits after it one spot
510
  /// to the left.
511
  ///
512
  /// `index` may be any value up to, but **not** including, `self.len()`.
513
  ///
514
  /// ## Original
515
  ///
516
  /// [`Vec::remove`](alloc::vec::Vec::remove)
517
  ///
518
  /// ## Panics
519
  ///
520
  /// This panics if `index` is out of bounds (excluding `self.len()`).
521
  #[inline]
522
0
  pub fn remove(&mut self, index: usize) -> bool {
523
0
    self.assert_in_bounds(index, 0 .. self.len());
524
0
    let last = self.len() - 1;
525
    unsafe {
526
0
      self.get_unchecked_mut(index ..).rotate_left(1);
527
0
      let out = *self.get_unchecked(last);
528
0
      self.set_len(last);
529
0
      out
530
    }
531
0
  }
532
533
  /// Retains only the bits that the predicate allows.
534
  ///
535
  /// Bits are deleted from the vector when the predicate function returns
536
  /// false. This function is linear in `self.len()`.
537
  ///
538
  /// ## Original
539
  ///
540
  /// [`Vec::retain`](alloc::vec::Vec::retain)
541
  ///
542
  /// ## API Differences
543
  ///
544
  /// The predicate receives both the index of the bit as well as its value,
545
  /// in order to allow the predicate to have more than one bit of
546
  /// keep/discard information.
547
  ///
548
  /// ## Examples
549
  ///
550
  /// ```rust
551
  /// use bitvec::prelude::*;
552
  ///
553
  /// let mut bv = bitvec![0, 1, 0, 0, 1];
554
  /// bv.retain(|idx, _| idx % 2 == 0);
555
  /// assert_eq!(bv, bits![0,    0,    1]);
556
  /// ```
557
  #[inline]
558
0
  pub fn retain<F>(&mut self, mut func: F)
559
0
  where F: FnMut(usize, &bool) -> bool {
560
0
    let mut len = self.len();
561
0
    let mut hole_ptr = self.as_mut_bitptr();
562
0
    let mut reader = self.as_bitptr_range().enumerate();
563
564
    //  Advance until the *first* hole is created. This avoids writing into
565
    //  the bit-slice when no change takes place.
566
0
    for (idx, bitptr) in reader.by_ref() {
567
0
      let bit = unsafe { bitptr.read() };
568
0
      if func(idx, &bit) {
569
0
        hole_ptr = unsafe { hole_ptr.add(1) };
570
0
      }
571
      else {
572
0
        len -= 1;
573
0
        break;
574
      }
575
    }
576
    //  Now that a hole exists, switch to a loop that always writes into the
577
    //  hole pointer.
578
0
    for (idx, bitptr) in reader {
579
0
      let bit = unsafe { bitptr.read() };
580
0
      if func(idx, &bit) {
581
0
        hole_ptr = unsafe {
582
0
          hole_ptr.write(bit);
583
0
          hole_ptr.add(1)
584
0
        };
585
0
      }
586
0
      else {
587
0
        len -= 1;
588
0
      }
589
    }
590
    //  Discard the bits that did not survive the predicate.
591
0
    unsafe {
592
0
      self.set_len_unchecked(len);
593
0
    }
594
0
  }
595
596
  /// Appends a single bit to the vector.
597
  ///
598
  /// ## Original
599
  ///
600
  /// [`Vec::push`](alloc::vec::Vec::push)
601
  ///
602
  /// ## Panics
603
  ///
604
  /// This panics if the push would cause the bit-vector to exceed its maximum
605
  /// capacity.
606
  ///
607
  /// ## Examples
608
  ///
609
  /// ```rust
610
  /// use bitvec::prelude::*;
611
  ///
612
  /// let mut bv = bitvec![0, 0];
613
  /// bv.push(true);
614
  /// assert_eq!(bv.as_bitslice(), bits![0, 0, 1]);
615
  /// ```
616
  #[inline]
617
0
  pub fn push(&mut self, value: bool) {
618
0
    let len = self.len();
619
0
    let new_len = len + 1;
620
0
    Self::assert_len_encodable(new_len);
621
    //  Push a new `T` into the underlying buffer if needed.
622
0
    if len == 0 || self.bitspan.tail() == BitEnd::MAX {
623
0
      self.with_vec(|vec| vec.push(T::ZERO));
624
0
    }
625
    //  Write `value` into the now-safely-allocated `len` slot.
626
0
    unsafe {
627
0
      self.set_len_unchecked(new_len);
628
0
      self.set_unchecked(len, value);
629
0
    }
630
0
  }
631
632
  /// Attempts to remove the trailing bit from the bit-vector.
633
  ///
634
  /// This returns `None` if the bit-vector is empty.
635
  ///
636
  /// ## Original
637
  ///
638
  /// [`Vec::pop`](alloc::vec::Vec::pop)
639
  ///
640
  /// ## Examples
641
  ///
642
  /// ```rust
643
  /// use bitvec::prelude::*;
644
  ///
645
  /// let mut bv = bitvec![0, 1];
646
  /// assert!(bv.pop().unwrap());
647
  /// assert!(!bv.pop().unwrap());
648
  /// assert!(bv.pop().is_none());
649
  /// ```
650
  #[inline]
651
0
  pub fn pop(&mut self) -> Option<bool> {
652
0
    match self.len() {
653
0
      0 => None,
654
0
      n => unsafe {
655
0
        let new_len = n - 1;
656
0
        let out = Some(*self.get_unchecked(new_len));
657
0
        self.set_len_unchecked(new_len);
658
0
        out
659
      },
660
    }
661
0
  }
662
663
  /// Moves all the bits out of `other` into the back of `self`.
664
  ///
665
  /// The `other` bit-vector is emptied after this occurs.
666
  ///
667
  /// ## Original
668
  ///
669
  /// [`Vec::append`](alloc::vec::Vec::append)
670
  ///
671
  /// ## API Differences
672
  ///
673
  /// This permits `other` to have different type parameters than `self`, and
674
  /// does not require that it be literally `Self`.
675
  ///
676
  /// ## Panics
677
  ///
678
  /// This panics if `self.len() + other.len()` exceeds the maximum capacity
679
  /// of a bit-vector.
680
  ///
681
  /// ## Examples
682
  ///
683
  /// ```rust
684
  /// use bitvec::prelude::*;
685
  ///
686
  /// let mut bv1 = bitvec![u16, Msb0; 0; 10];
687
  /// let mut bv2 = bitvec![u32, Lsb0; 1; 10];
688
  ///
689
  /// bv1.append(&mut bv2);
690
  ///
691
  /// assert_eq!(bv1.count_ones(), 10);
692
  /// assert_eq!(bv1.count_zeros(), 10);
693
  /// assert!(bv2.is_empty());
694
  /// ```
695
  #[inline]
696
0
  pub fn append<T2, O2>(&mut self, other: &mut BitVec<T2, O2>)
697
0
  where
698
0
    T2: BitStore,
699
0
    O2: BitOrder,
700
  {
701
0
    self.extend_from_bitslice(other);
702
0
    other.clear();
703
0
  }
704
705
  /// Iterates over a portion of the bit-vector, *removing* all yielded bits
706
  /// from it.
707
  ///
708
  /// When the iterator drops, *all* bits in its coverage are removed from
709
  /// `self`, even if the iterator did not yield them. If the iterator is
710
  /// leaked or otherwise forgotten, and its destructor never runs, then the
711
  /// amount of un-yielded bits removed from the bit-vector is not specified.
712
  ///
713
  /// ## Original
714
  ///
715
  /// [`Vec::drain`](alloc::vec::Vec::drain)
716
  ///
717
  /// ## Panics
718
  ///
719
  /// This panics if `range` departs `0 .. self.len()`.
720
  ///
721
  /// ## Examples
722
  ///
723
  /// ```rust
724
  /// use bitvec::prelude::*;
725
  ///
726
  /// let mut bv = bitvec![0, 1, 0, 0, 1];
727
  /// let bv2 = bv.drain(1 ..= 3).collect::<BitVec>();
728
  /// assert_eq!(bv, bits![0,          1]);
729
  /// assert_eq!(bv2, bits![1, 0, 0]);
730
  ///
731
  /// // A full range clears the bit-vector.
732
  /// bv.drain(..);
733
  /// assert!(bv.is_empty());
734
  /// ```
735
  #[inline]
736
0
  pub fn drain<R>(&mut self, range: R) -> Drain<T, O>
737
0
  where R: RangeBounds<usize> {
738
0
    Drain::new(self, range)
739
0
  }
740
741
  /// Empties the bit-vector.
742
  ///
743
  /// This does not affect the allocated capacity.
744
  ///
745
  /// ## Original
746
  ///
747
  /// [`Vec::clear`](alloc::vec::Vec::clear)
748
  ///
749
  /// ## Examples
750
  ///
751
  /// ```rust
752
  /// use bitvec::prelude::*;
753
  ///
754
  /// let mut bv = bitvec![0, 1, 0, 0, 1];
755
  /// bv.clear();
756
  /// assert!(bv.is_empty());
757
  /// ```
758
  #[inline]
759
0
  pub fn clear(&mut self) {
760
0
    self.truncate(0);
761
0
  }
762
763
  /// Gets the length of the bit-vector.
764
  ///
765
  /// This is equivalent to `BitSlice::len`; it is provided as an inherent
766
  /// method here rather than relying on `Deref` forwarding so that you can
767
  /// write `BitVec::len` as a named function item.
768
  ///
769
  /// ## Original
770
  ///
771
  /// [`Vec::len`](alloc::vec::Vec::len)
772
  #[inline]
773
  #[cfg(not(tarpaulin_include))]
774
0
  pub fn len(&self) -> usize {
775
0
    self.bitspan.len()
776
0
  }
777
778
  /// Tests if the bit-vector is empty.
779
  ///
780
  /// This is equivalent to `BitSlice::is_empty`; it is provided as an
781
  /// inherent method here rather than relying on `Deref` forwarding so that
782
  /// you can write `BitVec::is_empty` as a named function item.
783
  ///
784
  /// ## Original
785
  ///
786
  /// [`Vec::is_empty`](alloc::vec::Vec::is_empty)
787
  #[inline]
788
  #[cfg(not(tarpaulin_include))]
789
0
  pub fn is_empty(&self) -> bool {
790
0
    self.bitspan.len() == 0
791
0
  }
792
793
  /// Splits the bit-vector in half at an index, moving `self[at ..]` out into
794
  /// a new bit-vector.
795
  ///
796
  /// ## Original
797
  ///
798
  /// [`Vec::split_off`](alloc::vec::Vec::split_off)
799
  ///
800
  /// ## Examples
801
  ///
802
  /// ```rust
803
  /// use bitvec::prelude::*;
804
  ///
805
  /// let mut bv = bitvec![0, 1, 0, 0, 1];
806
  /// let bv2 = bv.split_off(2);
807
  /// assert_eq!((&*bv, &*bv2), (bits![0, 1], bits![0, 0, 1]));
808
  /// ```
809
  #[inline]
810
0
  pub fn split_off(&mut self, at: usize) -> Self {
811
0
    let len = self.len();
812
0
    self.assert_in_bounds(at, 0 ..= len);
813
0
    let (this, that) = unsafe {
814
0
      self.bitspan
815
0
        .into_bitslice_mut()
816
0
        .split_at_unchecked_mut_noalias(at)
817
0
    };
818
0
    self.bitspan = this.as_mut_bitspan();
819
0
    Self::from_bitslice(that)
820
0
  }
821
822
  /// Resizes the bit-vector to a new length, using a function to produce each
823
  /// inserted bit.
824
  ///
825
  /// If `new_len` is less than `self.len()`, this is a truncate operation; if
826
  /// it is greater, then `self` is extended by repeatedly pushing `func()`.
827
  ///
828
  /// ## Original
829
  ///
830
  /// [`Vec::resize_with`](alloc::vec::Vec::resize_with)
831
  ///
832
  /// ## API Differences
833
  ///
834
  /// The generator function receives the index into which its bit will be
835
  /// placed.
836
  ///
837
  /// ## Examples
838
  ///
839
  /// ```rust
840
  /// use bitvec::prelude::*;
841
  ///
842
  /// let mut bv = bitvec![1; 2];
843
  /// bv.resize_with(5, |idx| idx % 2 == 1);
844
  /// assert_eq!(bv, bits![1, 1, 0, 1, 0]);
845
  /// ```
846
  #[inline]
847
0
  pub fn resize_with<F>(&mut self, new_len: usize, mut func: F)
848
0
  where F: FnMut(usize) -> bool {
849
0
    let old_len = self.len();
850
0
    self.resize(new_len, false);
851
0
    if new_len > old_len {
852
0
      for (bitptr, idx) in unsafe { self.get_unchecked_mut(old_len ..) }
853
0
        .as_mut_bitptr_range()
854
0
        .zip(old_len ..)
855
      {
856
0
        unsafe {
857
0
          bitptr.write(func(idx));
858
0
        }
859
      }
860
0
    }
861
0
  }
862
863
  /// Destroys the `BitVec` handle without destroying the bit-vector
864
  /// allocation. The allocation is returned as an `&mut BitSlice` that lasts
865
  /// for the remaining program lifetime.
866
  ///
867
  /// You *may* call [`BitBox::from_raw`] on this slice handle exactly once in
868
  /// order to reap the allocation before program exit. That function takes a
869
  /// mutable pointer, not a mutable reference, so you must ensure that the
870
  /// returned reference is never used again after restoring the allocation
871
  /// handle.
872
  ///
873
  /// ## Original
874
  ///
875
  /// [`Vec::leak`](alloc::vec::Vec::leak)
876
  ///
877
  /// ## Examples
878
  ///
879
  /// ```rust
880
  /// use bitvec::prelude::*;
881
  ///
882
  /// let bv = bitvec![0, 0, 1];
883
  /// let static_bits: &'static mut BitSlice = bv.leak();
884
  /// static_bits.set(0, true);
885
  /// assert_eq!(static_bits, bits![1, 0, 1]);
886
  ///
887
  /// let bb = unsafe { BitBox::from_raw(static_bits) };
888
  /// // static_bits may no longer be used.
889
  /// drop(bb); // explicitly reap memory before program exit
890
  /// ```
891
  ///
892
  /// [`BitBox::leak`]: crate::boxed::BitBox::leak
893
  #[inline]
894
  #[cfg(not(tarpaulin_include))]
895
0
  pub fn leak<'a>(self) -> &'a mut BitSlice<T, O> {
896
0
    self.into_boxed_bitslice().pipe(BitBox::leak)
897
0
  }
898
899
  /// Resizes the bit-vector to a new length. New bits are initialized to
900
  /// `value`.
901
  ///
902
  /// ## Original
903
  ///
904
  /// [`Vec::resize`](alloc::vec::Vec::resize)
905
  ///
906
  /// ## Examples
907
  ///
908
  /// ```rust
909
  /// use bitvec::prelude::*;
910
  ///
911
  /// let mut bv = bitvec![0; 2];
912
  /// bv.resize(5, true);
913
  /// assert_eq!(bv, bits![0, 0, 1, 1, 1]);
914
  /// ```
915
  #[inline]
916
0
  pub fn resize(&mut self, new_len: usize, value: bool) {
917
0
    let len = self.len();
918
0
    if new_len > len {
919
0
      self.reserve(new_len - len);
920
0
      unsafe {
921
0
        self.set_len(new_len);
922
0
        self.get_unchecked_mut(len .. new_len).fill(value);
923
0
      }
924
    }
925
0
    else {
926
0
      self.truncate(new_len);
927
0
    }
928
0
  }
929
930
  #[inline]
931
  #[cfg(not(tarpaulin_include))]
932
  #[allow(missing_docs, clippy::missing_docs_in_private_items)]
933
  #[deprecated = "use `.extend_from_bitslice()` or `.extend_from_raw_slice()` \
934
                  instead"]
935
0
  pub fn extend_from_slice<T2, O2>(&mut self, other: &BitSlice<T2, O2>)
936
0
  where
937
0
    T2: BitStore,
938
0
    O2: BitOrder,
939
  {
940
0
    self.extend_from_bitslice(other);
941
0
  }
942
943
  /// Extends `self` by copying an internal range of its bit-slice as the
944
  /// region to append.
945
  ///
946
  /// ## Original
947
  ///
948
  /// [`Vec::extend_from_within`](alloc::vec::Vec::extend_from_within)
949
  ///
950
  /// ## Panics
951
  ///
952
  /// This panics if `src` is not within `0 .. self.len()`.
953
  ///
954
  /// ## Examples
955
  ///
956
  /// ```rust
957
  /// use bitvec::prelude::*;
958
  ///
959
  /// let mut bv = bitvec![0, 1, 0, 0, 1];
960
  /// bv.extend_from_within(1 .. 4);
961
  /// assert_eq!(bv, bits![0, 1, 0, 0, 1, 1, 0, 0]);
962
  /// ```
963
  #[inline]
964
0
  pub fn extend_from_within<R>(&mut self, src: R)
965
0
  where R: RangeExt<usize> {
966
0
    let old_len = self.len();
967
0
    let src = src.normalize(0, old_len);
968
0
    self.assert_in_bounds(src.end, 0 .. old_len);
969
0
    self.resize(old_len + src.len(), false);
970
0
    unsafe {
971
0
      self.copy_within_unchecked(src, old_len);
972
0
    }
973
0
  }
974
975
  /// Modifies [`self.drain()`] so that the removed bit-slice is instead
976
  /// replaced with the contents of another bit-stream.
977
  ///
978
  /// As with `.drain()`, the specified range is always removed from the
979
  /// bit-vector even if the splicer is not fully consumed, and the splicer
980
  /// does not specify how many bits are removed if it leaks.
981
  ///
982
  /// The replacement source is only consumed when the splicer drops; however,
983
  /// it may be pulled before then. The replacement source cannot assume that
984
  /// there will be a delay between creation of the splicer and when it must
985
  /// begin producing bits.
986
  ///
987
  /// This copies the `Vec::splice` implementation; see its documentation for
988
  /// more details about how the replacement should act.
989
  ///
990
  /// ## Original
991
  ///
992
  /// [`Vec::splice`](alloc::vec::Vec::splice)
993
  ///
994
  /// ## Panics
995
  ///
996
  /// This panics if `range` departs `0 .. self.len()`.
997
  ///
998
  /// ## Examples
999
  ///
1000
  /// ```rust
1001
  /// use bitvec::prelude::*;
1002
  ///
1003
  /// let mut bv = bitvec![0, 1, 1];
1004
  /// //                   a  b  c
1005
  /// let mut yank = bv.splice(
1006
  ///   .. 2,
1007
  ///   bits![static 1, 1, 0].iter().by_vals(),
1008
  /// //             d  e  f
1009
  /// );
1010
  ///
1011
  /// assert!(!yank.next().unwrap()); // a
1012
  /// assert!(yank.next().unwrap()); // b
1013
  /// drop(yank);
1014
  /// assert_eq!(bv, bits![1, 1, 0, 1]);
1015
  /// //                   d  e  f  c
1016
  /// ```
1017
  ///
1018
  /// [`self.drain()`]: Self::drain
1019
  #[inline]
1020
0
  pub fn splice<R, I>(
1021
0
    &mut self,
1022
0
    range: R,
1023
0
    replace_with: I,
1024
0
  ) -> Splice<T, O, I::IntoIter>
1025
0
  where
1026
0
    R: RangeBounds<usize>,
1027
0
    I: IntoIterator<Item = bool>,
1028
  {
1029
0
    Splice::new(self.drain(range), replace_with)
1030
0
  }
1031
}