bitvec/slice/api.rs
1#![doc = include_str!("../../doc/slice/api.md")]
2
3use core::{
4 cmp,
5 ops::{
6 Range,
7 RangeFrom,
8 RangeFull,
9 RangeInclusive,
10 RangeTo,
11 RangeToInclusive,
12 },
13};
14
15use wyz::{
16 comu::{
17 Const,
18 Mut,
19 },
20 range::RangeExt,
21};
22
23use super::{
24 BitSlice,
25 Chunks,
26 ChunksExact,
27 ChunksExactMut,
28 ChunksMut,
29 Iter,
30 IterMut,
31 RChunks,
32 RChunksExact,
33 RChunksExactMut,
34 RChunksMut,
35 RSplit,
36 RSplitMut,
37 RSplitN,
38 RSplitNMut,
39 Split,
40 SplitInclusive,
41 SplitInclusiveMut,
42 SplitMut,
43 SplitN,
44 SplitNMut,
45 Windows,
46};
47#[cfg(feature = "alloc")]
48use crate::vec::BitVec;
49use crate::{
50 array::BitArray,
51 domain::Domain,
52 mem::{
53 self,
54 BitRegister,
55 },
56 order::BitOrder,
57 ptr::{
58 BitPtr,
59 BitRef,
60 BitSpan,
61 BitSpanError,
62 },
63 store::BitStore,
64};
65
66/// Port of the `[T]` inherent API.
67impl<T, O> BitSlice<T, O>
68where
69 T: BitStore,
70 O: BitOrder,
71{
72 /// Gets the number of bits in the bit-slice.
73 ///
74 /// ## Original
75 ///
76 /// [`slice::len`](https://doc.rust-lang.org/std/primitive.slice.html#method.len)
77 ///
78 /// ## Examples
79 ///
80 /// ```rust
81 /// use bitvec::prelude::*;
82 ///
83 /// assert_eq!(bits![].len(), 0);
84 /// assert_eq!(bits![0; 10].len(), 10);
85 /// ```
86 #[inline]
87 pub fn len(&self) -> usize {
88 self.as_bitspan().len()
89 }
90
91 /// Tests if the bit-slice is empty (length zero).
92 ///
93 /// ## Original
94 ///
95 /// [`slice::is_empty`](https://doc.rust-lang.org/std/primitive.slice.html#method.is_empty)
96 ///
97 /// ## Examples
98 ///
99 /// ```rust
100 /// use bitvec::prelude::*;
101 ///
102 /// assert!(bits![].is_empty());
103 /// assert!(!bits![0; 10].is_empty());
104 /// ```
105 #[inline]
106 pub fn is_empty(&self) -> bool {
107 self.len() == 0
108 }
109
110 /// Gets a reference to the first bit of the bit-slice, or `None` if it is
111 /// empty.
112 ///
113 /// ## Original
114 ///
115 /// [`slice::first`](https://doc.rust-lang.org/std/primitive.slice.html#method.first)
116 ///
117 /// ## API Differences
118 ///
119 /// `bitvec` uses a custom structure for both read-only and mutable
120 /// references to `bool`.
121 ///
122 /// ## Examples
123 ///
124 /// ```rust
125 /// use bitvec::prelude::*;
126 ///
127 /// let bits = bits![1, 0, 0];
128 /// assert_eq!(bits.first().as_deref(), Some(&true));
129 ///
130 /// assert!(bits![].first().is_none());
131 /// ```
132 #[inline]
133 pub fn first(&self) -> Option<BitRef<Const, T, O>> {
134 self.get(0)
135 }
136
137 /// Gets a mutable reference to the first bit of the bit-slice, or `None` if
138 /// it is empty.
139 ///
140 /// ## Original
141 ///
142 /// [`slice::first_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.first_mut)
143 ///
144 /// ## API Differences
145 ///
146 /// `bitvec` uses a custom structure for both read-only and mutable
147 /// references to `bool`. This must be bound as `mut` in order to write
148 /// through it.
149 ///
150 /// ## Examples
151 ///
152 /// ```rust
153 /// use bitvec::prelude::*;
154 ///
155 /// let bits = bits![mut 0; 3];
156 /// if let Some(mut first) = bits.first_mut() {
157 /// *first = true;
158 /// }
159 /// assert_eq!(bits, bits![1, 0, 0]);
160 ///
161 /// assert!(bits![mut].first_mut().is_none());
162 /// ```
163 #[inline]
164 pub fn first_mut(&mut self) -> Option<BitRef<Mut, T, O>> {
165 self.get_mut(0)
166 }
167
168 /// Splits the bit-slice into a reference to its first bit, and the rest of
169 /// the bit-slice. Returns `None` when empty.
170 ///
171 /// ## Original
172 ///
173 /// [`slice::split_first`](https://doc.rust-lang.org/std/primitive.slice.html#method.split_first)
174 ///
175 /// ## API Differences
176 ///
177 /// `bitvec` uses a custom structure for both read-only and mutable
178 /// references to `bool`.
179 ///
180 /// ## Examples
181 ///
182 /// ```rust
183 /// use bitvec::prelude::*;
184 ///
185 /// let bits = bits![1, 0, 0];
186 /// let (first, rest) = bits.split_first().unwrap();
187 /// assert_eq!(first, &true);
188 /// assert_eq!(rest, bits![0; 2]);
189 /// ```
190 #[inline]
191 pub fn split_first(&self) -> Option<(BitRef<Const, T, O>, &Self)> {
192 match self.len() {
193 0 => None,
194 _ => unsafe {
195 let (head, rest) = self.split_at_unchecked(1);
196 Some((head.get_unchecked(0), rest))
197 },
198 }
199 }
200
201 /// Splits the bit-slice into mutable references of its first bit, and the
202 /// rest of the bit-slice. Returns `None` when empty.
203 ///
204 /// ## Original
205 ///
206 /// [`slice::split_first_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.split_first_mut)
207 ///
208 /// ## API Differences
209 ///
210 /// `bitvec` uses a custom structure for both read-only and mutable
211 /// references to `bool`. This must be bound as `mut` in order to write
212 /// through it.
213 ///
214 /// ## Examples
215 ///
216 /// ```rust
217 /// use bitvec::prelude::*;
218 ///
219 /// let bits = bits![mut 0; 3];
220 /// if let Some((mut first, rest)) = bits.split_first_mut() {
221 /// *first = true;
222 /// assert_eq!(rest, bits![0; 2]);
223 /// }
224 /// assert_eq!(bits, bits![1, 0, 0]);
225 /// ```
226 #[inline]
227 pub fn split_first_mut(
228 &mut self,
229 ) -> Option<(BitRef<Mut, T::Alias, O>, &mut BitSlice<T::Alias, O>)> {
230 match self.len() {
231 0 => None,
232 _ => unsafe {
233 let (head, rest) = self.split_at_unchecked_mut(1);
234 Some((head.get_unchecked_mut(0), rest))
235 },
236 }
237 }
238
239 /// Splits the bit-slice into a reference to its last bit, and the rest of
240 /// the bit-slice. Returns `None` when empty.
241 ///
242 /// ## Original
243 ///
244 /// [`slice::split_last`](https://doc.rust-lang.org/std/primitive.slice.html#method.split_last)
245 ///
246 /// ## API Differences
247 ///
248 /// `bitvec` uses a custom structure for both read-only and mutable
249 /// references to `bool`.
250 ///
251 /// ## Examples
252 ///
253 /// ```rust
254 /// use bitvec::prelude::*;
255 ///
256 /// let bits = bits![0, 0, 1];
257 /// let (last, rest) = bits.split_last().unwrap();
258 /// assert_eq!(last, &true);
259 /// assert_eq!(rest, bits![0; 2]);
260 /// ```
261 #[inline]
262 pub fn split_last(&self) -> Option<(BitRef<Const, T, O>, &Self)> {
263 match self.len() {
264 0 => None,
265 n => unsafe {
266 let (rest, tail) = self.split_at_unchecked(n - 1);
267 Some((tail.get_unchecked(0), rest))
268 },
269 }
270 }
271
272 /// Splits the bit-slice into mutable references to its last bit, and the
273 /// rest of the bit-slice. Returns `None` when empty.
274 ///
275 /// ## Original
276 ///
277 /// [`slice::split_last_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.split_last_mut)
278 ///
279 /// ## API Differences
280 ///
281 /// `bitvec` uses a custom structure for both read-only and mutable
282 /// references to `bool`. This must be bound as `mut` in order to write
283 /// through it.
284 ///
285 /// ## Examples
286 ///
287 /// ```rust
288 /// use bitvec::prelude::*;
289 ///
290 /// let bits = bits![mut 0; 3];
291 /// if let Some((mut last, rest)) = bits.split_last_mut() {
292 /// *last = true;
293 /// assert_eq!(rest, bits![0; 2]);
294 /// }
295 /// assert_eq!(bits, bits![0, 0, 1]);
296 /// ```
297 #[inline]
298 pub fn split_last_mut(
299 &mut self,
300 ) -> Option<(BitRef<Mut, T::Alias, O>, &mut BitSlice<T::Alias, O>)> {
301 match self.len() {
302 0 => None,
303 n => unsafe {
304 let (rest, tail) = self.split_at_unchecked_mut(n - 1);
305 Some((tail.get_unchecked_mut(0), rest))
306 },
307 }
308 }
309
310 /// Gets a reference to the last bit of the bit-slice, or `None` if it is
311 /// empty.
312 ///
313 /// ## Original
314 ///
315 /// [`slice::last`](https://doc.rust-lang.org/std/primitive.slice.html#method.last)
316 ///
317 /// ## API Differences
318 ///
319 /// `bitvec` uses a custom structure for both read-only and mutable
320 /// references to `bool`.
321 ///
322 /// ## Examples
323 ///
324 /// ```rust
325 /// use bitvec::prelude::*;
326 ///
327 /// let bits = bits![0, 0, 1];
328 /// assert_eq!(bits.last().as_deref(), Some(&true));
329 ///
330 /// assert!(bits![].last().is_none());
331 /// ```
332 #[inline]
333 pub fn last(&self) -> Option<BitRef<Const, T, O>> {
334 match self.len() {
335 0 => None,
336 n => Some(unsafe { self.get_unchecked(n - 1) }),
337 }
338 }
339
340 /// Gets a mutable reference to the last bit of the bit-slice, or `None` if
341 /// it is empty.
342 ///
343 /// ## Original
344 ///
345 /// [`slice::last_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.last_mut)
346 ///
347 /// ## API Differences
348 ///
349 /// `bitvec` uses a custom structure for both read-only and mutable
350 /// references to `bool`. This must be bound as `mut` in order to write
351 /// through it.
352 ///
353 /// ## Examples
354 ///
355 /// ```rust
356 /// use bitvec::prelude::*;
357 ///
358 /// let bits = bits![mut 0; 3];
359 /// if let Some(mut last) = bits.last_mut() {
360 /// *last = true;
361 /// }
362 /// assert_eq!(bits, bits![0, 0, 1]);
363 ///
364 /// assert!(bits![mut].last_mut().is_none());
365 /// ```
366 #[inline]
367 pub fn last_mut(&mut self) -> Option<BitRef<Mut, T, O>> {
368 match self.len() {
369 0 => None,
370 n => Some(unsafe { self.get_unchecked_mut(n - 1) }),
371 }
372 }
373
374 /// Gets a reference to a single bit or a subsection of the bit-slice,
375 /// depending on the type of `index`.
376 ///
377 /// - If given a `usize`, this produces a reference structure to the `bool`
378 /// at the position.
379 /// - If given any form of range, this produces a smaller bit-slice.
380 ///
381 /// This returns `None` if the `index` departs the bounds of `self`.
382 ///
383 /// ## Original
384 ///
385 /// [`slice::get`](https://doc.rust-lang.org/std/primitive.slice.html#method.get)
386 ///
387 /// ## API Differences
388 ///
389 /// `BitSliceIndex` uses discrete types for immutable and mutable
390 /// references, rather than a single referent type.
391 ///
392 /// ## Examples
393 ///
394 /// ```rust
395 /// use bitvec::prelude::*;
396 ///
397 /// let bits = bits![0, 1, 0];
398 /// assert_eq!(bits.get(1).as_deref(), Some(&true));
399 /// assert_eq!(bits.get(0 .. 2), Some(bits![0, 1]));
400 /// assert!(bits.get(3).is_none());
401 /// assert!(bits.get(0 .. 4).is_none());
402 /// ```
403 #[inline]
404 pub fn get<'a, I>(&'a self, index: I) -> Option<I::Immut>
405 where I: BitSliceIndex<'a, T, O> {
406 index.get(self)
407 }
408
409 /// Gets a mutable reference to a single bit or a subsection of the
410 /// bit-slice, depending on the type of `index`.
411 ///
412 /// - If given a `usize`, this produces a reference structure to the `bool`
413 /// at the position.
414 /// - If given any form of range, this produces a smaller bit-slice.
415 ///
416 /// This returns `None` if the `index` departs the bounds of `self`.
417 ///
418 /// ## Original
419 ///
420 /// [`slice::get_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.get_mut)
421 ///
422 /// ## API Differences
423 ///
424 /// `BitSliceIndex` uses discrete types for immutable and mutable
425 /// references, rather than a single referent type.
426 ///
427 /// ## Examples
428 ///
429 /// ```rust
430 /// use bitvec::prelude::*;
431 ///
432 /// let bits = bits![mut 0; 3];
433 ///
434 /// *bits.get_mut(0).unwrap() = true;
435 /// bits.get_mut(1 ..).unwrap().fill(true);
436 /// assert_eq!(bits, bits![1; 3]);
437 /// ```
438 #[inline]
439 pub fn get_mut<'a, I>(&'a mut self, index: I) -> Option<I::Mut>
440 where I: BitSliceIndex<'a, T, O> {
441 index.get_mut(self)
442 }
443
444 /// Gets a reference to a single bit or to a subsection of the bit-slice,
445 /// without bounds checking.
446 ///
447 /// This has the same arguments and behavior as [`.get()`], except that it
448 /// does not check that `index` is in bounds.
449 ///
450 /// ## Original
451 ///
452 /// [`slice::get_unchecked`](https://doc.rust-lang.org/std/primitive.slice.html#method.get_unchecked)
453 ///
454 /// ## Safety
455 ///
456 /// You must ensure that `index` is within bounds (within the range `0 ..
457 /// self.len()`), or this method will introduce memory safety and/or
458 /// undefined behavior.
459 ///
460 /// It is library-level undefined behavior to index beyond the length of any
461 /// bit-slice, even if you **know** that the offset remains within an
462 /// allocation as measured by Rust or LLVM.
463 ///
464 /// ## Examples
465 ///
466 /// ```rust
467 /// use bitvec::prelude::*;
468 ///
469 /// let data = 0b0001_0010u8;
470 /// let bits = &data.view_bits::<Lsb0>()[.. 3];
471 ///
472 /// unsafe {
473 /// assert!(bits.get_unchecked(1));
474 /// assert!(bits.get_unchecked(4));
475 /// }
476 /// ```
477 ///
478 /// [`.get()`]: Self::get
479 #[inline]
480 pub unsafe fn get_unchecked<'a, I>(&'a self, index: I) -> I::Immut
481 where I: BitSliceIndex<'a, T, O> {
482 index.get_unchecked(self)
483 }
484
485 /// Gets a mutable reference to a single bit or a subsection of the
486 /// bit-slice, depending on the type of `index`.
487 ///
488 /// This has the same arguments and behavior as [`.get_mut()`], except that
489 /// it does not check that `index` is in bounds.
490 ///
491 /// ## Original
492 ///
493 /// [`slice::get_unchecked_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.get_unchecked_mut)
494 ///
495 /// ## Safety
496 ///
497 /// You must ensure that `index` is within bounds (within the range `0 ..
498 /// self.len()`), or this method will introduce memory safety and/or
499 /// undefined behavior.
500 ///
501 /// It is library-level undefined behavior to index beyond the length of any
502 /// bit-slice, even if you **know** that the offset remains within an
503 /// allocation as measured by Rust or LLVM.
504 ///
505 /// ## Examples
506 ///
507 /// ```rust
508 /// use bitvec::prelude::*;
509 ///
510 /// let mut data = 0u8;
511 /// let bits = &mut data.view_bits_mut::<Lsb0>()[.. 3];
512 ///
513 /// unsafe {
514 /// bits.get_unchecked_mut(1).commit(true);
515 /// bits.get_unchecked_mut(4 .. 6).fill(true);
516 /// }
517 /// assert_eq!(data, 0b0011_0010);
518 /// ```
519 ///
520 /// [`.get_mut()`]: Self::get_mut
521 #[inline]
522 pub unsafe fn get_unchecked_mut<'a, I>(&'a mut self, index: I) -> I::Mut
523 where I: BitSliceIndex<'a, T, O> {
524 index.get_unchecked_mut(self)
525 }
526
527 #[inline]
528 #[cfg(not(tarpaulin_include))]
529 #[deprecated = "use `.as_bitptr()` instead"]
530 #[allow(missing_docs, clippy::missing_docs_in_private_items)]
531 pub fn as_ptr(&self) -> BitPtr<Const, T, O> {
532 self.as_bitptr()
533 }
534
535 #[inline]
536 #[cfg(not(tarpaulin_include))]
537 #[deprecated = "use `.as_mut_bitptr()` instead"]
538 #[allow(missing_docs, clippy::missing_docs_in_private_items)]
539 pub fn as_mut_ptr(&mut self) -> BitPtr<Mut, T, O> {
540 self.as_mut_bitptr()
541 }
542
543 /// Produces a range of bit-pointers to each bit in the bit-slice.
544 ///
545 /// This is a standard-library range, which has no real functionality for
546 /// pointer types. You should prefer [`.as_bitptr_range()`] instead, as it
547 /// produces a custom structure that provides expected ranging
548 /// functionality.
549 ///
550 /// ## Original
551 ///
552 /// [`slice::as_ptr_range`](https://doc.rust-lang.org/std/primitive.slice.html#method.as_ptr_range)
553 ///
554 /// [`.as_bitptr_range()`]: Self::as_bitptr_range
555 #[inline]
556 #[cfg(not(tarpaulin_include))]
557 pub fn as_ptr_range(&self) -> Range<BitPtr<Const, T, O>> {
558 self.as_bitptr_range().into_range()
559 }
560
561 /// Produces a range of mutable bit-pointers to each bit in the bit-slice.
562 ///
563 /// This is a standard-library range, which has no real functionality for
564 /// pointer types. You should prefer [`.as_mut_bitptr_range()`] instead, as
565 /// it produces a custom structure that provides expected ranging
566 /// functionality.
567 ///
568 /// ## Original
569 ///
570 /// [`slice::as_mut_ptr_range`](https://doc.rust-lang.org/std/primitive.slice.html#method.as_mut_ptr_range)
571 ///
572 /// [`.as_mut_bitptr_range()`]: Self::as_mut_bitptr_range
573 #[inline]
574 #[cfg(not(tarpaulin_include))]
575 pub fn as_mut_ptr_range(&mut self) -> Range<BitPtr<Mut, T, O>> {
576 self.as_mut_bitptr_range().into_range()
577 }
578
579 /// Exchanges the bit values at two indices.
580 ///
581 /// ## Original
582 ///
583 /// [`slice::swap`](https://doc.rust-lang.org/std/primitive.slice.html#method.swap)
584 ///
585 /// ## Panics
586 ///
587 /// This panics if either `a` or `b` are out of bounds.
588 ///
589 /// ## Examples
590 ///
591 /// ```rust
592 /// use bitvec::prelude::*;
593 ///
594 /// let bits = bits![mut 0, 1];
595 /// bits.swap(0, 1);
596 /// assert_eq!(bits, bits![1, 0]);
597 /// ```
598 #[inline]
599 pub fn swap(&mut self, a: usize, b: usize) {
600 let bounds = 0 .. self.len();
601 self.assert_in_bounds(a, bounds.clone());
602 self.assert_in_bounds(b, bounds);
603 unsafe {
604 self.swap_unchecked(a, b);
605 }
606 }
607
608 /// Reverses the order of bits in a bit-slice.
609 ///
610 /// ## Original
611 ///
612 /// [`slice::reverse`](https://doc.rust-lang.org/std/primitive.slice.html#method.reverse)
613 ///
614 /// ## Examples
615 ///
616 /// ```rust
617 /// use bitvec::prelude::*;
618 ///
619 /// let bits = bits![mut 0, 0, 1, 0, 1, 1, 0, 0, 1];
620 /// bits.reverse();
621 /// assert_eq!(bits, bits![1, 0, 0, 1, 1, 0, 1, 0, 0]);
622 /// ```
623 #[inline]
624 pub fn reverse(&mut self) {
625 let mut iter = self.as_mut_bitptr_range();
626 while let (Some(a), Some(b)) = (iter.next(), iter.next_back()) {
627 unsafe {
628 crate::ptr::swap(a, b);
629 }
630 }
631 }
632
633 /// Produces an iterator over each bit in the bit-slice.
634 ///
635 /// ## Original
636 ///
637 /// [`slice::iter`](https://doc.rust-lang.org/std/primitive.slice.html#method.iter)
638 ///
639 /// ## API Differences
640 ///
641 /// This iterator yields proxy-reference structures, not `&bool`. It can be
642 /// adapted to yield `&bool` with the [`.by_refs()`] method, or `bool` with
643 /// [`.by_vals()`].
644 ///
645 /// This iterator, and its adapters, are fast. Do not try to be more clever
646 /// than them by abusing `.as_bitptr_range()`.
647 ///
648 /// ## Examples
649 ///
650 /// ```rust
651 /// use bitvec::prelude::*;
652 ///
653 /// let bits = bits![0, 1, 0, 1];
654 /// let mut iter = bits.iter();
655 ///
656 /// assert!(!iter.next().unwrap());
657 /// assert!( iter.next().unwrap());
658 /// assert!( iter.next_back().unwrap());
659 /// assert!(!iter.next_back().unwrap());
660 /// assert!( iter.next().is_none());
661 /// ```
662 ///
663 /// [`.by_refs()`]: crate::slice::Iter::by_refs
664 /// [`.by_vals()`]: crate::slice::Iter::by_vals
665 #[inline]
666 pub fn iter(&self) -> Iter<T, O> {
667 Iter::new(self)
668 }
669
670 /// Produces a mutable iterator over each bit in the bit-slice.
671 ///
672 /// ## Original
673 ///
674 /// [`slice::iter_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.iter_mut)
675 ///
676 /// ## API Differences
677 ///
678 /// This iterator yields proxy-reference structures, not `&mut bool`. In
679 /// addition, it marks each proxy as alias-tainted.
680 ///
681 /// If you are using this in an ordinary loop and **not** keeping multiple
682 /// yielded proxy-references alive at the same scope, you may use the
683 /// [`.remove_alias()`] adapter to undo the alias marking.
684 ///
685 /// This iterator is fast. Do not try to be more clever than it by abusing
686 /// `.as_mut_bitptr_range()`.
687 ///
688 /// ## Examples
689 ///
690 /// ```rust
691 /// use bitvec::prelude::*;
692 ///
693 /// let bits = bits![mut 0; 4];
694 /// let mut iter = bits.iter_mut();
695 ///
696 /// iter.nth(1).unwrap().commit(true); // index 1
697 /// iter.next_back().unwrap().commit(true); // index 3
698 ///
699 /// assert!(iter.next().is_some()); // index 2
700 /// assert!(iter.next().is_none()); // complete
701 /// assert_eq!(bits, bits![0, 1, 0, 1]);
702 /// ```
703 ///
704 /// [`.remove_alias()`]: crate::slice::IterMut::remove_alias
705 #[inline]
706 pub fn iter_mut(&mut self) -> IterMut<T, O> {
707 IterMut::new(self)
708 }
709
710 /// Iterates over consecutive windowing subslices in a bit-slice.
711 ///
712 /// Windows are overlapping views of the bit-slice. Each window advances one
713 /// bit from the previous, so in a bit-slice `[A, B, C, D, E]`, calling
714 /// `.windows(3)` will yield `[A, B, C]`, `[B, C, D]`, and `[C, D, E]`.
715 ///
716 /// ## Original
717 ///
718 /// [`slice::windows`](https://doc.rust-lang.org/std/primitive.slice.html#method.windows)
719 ///
720 /// ## Panics
721 ///
722 /// This panics if `size` is `0`.
723 ///
724 /// ## Examples
725 ///
726 /// ```rust
727 /// use bitvec::prelude::*;
728 ///
729 /// let bits = bits![0, 1, 0, 0, 1];
730 /// let mut iter = bits.windows(3);
731 ///
732 /// assert_eq!(iter.next(), Some(bits![0, 1, 0]));
733 /// assert_eq!(iter.next(), Some(bits![1, 0, 0]));
734 /// assert_eq!(iter.next(), Some(bits![0, 0, 1]));
735 /// assert!(iter.next().is_none());
736 /// ```
737 #[inline]
738 pub fn windows(&self, size: usize) -> Windows<T, O> {
739 Windows::new(self, size)
740 }
741
742 /// Iterates over non-overlapping subslices of a bit-slice.
743 ///
744 /// Unlike `.windows()`, the subslices this yields do not overlap with each
745 /// other. If `self.len()` is not an even multiple of `chunk_size`, then the
746 /// last chunk yielded will be shorter.
747 ///
748 /// ## Original
749 ///
750 /// [`slice::chunks`](https://doc.rust-lang.org/std/primitive.slice.html#method.chunks)
751 ///
752 /// ## Sibling Methods
753 ///
754 /// - [`.chunks_mut()`] has the same division logic, but each yielded
755 /// bit-slice is mutable.
756 /// - [`.chunks_exact()`] does not yield the final chunk if it is shorter
757 /// than `chunk_size`.
758 /// - [`.rchunks()`] iterates from the back of the bit-slice to the front,
759 /// with the final, possibly-shorter, segment at the front edge.
760 ///
761 /// ## Panics
762 ///
763 /// This panics if `chunk_size` is `0`.
764 ///
765 /// ## Examples
766 ///
767 /// ```rust
768 /// use bitvec::prelude::*;
769 ///
770 /// let bits = bits![0, 1, 0, 0, 1];
771 /// let mut iter = bits.chunks(2);
772 ///
773 /// assert_eq!(iter.next(), Some(bits![0, 1]));
774 /// assert_eq!(iter.next(), Some(bits![0, 0]));
775 /// assert_eq!(iter.next(), Some(bits![1]));
776 /// assert!(iter.next().is_none());
777 /// ```
778 ///
779 /// [`.chunks_exact()`]: Self::chunks_exact
780 /// [`.chunks_mut()`]: Self::chunks_mut
781 /// [`.rchunks()`]: Self::rchunks
782 #[inline]
783 pub fn chunks(&self, chunk_size: usize) -> Chunks<T, O> {
784 Chunks::new(self, chunk_size)
785 }
786
787 /// Iterates over non-overlapping mutable subslices of a bit-slice.
788 ///
789 /// Iterators do not require that each yielded item is destroyed before the
790 /// next is produced. This means that each bit-slice yielded must be marked
791 /// as aliased. If you are using this in a loop that does not collect
792 /// multiple yielded subslices for the same scope, then you can remove the
793 /// alias marking by calling the (`unsafe`) method [`.remove_alias()`] on
794 /// the iterator.
795 ///
796 /// ## Original
797 ///
798 /// [`slice::chunks_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.chunks_mut)
799 ///
800 /// ## Sibling Methods
801 ///
802 /// - [`.chunks()`] has the same division logic, but each yielded bit-slice
803 /// is immutable.
804 /// - [`.chunks_exact_mut()`] does not yield the final chunk if it is
805 /// shorter than `chunk_size`.
806 /// - [`.rchunks_mut()`] iterates from the back of the bit-slice to the
807 /// front, with the final, possibly-shorter, segment at the front edge.
808 ///
809 /// ## Panics
810 ///
811 /// This panics if `chunk_size` is `0`.
812 ///
813 /// ## Examples
814 ///
815 /// ```rust
816 /// use bitvec::prelude::*;
817 ///
818 /// let bits = bits![mut u8, Msb0; 0; 5];
819 ///
820 /// for (idx, chunk) in unsafe {
821 /// bits.chunks_mut(2).remove_alias()
822 /// }.enumerate() {
823 /// chunk.store(idx + 1);
824 /// }
825 /// assert_eq!(bits, bits![0, 1, 1, 0, 1]);
826 /// // ^^^^ ^^^^ ^
827 /// ```
828 ///
829 /// [`.chunks()`]: Self::chunks
830 /// [`.chunks_exact_mut()`]: Self::chunks_exact_mut
831 /// [`.rchunks_mut()`]: Self::rchunks_mut
832 /// [`.remove_alias()`]: crate::slice::ChunksMut::remove_alias
833 #[inline]
834 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T, O> {
835 ChunksMut::new(self, chunk_size)
836 }
837
838 /// Iterates over non-overlapping subslices of a bit-slice.
839 ///
840 /// If `self.len()` is not an even multiple of `chunk_size`, then the last
841 /// few bits are not yielded by the iterator at all. They can be accessed
842 /// with the [`.remainder()`] method if the iterator is bound to a name.
843 ///
844 /// ## Original
845 ///
846 /// [`slice::chunks_exact`](https://doc.rust-lang.org/std/primitive.slice.html#method.chunks_exact)
847 ///
848 /// ## Sibling Methods
849 ///
850 /// - [`.chunks()`] yields any leftover bits at the end as a shorter chunk
851 /// during iteration.
852 /// - [`.chunks_exact_mut()`] has the same division logic, but each yielded
853 /// bit-slice is mutable.
854 /// - [`.rchunks_exact()`] iterates from the back of the bit-slice to the
855 /// front, with the unyielded remainder segment at the front edge.
856 ///
857 /// ## Panics
858 ///
859 /// This panics if `chunk_size` is `0`.
860 ///
861 /// ## Examples
862 ///
863 /// ```rust
864 /// use bitvec::prelude::*;
865 ///
866 /// let bits = bits![0, 1, 0, 0, 1];
867 /// let mut iter = bits.chunks_exact(2);
868 ///
869 /// assert_eq!(iter.next(), Some(bits![0, 1]));
870 /// assert_eq!(iter.next(), Some(bits![0, 0]));
871 /// assert!(iter.next().is_none());
872 /// assert_eq!(iter.remainder(), bits![1]);
873 /// ```
874 ///
875 /// [`.chunks()`]: Self::chunks
876 /// [`.chunks_exact_mut()`]: Self::chunks_exact_mut
877 /// [`.rchunks_exact()`]: Self::rchunks_exact
878 /// [`.remainder()`]: crate::slice::ChunksExact::remainder
879 #[inline]
880 pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<T, O> {
881 ChunksExact::new(self, chunk_size)
882 }
883
884 /// Iterates over non-overlapping mutable subslices of a bit-slice.
885 ///
886 /// If `self.len()` is not an even multiple of `chunk_size`, then the last
887 /// few bits are not yielded by the iterator at all. They can be accessed
888 /// with the [`.into_remainder()`] method if the iterator is bound to a
889 /// name.
890 ///
891 /// Iterators do not require that each yielded item is destroyed before the
892 /// next is produced. This means that each bit-slice yielded must be marked
893 /// as aliased. If you are using this in a loop that does not collect
894 /// multiple yielded subslices for the same scope, then you can remove the
895 /// alias marking by calling the (`unsafe`) method [`.remove_alias()`] on
896 /// the iterator.
897 ///
898 /// ## Original
899 ///
900 /// [`slice::chunks_exact_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.chunks_exact_mut)
901 ///
902 /// ## Sibling Methods
903 ///
904 /// - [`.chunks_mut()`] yields any leftover bits at the end as a shorter
905 /// chunk during iteration.
906 /// - [`.chunks_exact()`] has the same division logic, but each yielded
907 /// bit-slice is immutable.
908 /// - [`.rchunks_exact_mut()`] iterates from the back of the bit-slice
909 /// forwards, with the unyielded remainder segment at the front edge.
910 ///
911 /// ## Panics
912 ///
913 /// This panics if `chunk_size` is `0`.
914 ///
915 /// ## Examples
916 ///
917 /// ```rust
918 /// use bitvec::prelude::*;
919 ///
920 /// let bits = bits![mut u8, Msb0; 0; 5];
921 /// let mut iter = bits.chunks_exact_mut(2);
922 ///
923 /// for (idx, chunk) in iter.by_ref().enumerate() {
924 /// chunk.store(idx + 1);
925 /// }
926 /// iter.into_remainder().store(1u8);
927 ///
928 /// assert_eq!(bits, bits![0, 1, 1, 0, 1]);
929 /// // remainder ^
930 /// ```
931 ///
932 /// [`.chunks_exact()`]: Self::chunks_exact
933 /// [`.chunks_mut()`]: Self::chunks_mut
934 /// [`.into_remainder()`]: crate::slice::ChunksExactMut::into_remainder
935 /// [`.rchunks_exact_mut()`]: Self::rchunks_exact_mut
936 /// [`.remove_alias()`]: crate::slice::ChunksExactMut::remove_alias
937 #[inline]
938 pub fn chunks_exact_mut(
939 &mut self,
940 chunk_size: usize,
941 ) -> ChunksExactMut<T, O> {
942 ChunksExactMut::new(self, chunk_size)
943 }
944
945 /// Iterates over non-overlapping subslices of a bit-slice, from the back
946 /// edge.
947 ///
948 /// Unlike `.chunks()`, this aligns its chunks to the back edge of `self`.
949 /// If `self.len()` is not an even multiple of `chunk_size`, then the
950 /// leftover partial chunk is `self[0 .. len % chunk_size]`.
951 ///
952 /// ## Original
953 ///
954 /// [`slice::rchunks`](https://doc.rust-lang.org/std/primitive.slice.html#method.rchunks)
955 ///
956 /// ## Sibling Methods
957 ///
958 /// - [`.rchunks_mut()`] has the same division logic, but each yielded
959 /// bit-slice is mutable.
960 /// - [`.rchunks_exact()`] does not yield the final chunk if it is shorter
961 /// than `chunk_size`.
962 /// - [`.chunks()`] iterates from the front of the bit-slice to the back,
963 /// with the final, possibly-shorter, segment at the back edge.
964 ///
965 /// ## Panics
966 ///
967 /// This panics if `chunk_size` is `0`.
968 ///
969 /// ## Examples
970 ///
971 /// ```rust
972 /// use bitvec::prelude::*;
973 ///
974 /// let bits = bits![0, 1, 0, 0, 1];
975 /// let mut iter = bits.rchunks(2);
976 ///
977 /// assert_eq!(iter.next(), Some(bits![0, 1]));
978 /// assert_eq!(iter.next(), Some(bits![1, 0]));
979 /// assert_eq!(iter.next(), Some(bits![0]));
980 /// assert!(iter.next().is_none());
981 /// ```
982 ///
983 /// [`.chunks()`]: Self::chunks
984 /// [`.rchunks_exact()`]: Self::rchunks_exact
985 /// [`.rchunks_mut()`]: Self::rchunks_mut
986 #[inline]
987 pub fn rchunks(&self, chunk_size: usize) -> RChunks<T, O> {
988 RChunks::new(self, chunk_size)
989 }
990
991 /// Iterates over non-overlapping mutable subslices of a bit-slice, from the
992 /// back edge.
993 ///
994 /// Unlike `.chunks_mut()`, this aligns its chunks to the back edge of
995 /// `self`. If `self.len()` is not an even multiple of `chunk_size`, then
996 /// the leftover partial chunk is `self[0 .. len % chunk_size]`.
997 ///
998 /// Iterators do not require that each yielded item is destroyed before the
999 /// next is produced. This means that each bit-slice yielded must be marked
1000 /// as aliased. If you are using this in a loop that does not collect
1001 /// multiple yielded values for the same scope, then you can remove the
1002 /// alias marking by calling the (`unsafe`) method [`.remove_alias()`] on
1003 /// the iterator.
1004 ///
1005 /// ## Original
1006 ///
1007 /// [`slice::rchunks_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.rchunks_mut)
1008 ///
1009 /// ## Sibling Methods
1010 ///
1011 /// - [`.rchunks()`] has the same division logic, but each yielded bit-slice
1012 /// is immutable.
1013 /// - [`.rchunks_exact_mut()`] does not yield the final chunk if it is
1014 /// shorter than `chunk_size`.
1015 /// - [`.chunks_mut()`] iterates from the front of the bit-slice to the
1016 /// back, with the final, possibly-shorter, segment at the back edge.
1017 ///
1018 /// ## Examples
1019 ///
1020 /// ```rust
1021 /// use bitvec::prelude::*;
1022 ///
1023 /// let bits = bits![mut u8, Msb0; 0; 5];
1024 /// for (idx, chunk) in unsafe {
1025 /// bits.rchunks_mut(2).remove_alias()
1026 /// }.enumerate() {
1027 /// chunk.store(idx + 1);
1028 /// }
1029 /// assert_eq!(bits, bits![1, 1, 0, 0, 1]);
1030 /// // remainder ^ ^^^^ ^^^^
1031 /// ```
1032 ///
1033 /// [`.chunks_mut()`]: Self::chunks_mut
1034 /// [`.rchunks()`]: Self::rchunks
1035 /// [`.rchunks_exact_mut()`]: Self::rchunks_exact_mut
1036 /// [`.remove_alias()`]: crate::slice::RChunksMut::remove_alias
1037 #[inline]
1038 pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<T, O> {
1039 RChunksMut::new(self, chunk_size)
1040 }
1041
1042 /// Iterates over non-overlapping subslices of a bit-slice, from the back
1043 /// edge.
1044 ///
1045 /// If `self.len()` is not an even multiple of `chunk_size`, then the first
1046 /// few bits are not yielded by the iterator at all. They can be accessed
1047 /// with the [`.remainder()`] method if the iterator is bound to a name.
1048 ///
1049 /// ## Original
1050 ///
1051 /// [`slice::rchunks_exact`](https://doc.rust-lang.org/std/primitive.slice.html#method.rchunks_exact)
1052 ///
1053 /// ## Sibling Methods
1054 ///
1055 /// - [`.rchunks()`] yields any leftover bits at the front as a shorter
1056 /// chunk during iteration.
1057 /// - [`.rchunks_exact_mut()`] has the same division logic, but each yielded
1058 /// bit-slice is mutable.
1059 /// - [`.chunks_exact()`] iterates from the front of the bit-slice to the
1060 /// back, with the unyielded remainder segment at the back edge.
1061 ///
1062 /// ## Panics
1063 ///
1064 /// This panics if `chunk_size` is `0`.
1065 ///
1066 /// ## Examples
1067 ///
1068 /// ```rust
1069 /// use bitvec::prelude::*;
1070 ///
1071 /// let bits = bits![0, 1, 0, 0, 1];
1072 /// let mut iter = bits.rchunks_exact(2);
1073 ///
1074 /// assert_eq!(iter.next(), Some(bits![0, 1]));
1075 /// assert_eq!(iter.next(), Some(bits![1, 0]));
1076 /// assert!(iter.next().is_none());
1077 /// assert_eq!(iter.remainder(), bits![0]);
1078 /// ```
1079 ///
1080 /// [`.chunks_exact()`]: Self::chunks_exact
1081 /// [`.rchunks()`]: Self::rchunks
1082 /// [`.rchunks_exact_mut()`]: Self::rchunks_exact_mut
1083 /// [`.remainder()`]: crate::slice::RChunksExact::remainder
1084 #[inline]
1085 pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<T, O> {
1086 RChunksExact::new(self, chunk_size)
1087 }
1088
1089 /// Iterates over non-overlapping mutable subslices of a bit-slice, from the
1090 /// back edge.
1091 ///
1092 /// If `self.len()` is not an even multiple of `chunk_size`, then the first
1093 /// few bits are not yielded by the iterator at all. They can be accessed
1094 /// with the [`.into_remainder()`] method if the iterator is bound to a
1095 /// name.
1096 ///
1097 /// Iterators do not require that each yielded item is destroyed before the
1098 /// next is produced. This means that each bit-slice yielded must be marked
1099 /// as aliased. If you are using this in a loop that does not collect
1100 /// multiple yielded subslices for the same scope, then you can remove the
1101 /// alias marking by calling the (`unsafe`) method [`.remove_alias()`] on
1102 /// the iterator.
1103 ///
1104 /// ## Sibling Methods
1105 ///
1106 /// - [`.rchunks_mut()`] yields any leftover bits at the front as a shorter
1107 /// chunk during iteration.
1108 /// - [`.rchunks_exact()`] has the same division logic, but each yielded
1109 /// bit-slice is immutable.
1110 /// - [`.chunks_exact_mut()`] iterates from the front of the bit-slice
1111 /// backwards, with the unyielded remainder segment at the back edge.
1112 ///
1113 /// ## Panics
1114 ///
1115 /// This panics if `chunk_size` is `0`.
1116 ///
1117 /// ## Examples
1118 ///
1119 /// ```rust
1120 /// use bitvec::prelude::*;
1121 ///
1122 /// let bits = bits![mut u8, Msb0; 0; 5];
1123 /// let mut iter = bits.rchunks_exact_mut(2);
1124 ///
1125 /// for (idx, chunk) in iter.by_ref().enumerate() {
1126 /// chunk.store(idx + 1);
1127 /// }
1128 /// iter.into_remainder().store(1u8);
1129 ///
1130 /// assert_eq!(bits, bits![1, 1, 0, 0, 1]);
1131 /// // remainder ^
1132 /// ```
1133 ///
1134 /// [`.chunks_exact_mut()`]: Self::chunks_exact_mut
1135 /// [`.into_remainder()`]: crate::slice::RChunksExactMut::into_remainder
1136 /// [`.rchunks_exact()`]: Self::rchunks_exact
1137 /// [`.rchunks_mut()`]: Self::rchunks_mut
1138 /// [`.remove_alias()`]: crate::slice::RChunksExactMut::remove_alias
1139 #[inline]
1140 pub fn rchunks_exact_mut(
1141 &mut self,
1142 chunk_size: usize,
1143 ) -> RChunksExactMut<T, O> {
1144 RChunksExactMut::new(self, chunk_size)
1145 }
1146
1147 /// Splits a bit-slice in two parts at an index.
1148 ///
1149 /// The returned bit-slices are `self[.. mid]` and `self[mid ..]`. `mid` is
1150 /// included in the right bit-slice, not the left.
1151 ///
1152 /// If `mid` is `0` then the left bit-slice is empty; if it is `self.len()`
1153 /// then the right bit-slice is empty.
1154 ///
1155 /// This method guarantees that even when either partition is empty, the
1156 /// encoded bit-pointer values of the bit-slice references is `&self[0]` and
1157 /// `&self[mid]`.
1158 ///
1159 /// ## Original
1160 ///
1161 /// [`slice::split_at`](https://doc.rust-lang.org/std/primitive.slice.html#method.split_at)
1162 ///
1163 /// ## Panics
1164 ///
1165 /// This panics if `mid` is greater than `self.len()`. It is allowed to be
1166 /// equal to the length, in which case the right bit-slice is simply empty.
1167 ///
1168 /// ## Examples
1169 ///
1170 /// ```rust
1171 /// use bitvec::prelude::*;
1172 ///
1173 /// let bits = bits![0, 0, 0, 1, 1, 1];
1174 /// let base = bits.as_bitptr();
1175 ///
1176 /// let (a, b) = bits.split_at(0);
1177 /// assert_eq!(unsafe { a.as_bitptr().offset_from(base) }, 0);
1178 /// assert_eq!(unsafe { b.as_bitptr().offset_from(base) }, 0);
1179 ///
1180 /// let (a, b) = bits.split_at(6);
1181 /// assert_eq!(unsafe { b.as_bitptr().offset_from(base) }, 6);
1182 ///
1183 /// let (a, b) = bits.split_at(3);
1184 /// assert_eq!(a, bits![0; 3]);
1185 /// assert_eq!(b, bits![1; 3]);
1186 /// ```
1187 #[inline]
1188 pub fn split_at(&self, mid: usize) -> (&Self, &Self) {
1189 self.assert_in_bounds(mid, 0 ..= self.len());
1190 unsafe { self.split_at_unchecked(mid) }
1191 }
1192
1193 /// Splits a mutable bit-slice in two parts at an index.
1194 ///
1195 /// The returned bit-slices are `self[.. mid]` and `self[mid ..]`. `mid` is
1196 /// included in the right bit-slice, not the left.
1197 ///
1198 /// If `mid` is `0` then the left bit-slice is empty; if it is `self.len()`
1199 /// then the right bit-slice is empty.
1200 ///
1201 /// This method guarantees that even when either partition is empty, the
1202 /// encoded bit-pointer values of the bit-slice references is `&self[0]` and
1203 /// `&self[mid]`.
1204 ///
1205 /// ## Original
1206 ///
1207 /// [`slice::split_at_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.split_at_mut)
1208 ///
1209 /// ## API Differences
1210 ///
1211 /// The end bits of the left half and the start bits of the right half might
1212 /// be stored in the same memory element. In order to avoid breaking
1213 /// `bitvec`’s memory-safety guarantees, both bit-slices are marked as
1214 /// `T::Alias`. This marking allows them to be used without interfering with
1215 /// each other when they interact with memory.
1216 ///
1217 /// ## Panics
1218 ///
1219 /// This panics if `mid` is greater than `self.len()`. It is allowed to be
1220 /// equal to the length, in which case the right bit-slice is simply empty.
1221 ///
1222 /// ## Examples
1223 ///
1224 /// ```rust
1225 /// use bitvec::prelude::*;
1226 ///
1227 /// let bits = bits![mut u8, Msb0; 0; 6];
1228 /// let base = bits.as_mut_bitptr();
1229 ///
1230 /// let (a, b) = bits.split_at_mut(0);
1231 /// assert_eq!(unsafe { a.as_mut_bitptr().offset_from(base) }, 0);
1232 /// assert_eq!(unsafe { b.as_mut_bitptr().offset_from(base) }, 0);
1233 ///
1234 /// let (a, b) = bits.split_at_mut(6);
1235 /// assert_eq!(unsafe { b.as_mut_bitptr().offset_from(base) }, 6);
1236 ///
1237 /// let (a, b) = bits.split_at_mut(3);
1238 /// a.store(3);
1239 /// b.store(5);
1240 ///
1241 /// assert_eq!(bits, bits![0, 1, 1, 1, 0, 1]);
1242 /// ```
1243 #[inline]
1244 pub fn split_at_mut(
1245 &mut self,
1246 mid: usize,
1247 ) -> (&mut BitSlice<T::Alias, O>, &mut BitSlice<T::Alias, O>) {
1248 self.assert_in_bounds(mid, 0 ..= self.len());
1249 unsafe { self.split_at_unchecked_mut(mid) }
1250 }
1251
1252 /// Iterates over subslices separated by bits that match a predicate. The
1253 /// matched bit is *not* contained in the yielded bit-slices.
1254 ///
1255 /// ## Original
1256 ///
1257 /// [`slice::split`](https://doc.rust-lang.org/std/primitive.slice.html#method.split)
1258 ///
1259 /// ## API Differences
1260 ///
1261 /// The predicate function receives the index being tested as well as the
1262 /// bit value at that index. This allows the predicate to have more than one
1263 /// bit of information about the bit-slice being traversed.
1264 ///
1265 /// ## Sibling Methods
1266 ///
1267 /// - [`.split_mut()`] has the same splitting logic, but each yielded
1268 /// bit-slice is mutable.
1269 /// - [`.split_inclusive()`] includes the matched bit in the yielded
1270 /// bit-slice.
1271 /// - [`.rsplit()`] iterates from the back of the bit-slice instead of the
1272 /// front.
1273 /// - [`.splitn()`] times out after `n` yields.
1274 ///
1275 /// ## Examples
1276 ///
1277 /// ```rust
1278 /// use bitvec::prelude::*;
1279 ///
1280 /// let bits = bits![0, 1, 1, 0];
1281 /// // ^
1282 /// let mut iter = bits.split(|pos, _bit| pos % 3 == 2);
1283 ///
1284 /// assert_eq!(iter.next().unwrap(), bits![0, 1]);
1285 /// assert_eq!(iter.next().unwrap(), bits![0]);
1286 /// assert!(iter.next().is_none());
1287 /// ```
1288 ///
1289 /// If the first bit is matched, then an empty bit-slice will be the first
1290 /// item yielded by the iterator. Similarly, if the last bit in the
1291 /// bit-slice matches, then an empty bit-slice will be the last item
1292 /// yielded.
1293 ///
1294 /// ```rust
1295 /// use bitvec::prelude::*;
1296 ///
1297 /// let bits = bits![0, 0, 1];
1298 /// // ^
1299 /// let mut iter = bits.split(|_pos, bit| *bit);
1300 ///
1301 /// assert_eq!(iter.next().unwrap(), bits![0; 2]);
1302 /// assert!(iter.next().unwrap().is_empty());
1303 /// assert!(iter.next().is_none());
1304 /// ```
1305 ///
1306 /// If two matched bits are directly adjacent, then an empty bit-slice will
1307 /// be yielded between them:
1308 ///
1309 /// ```rust
1310 /// use bitvec::prelude::*;
1311 ///
1312 /// let bits = bits![1, 0, 0, 1];
1313 /// // ^ ^
1314 /// let mut iter = bits.split(|_pos, bit| !*bit);
1315 ///
1316 /// assert_eq!(iter.next().unwrap(), bits![1]);
1317 /// assert!(iter.next().unwrap().is_empty());
1318 /// assert_eq!(iter.next().unwrap(), bits![1]);
1319 /// assert!(iter.next().is_none());
1320 /// ```
1321 ///
1322 /// [`.rsplit()`]: Self::rsplit
1323 /// [`.splitn()`]: Self::splitn
1324 /// [`.split_inclusive()`]: Self::split_inclusive
1325 /// [`.split_mut()`]: Self::split_mut
1326 #[inline]
1327 pub fn split<F>(&self, pred: F) -> Split<T, O, F>
1328 where F: FnMut(usize, &bool) -> bool {
1329 Split::new(self, pred)
1330 }
1331
1332 /// Iterates over mutable subslices separated by bits that match a
1333 /// predicate. The matched bit is *not* contained in the yielded bit-slices.
1334 ///
1335 /// Iterators do not require that each yielded item is destroyed before the
1336 /// next is produced. This means that each bit-slice yielded must be marked
1337 /// as aliased. If you are using this in a loop that does not collect
1338 /// multiple yielded subslices for the same scope, then you can remove the
1339 /// alias marking by calling the (`unsafe`) method [`.remove_alias()`] on
1340 /// the iterator.
1341 ///
1342 /// ## Original
1343 ///
1344 /// [`slice::split_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.split_mut)
1345 ///
1346 /// ## API Differences
1347 ///
1348 /// The predicate function receives the index being tested as well as the
1349 /// bit value at that index. This allows the predicate to have more than one
1350 /// bit of information about the bit-slice being traversed.
1351 ///
1352 /// ## Sibling Methods
1353 ///
1354 /// - [`.split()`] has the same splitting logic, but each yielded bit-slice
1355 /// is immutable.
1356 /// - [`.split_inclusive_mut()`] includes the matched bit in the yielded
1357 /// bit-slice.
1358 /// - [`.rsplit_mut()`] iterates from the back of the bit-slice instead of
1359 /// the front.
1360 /// - [`.splitn_mut()`] times out after `n` yields.
1361 ///
1362 /// ## Examples
1363 ///
1364 /// ```rust
1365 /// use bitvec::prelude::*;
1366 ///
1367 /// let bits = bits![mut 0, 0, 1, 0, 1, 0];
1368 /// // ^ ^
1369 /// for group in bits.split_mut(|_pos, bit| *bit) {
1370 /// group.set(0, true);
1371 /// }
1372 /// assert_eq!(bits, bits![1, 0, 1, 1, 1, 1]);
1373 /// ```
1374 ///
1375 /// [`.remove_alias()`]: crate::slice::SplitMut::remove_alias
1376 /// [`.rsplit_mut()`]: Self::rsplit_mut
1377 /// [`.split()`]: Self::split
1378 /// [`.split_inclusive_mut()`]: Self::split_inclusive_mut
1379 /// [`.splitn_mut()`]: Self::splitn_mut
1380 #[inline]
1381 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, O, F>
1382 where F: FnMut(usize, &bool) -> bool {
1383 SplitMut::new(self.alias_mut(), pred)
1384 }
1385
1386 /// Iterates over subslices separated by bits that match a predicate. Unlike
1387 /// `.split()`, this *does* include the matching bit as the last bit in the
1388 /// yielded bit-slice.
1389 ///
1390 /// ## Original
1391 ///
1392 /// [`slice::split_inclusive`](https://doc.rust-lang.org/std/primitive.slice.html#method.split_inclusive)
1393 ///
1394 /// ## API Differences
1395 ///
1396 /// The predicate function receives the index being tested as well as the
1397 /// bit value at that index. This allows the predicate to have more than one
1398 /// bit of information about the bit-slice being traversed.
1399 ///
1400 /// ## Sibling Methods
1401 ///
1402 /// - [`.split_inclusive_mut()`] has the same splitting logic, but each
1403 /// yielded bit-slice is mutable.
1404 /// - [`.split()`] does not include the matched bit in the yielded
1405 /// bit-slice.
1406 ///
1407 /// ## Examples
1408 ///
1409 /// ```rust
1410 /// use bitvec::prelude::*;
1411 ///
1412 /// let bits = bits![0, 0, 1, 0, 1];
1413 /// // ^ ^
1414 /// let mut iter = bits.split_inclusive(|_pos, bit| *bit);
1415 ///
1416 /// assert_eq!(iter.next().unwrap(), bits![0, 0, 1]);
1417 /// assert_eq!(iter.next().unwrap(), bits![0, 1]);
1418 /// assert!(iter.next().is_none());
1419 /// ```
1420 ///
1421 /// [`.split()`]: Self::split
1422 /// [`.split_inclusive_mut()`]: Self::split_inclusive_mut
1423 #[inline]
1424 pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<T, O, F>
1425 where F: FnMut(usize, &bool) -> bool {
1426 SplitInclusive::new(self, pred)
1427 }
1428
1429 /// Iterates over mutable subslices separated by bits that match a
1430 /// predicate. Unlike `.split_mut()`, this *does* include the matching bit
1431 /// as the last bit in the bit-slice.
1432 ///
1433 /// Iterators do not require that each yielded item is destroyed before the
1434 /// next is produced. This means that each bit-slice yielded must be marked
1435 /// as aliased. If you are using this in a loop that does not collect
1436 /// multiple yielded subslices for the same scope, then you can remove the
1437 /// alias marking by calling the (`unsafe`) method [`.remove_alias()`] on
1438 /// the iterator.
1439 ///
1440 /// ## Original
1441 ///
1442 /// [`slice::split_inclusive_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.split_inclusive_mut)
1443 ///
1444 /// ## API Differences
1445 ///
1446 /// The predicate function receives the index being tested as well as the
1447 /// bit value at that index. This allows the predicate to have more than one
1448 /// bit of information about the bit-slice being traversed.
1449 ///
1450 /// ## Sibling Methods
1451 ///
1452 /// - [`.split_inclusive()`] has the same splitting logic, but each yielded
1453 /// bit-slice is immutable.
1454 /// - [`.split_mut()`] does not include the matched bit in the yielded
1455 /// bit-slice.
1456 ///
1457 /// ## Examples
1458 ///
1459 /// ```rust
1460 /// use bitvec::prelude::*;
1461 ///
1462 /// let bits = bits![mut 0, 0, 0, 0, 0];
1463 /// // ^
1464 /// for group in bits.split_inclusive_mut(|pos, _bit| pos % 3 == 2) {
1465 /// group.set(0, true);
1466 /// }
1467 /// assert_eq!(bits, bits![1, 0, 0, 1, 0]);
1468 /// ```
1469 ///
1470 /// [`.remove_alias()`]: crate::slice::SplitInclusiveMut::remove_alias
1471 /// [`.split_inclusive()`]: Self::split_inclusive
1472 /// [`.split_mut()`]: Self::split_mut
1473 #[inline]
1474 pub fn split_inclusive_mut<F>(
1475 &mut self,
1476 pred: F,
1477 ) -> SplitInclusiveMut<T, O, F>
1478 where
1479 F: FnMut(usize, &bool) -> bool,
1480 {
1481 SplitInclusiveMut::new(self.alias_mut(), pred)
1482 }
1483
1484 /// Iterates over subslices separated by bits that match a predicate, from
1485 /// the back edge. The matched bit is *not* contained in the yielded
1486 /// bit-slices.
1487 ///
1488 /// ## Original
1489 ///
1490 /// [`slice::rsplit`](https://doc.rust-lang.org/std/primitive.slice.html#method.rsplit)
1491 ///
1492 /// ## API Differences
1493 ///
1494 /// The predicate function receives the index being tested as well as the
1495 /// bit value at that index. This allows the predicate to have more than one
1496 /// bit of information about the bit-slice being traversed.
1497 ///
1498 /// ## Sibling Methods
1499 ///
1500 /// - [`.rsplit_mut()`] has the same splitting logic, but each yielded
1501 /// bit-slice is mutable.
1502 /// - [`.split()`] iterates from the front of the bit-slice instead of the
1503 /// back.
1504 /// - [`.rsplitn()`] times out after `n` yields.
1505 ///
1506 /// ## Examples
1507 ///
1508 /// ```rust
1509 /// use bitvec::prelude::*;
1510 ///
1511 /// let bits = bits![0, 1, 1, 0];
1512 /// // ^
1513 /// let mut iter = bits.rsplit(|pos, _bit| pos % 3 == 2);
1514 ///
1515 /// assert_eq!(iter.next().unwrap(), bits![0]);
1516 /// assert_eq!(iter.next().unwrap(), bits![0, 1]);
1517 /// assert!(iter.next().is_none());
1518 /// ```
1519 ///
1520 /// If the last bit is matched, then an empty bit-slice will be the first
1521 /// item yielded by the iterator. Similarly, if the first bit in the
1522 /// bit-slice matches, then an empty bit-slice will be the last item
1523 /// yielded.
1524 ///
1525 /// ```rust
1526 /// use bitvec::prelude::*;
1527 ///
1528 /// let bits = bits![0, 0, 1];
1529 /// // ^
1530 /// let mut iter = bits.rsplit(|_pos, bit| *bit);
1531 ///
1532 /// assert!(iter.next().unwrap().is_empty());
1533 /// assert_eq!(iter.next().unwrap(), bits![0; 2]);
1534 /// assert!(iter.next().is_none());
1535 /// ```
1536 ///
1537 /// If two yielded bits are directly adjacent, then an empty bit-slice will
1538 /// be yielded between them:
1539 ///
1540 /// ```rust
1541 /// use bitvec::prelude::*;
1542 ///
1543 /// let bits = bits![1, 0, 0, 1];
1544 /// // ^ ^
1545 /// let mut iter = bits.split(|_pos, bit| !*bit);
1546 ///
1547 /// assert_eq!(iter.next().unwrap(), bits![1]);
1548 /// assert!(iter.next().unwrap().is_empty());
1549 /// assert_eq!(iter.next().unwrap(), bits![1]);
1550 /// assert!(iter.next().is_none());
1551 /// ```
1552 ///
1553 /// [`.rsplitn()`]: Self::rsplitn
1554 /// [`.rsplit_mut()`]: Self::rsplit_mut
1555 /// [`.split()`]: Self::split
1556 #[inline]
1557 pub fn rsplit<F>(&self, pred: F) -> RSplit<T, O, F>
1558 where F: FnMut(usize, &bool) -> bool {
1559 RSplit::new(self, pred)
1560 }
1561
1562 /// Iterates over mutable subslices separated by bits that match a
1563 /// predicate, from the back. The matched bit is *not* contained in the
1564 /// yielded bit-slices.
1565 ///
1566 /// Iterators do not require that each yielded item is destroyed before the
1567 /// next is produced. This means that each bit-slice yielded must be marked
1568 /// as aliased. If you are using this in a loop that does not collect
1569 /// multiple yielded subslices for the same scope, then you can remove the
1570 /// alias marking by calling the (`unsafe`) method [`.remove_alias()`] on
1571 /// the iterator.
1572 ///
1573 /// ## Original
1574 ///
1575 /// [`slice::rsplit_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.rsplit_mut)
1576 ///
1577 /// ## API Differences
1578 ///
1579 /// The predicate function receives the index being tested as well as the
1580 /// bit value at that index. This allows the predicate to have more than one
1581 /// bit of information about the bit-slice being traversed.
1582 ///
1583 /// ## Sibling Methods
1584 ///
1585 /// - [`.rsplit()`] has the same splitting logic, but each yielded bit-slice
1586 /// is immutable.
1587 /// - [`.split_mut()`] iterates from the front of the bit-slice to the back.
1588 /// - [`.rsplitn_mut()`] iterates from the front of the bit-slice to the
1589 /// back.
1590 ///
1591 /// ## Examples
1592 ///
1593 /// ```rust
1594 /// use bitvec::prelude::*;
1595 ///
1596 /// let bits = bits![mut 0, 0, 1, 0, 1, 0];
1597 /// // ^ ^
1598 /// for group in bits.rsplit_mut(|_pos, bit| *bit) {
1599 /// group.set(0, true);
1600 /// }
1601 /// assert_eq!(bits, bits![1, 0, 1, 1, 1, 1]);
1602 /// ```
1603 ///
1604 /// [`.remove_alias()`]: crate::slice::RSplitMut::remove_alias
1605 /// [`.rsplit()`]: Self::rsplit
1606 /// [`.rsplitn_mut()`]: Self::rsplitn_mut
1607 /// [`.split_mut()`]: Self::split_mut
1608 #[inline]
1609 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<T, O, F>
1610 where F: FnMut(usize, &bool) -> bool {
1611 RSplitMut::new(self.alias_mut(), pred)
1612 }
1613
1614 /// Iterates over subslices separated by bits that match a predicate, giving
1615 /// up after yielding `n` times. The `n`th yield contains the rest of the
1616 /// bit-slice. As with `.split()`, the yielded bit-slices do not contain the
1617 /// matched bit.
1618 ///
1619 /// ## Original
1620 ///
1621 /// [`slice::splitn`](https://doc.rust-lang.org/std/primitive.slice.html#method.splitn)
1622 ///
1623 /// ## API Differences
1624 ///
1625 /// The predicate function receives the index being tested as well as the
1626 /// bit value at that index. This allows the predicate to have more than one
1627 /// bit of information about the bit-slice being traversed.
1628 ///
1629 /// ## Sibling Methods
1630 ///
1631 /// - [`.splitn_mut()`] has the same splitting logic, but each yielded
1632 /// bit-slice is mutable.
1633 /// - [`.rsplitn()`] iterates from the back of the bit-slice instead of the
1634 /// front.
1635 /// - [`.split()`] has the same splitting logic, but never times out.
1636 ///
1637 /// ## Examples
1638 ///
1639 /// ```rust
1640 /// use bitvec::prelude::*;
1641 ///
1642 /// let bits = bits![0, 0, 1, 0, 1, 0];
1643 /// let mut iter = bits.splitn(2, |_pos, bit| *bit);
1644 ///
1645 /// assert_eq!(iter.next().unwrap(), bits![0, 0]);
1646 /// assert_eq!(iter.next().unwrap(), bits![0, 1, 0]);
1647 /// assert!(iter.next().is_none());
1648 /// ```
1649 ///
1650 /// [`.rsplitn()`]: Self::rsplitn
1651 /// [`.split()`]: Self::split
1652 /// [`.splitn_mut()`]: Self::splitn_mut
1653 #[inline]
1654 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, O, F>
1655 where F: FnMut(usize, &bool) -> bool {
1656 SplitN::new(self, pred, n)
1657 }
1658
1659 /// Iterates over mutable subslices separated by bits that match a
1660 /// predicate, giving up after yielding `n` times. The `n`th yield contains
1661 /// the rest of the bit-slice. As with `.split_mut()`, the yielded
1662 /// bit-slices do not contain the matched bit.
1663 ///
1664 /// Iterators do not require that each yielded item is destroyed before the
1665 /// next is produced. This means that each bit-slice yielded must be marked
1666 /// as aliased. If you are using this in a loop that does not collect
1667 /// multiple yielded subslices for the same scope, then you can remove the
1668 /// alias marking by calling the (`unsafe`) method [`.remove_alias()`] on
1669 /// the iterator.
1670 ///
1671 /// ## Original
1672 ///
1673 /// [`slice::splitn_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.splitn_mut)
1674 ///
1675 /// ## API Differences
1676 ///
1677 /// The predicate function receives the index being tested as well as the
1678 /// bit value at that index. This allows the predicate to have more than one
1679 /// bit of information about the bit-slice being traversed.
1680 ///
1681 /// ## Sibling Methods
1682 ///
1683 /// - [`.splitn()`] has the same splitting logic, but each yielded bit-slice
1684 /// is immutable.
1685 /// - [`.rsplitn_mut()`] iterates from the back of the bit-slice instead of
1686 /// the front.
1687 /// - [`.split_mut()`] has the same splitting logic, but never times out.
1688 ///
1689 /// ## Examples
1690 ///
1691 /// ```rust
1692 /// use bitvec::prelude::*;
1693 ///
1694 /// let bits = bits![mut 0, 0, 1, 0, 1, 0];
1695 /// for group in bits.splitn_mut(2, |_pos, bit| *bit) {
1696 /// group.set(0, true);
1697 /// }
1698 /// assert_eq!(bits, bits![1, 0, 1, 1, 1, 0]);
1699 /// ```
1700 ///
1701 /// [`.remove_alias()`]: crate::slice::SplitNMut::remove_alias
1702 /// [`.rsplitn_mut()`]: Self::rsplitn_mut
1703 /// [`.split_mut()`]: Self::split_mut
1704 /// [`.splitn()`]: Self::splitn
1705 #[inline]
1706 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, O, F>
1707 where F: FnMut(usize, &bool) -> bool {
1708 SplitNMut::new(self.alias_mut(), pred, n)
1709 }
1710
1711 /// Iterates over mutable subslices separated by bits that match a
1712 /// predicate from the back edge, giving up after yielding `n` times. The
1713 /// `n`th yield contains the rest of the bit-slice. As with `.split_mut()`,
1714 /// the yielded bit-slices do not contain the matched bit.
1715 ///
1716 /// ## Original
1717 ///
1718 /// [`slice::rsplitn`](https://doc.rust-lang.org/std/primitive.slice.html#method.rsplitn)
1719 ///
1720 /// ## API Differences
1721 ///
1722 /// The predicate function receives the index being tested as well as the
1723 /// bit value at that index. This allows the predicate to have more than one
1724 /// bit of information about the bit-slice being traversed.
1725 ///
1726 /// ## Sibling Methods
1727 ///
1728 /// - [`.rsplitn_mut()`] has the same splitting logic, but each yielded
1729 /// bit-slice is mutable.
1730 /// - [`.splitn()`]: iterates from the front of the bit-slice instead of the
1731 /// back.
1732 /// - [`.rsplit()`] has the same splitting logic, but never times out.
1733 ///
1734 /// ## Examples
1735 ///
1736 /// ```rust
1737 /// use bitvec::prelude::*;
1738 ///
1739 /// let bits = bits![0, 0, 1, 1, 0];
1740 /// // ^
1741 /// let mut iter = bits.rsplitn(2, |_pos, bit| *bit);
1742 ///
1743 /// assert_eq!(iter.next().unwrap(), bits![0]);
1744 /// assert_eq!(iter.next().unwrap(), bits![0, 0, 1]);
1745 /// assert!(iter.next().is_none());
1746 /// ```
1747 ///
1748 /// [`.rsplit()`]: Self::rsplit
1749 /// [`.rsplitn_mut()`]: Self::rsplitn_mut
1750 /// [`.splitn()`]: Self::splitn
1751 #[inline]
1752 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, O, F>
1753 where F: FnMut(usize, &bool) -> bool {
1754 RSplitN::new(self, pred, n)
1755 }
1756
1757 /// Iterates over mutable subslices separated by bits that match a
1758 /// predicate from the back edge, giving up after yielding `n` times. The
1759 /// `n`th yield contains the rest of the bit-slice. As with `.split_mut()`,
1760 /// the yielded bit-slices do not contain the matched bit.
1761 ///
1762 /// Iterators do not require that each yielded item is destroyed before the
1763 /// next is produced. This means that each bit-slice yielded must be marked
1764 /// as aliased. If you are using this in a loop that does not collect
1765 /// multiple yielded subslices for the same scope, then you can remove the
1766 /// alias marking by calling the (`unsafe`) method [`.remove_alias()`] on
1767 /// the iterator.
1768 ///
1769 /// ## Original
1770 ///
1771 /// [`slice::rsplitn_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.rsplitn_mut)
1772 ///
1773 /// ## API Differences
1774 ///
1775 /// The predicate function receives the index being tested as well as the
1776 /// bit value at that index. This allows the predicate to have more than one
1777 /// bit of information about the bit-slice being traversed.
1778 ///
1779 /// ## Sibling Methods
1780 ///
1781 /// - [`.rsplitn()`] has the same splitting logic, but each yielded
1782 /// bit-slice is immutable.
1783 /// - [`.splitn_mut()`] iterates from the front of the bit-slice instead of
1784 /// the back.
1785 /// - [`.rsplit_mut()`] has the same splitting logic, but never times out.
1786 ///
1787 /// ## Examples
1788 ///
1789 /// ```rust
1790 /// use bitvec::prelude::*;
1791 ///
1792 /// let bits = bits![mut 0, 0, 1, 0, 0, 1, 0, 0, 0];
1793 /// for group in bits.rsplitn_mut(2, |_idx, bit| *bit) {
1794 /// group.set(0, true);
1795 /// }
1796 /// assert_eq!(bits, bits![1, 0, 1, 0, 0, 1, 1, 0, 0]);
1797 /// // ^ group 2 ^ group 1
1798 /// ```
1799 ///
1800 /// [`.remove_alias()`]: crate::slice::RSplitNMut::remove_alias
1801 /// [`.rsplitn()`]: Self::rsplitn
1802 /// [`.rsplit_mut()`]: Self::rsplit_mut
1803 /// [`.splitn_mut()`]: Self::splitn_mut
1804 #[inline]
1805 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, O, F>
1806 where F: FnMut(usize, &bool) -> bool {
1807 RSplitNMut::new(self.alias_mut(), pred, n)
1808 }
1809
1810 /// Tests if the bit-slice contains the given sequence anywhere within it.
1811 ///
1812 /// This scans over `self.windows(other.len())` until one of the windows
1813 /// matches. The search key does not need to share type parameters with the
1814 /// bit-slice being tested, as the comparison is bit-wise. However, sharing
1815 /// type parameters will accelerate the comparison.
1816 ///
1817 /// ## Original
1818 ///
1819 /// [`slice::contains`](https://doc.rust-lang.org/std/primitive.slice.html#method.contains)
1820 ///
1821 /// ## Examples
1822 ///
1823 /// ```rust
1824 /// use bitvec::prelude::*;
1825 ///
1826 /// let bits = bits![0, 0, 1, 0, 1, 1, 0, 0];
1827 /// assert!( bits.contains(bits![0, 1, 1, 0]));
1828 /// assert!(!bits.contains(bits![1, 0, 0, 1]));
1829 /// ```
1830 #[inline]
1831 pub fn contains<T2, O2>(&self, other: &BitSlice<T2, O2>) -> bool
1832 where
1833 T2: BitStore,
1834 O2: BitOrder,
1835 {
1836 self.len() >= other.len()
1837 && self.windows(other.len()).any(|window| window == other)
1838 }
1839
1840 /// Tests if the bit-slice begins with the given sequence.
1841 ///
1842 /// The search key does not need to share type parameters with the bit-slice
1843 /// being tested, as the comparison is bit-wise. However, sharing type
1844 /// parameters will accelerate the comparison.
1845 ///
1846 /// ## Original
1847 ///
1848 /// [`slice::starts_with`](https://doc.rust-lang.org/std/primitive.slice.html#method.starts_with)
1849 ///
1850 /// ## Examples
1851 ///
1852 /// ```rust
1853 /// use bitvec::prelude::*;
1854 ///
1855 /// let bits = bits![0, 1, 1, 0];
1856 /// assert!( bits.starts_with(bits![0, 1]));
1857 /// assert!(!bits.starts_with(bits![1, 0]));
1858 /// ```
1859 ///
1860 /// This always returns `true` if the needle is empty:
1861 ///
1862 /// ```rust
1863 /// use bitvec::prelude::*;
1864 ///
1865 /// let bits = bits![0, 1, 0];
1866 /// let empty = bits![];
1867 /// assert!(bits.starts_with(empty));
1868 /// assert!(empty.starts_with(empty));
1869 /// ```
1870 #[inline]
1871 pub fn starts_with<T2, O2>(&self, needle: &BitSlice<T2, O2>) -> bool
1872 where
1873 T2: BitStore,
1874 O2: BitOrder,
1875 {
1876 self.get(.. needle.len())
1877 .map(|slice| slice == needle)
1878 .unwrap_or(false)
1879 }
1880
1881 /// Tests if the bit-slice ends with the given sequence.
1882 ///
1883 /// The search key does not need to share type parameters with the bit-slice
1884 /// being tested, as the comparison is bit-wise. However, sharing type
1885 /// parameters will accelerate the comparison.
1886 ///
1887 /// ## Original
1888 ///
1889 /// [`slice::ends_with`](https://doc.rust-lang.org/std/primitive.slice.html#method.ends_with)
1890 ///
1891 /// ## Examples
1892 ///
1893 /// ```rust
1894 /// use bitvec::prelude::*;
1895 ///
1896 /// let bits = bits![0, 1, 1, 0];
1897 /// assert!( bits.ends_with(bits![1, 0]));
1898 /// assert!(!bits.ends_with(bits![0, 1]));
1899 /// ```
1900 ///
1901 /// This always returns `true` if the needle is empty:
1902 ///
1903 /// ```rust
1904 /// use bitvec::prelude::*;
1905 ///
1906 /// let bits = bits![0, 1, 0];
1907 /// let empty = bits![];
1908 /// assert!(bits.ends_with(empty));
1909 /// assert!(empty.ends_with(empty));
1910 /// ```
1911 #[inline]
1912 pub fn ends_with<T2, O2>(&self, needle: &BitSlice<T2, O2>) -> bool
1913 where
1914 T2: BitStore,
1915 O2: BitOrder,
1916 {
1917 self.get(self.len() - needle.len() ..)
1918 .map(|slice| slice == needle)
1919 .unwrap_or(false)
1920 }
1921
1922 /// Removes a prefix bit-slice, if present.
1923 ///
1924 /// Like [`.starts_with()`], the search key does not need to share type
1925 /// parameters with the bit-slice being stripped. If
1926 /// `self.starts_with(suffix)`, then this returns `Some(&self[prefix.len()
1927 /// ..])`, otherwise it returns `None`.
1928 ///
1929 /// ## Original
1930 ///
1931 /// [`slice::strip_prefix`](https://doc.rust-lang.org/std/primitive.slice.html#method.strip_prefix)
1932 ///
1933 /// ## API Differences
1934 ///
1935 /// `BitSlice` does not support pattern searches; instead, it permits `self`
1936 /// and `prefix` to differ in type parameters.
1937 ///
1938 /// ## Examples
1939 ///
1940 /// ```rust
1941 /// use bitvec::prelude::*;
1942 ///
1943 /// let bits = bits![0, 1, 0, 0, 1, 0, 1, 1, 0];
1944 /// assert_eq!(bits.strip_prefix(bits![0, 1]).unwrap(), bits[2 ..]);
1945 /// assert_eq!(bits.strip_prefix(bits![0, 1, 0, 0,]).unwrap(), bits[4 ..]);
1946 /// assert!(bits.strip_prefix(bits![1, 0]).is_none());
1947 /// ```
1948 ///
1949 /// [`.starts_with()`]: Self::starts_with
1950 #[inline]
1951 pub fn strip_prefix<T2, O2>(
1952 &self,
1953 prefix: &BitSlice<T2, O2>,
1954 ) -> Option<&Self>
1955 where
1956 T2: BitStore,
1957 O2: BitOrder,
1958 {
1959 if self.starts_with(prefix) {
1960 self.get(prefix.len() ..)
1961 }
1962 else {
1963 None
1964 }
1965 }
1966
1967 /// Removes a suffix bit-slice, if present.
1968 ///
1969 /// Like [`.ends_with()`], the search key does not need to share type
1970 /// parameters with the bit-slice being stripped. If
1971 /// `self.ends_with(suffix)`, then this returns `Some(&self[.. self.len() -
1972 /// suffix.len()])`, otherwise it returns `None`.
1973 ///
1974 /// ## Original
1975 ///
1976 /// [`slice::strip_suffix`](https://doc.rust-lang.org/std/primitive.slice.html#method.strip_suffix)
1977 ///
1978 /// ## API Differences
1979 ///
1980 /// `BitSlice` does not support pattern searches; instead, it permits `self`
1981 /// and `suffix` to differ in type parameters.
1982 ///
1983 /// ## Examples
1984 ///
1985 /// ```rust
1986 /// use bitvec::prelude::*;
1987 ///
1988 /// let bits = bits![0, 1, 0, 0, 1, 0, 1, 1, 0];
1989 /// assert_eq!(bits.strip_suffix(bits![1, 0]).unwrap(), bits[.. 7]);
1990 /// assert_eq!(bits.strip_suffix(bits![0, 1, 1, 0]).unwrap(), bits[.. 5]);
1991 /// assert!(bits.strip_suffix(bits![0, 1]).is_none());
1992 /// ```
1993 ///
1994 /// [`.ends_with()`]: Self::ends_with.
1995 #[inline]
1996 pub fn strip_suffix<T2, O2>(
1997 &self,
1998 suffix: &BitSlice<T2, O2>,
1999 ) -> Option<&Self>
2000 where
2001 T2: BitStore,
2002 O2: BitOrder,
2003 {
2004 if self.ends_with(suffix) {
2005 self.get(.. self.len() - suffix.len())
2006 }
2007 else {
2008 None
2009 }
2010 }
2011
2012 /// Rotates the contents of a bit-slice to the left (towards the zero
2013 /// index).
2014 ///
2015 /// This essentially splits the bit-slice at `by`, then exchanges the two
2016 /// pieces. `self[.. by]` becomes the first section, and is then followed by
2017 /// `self[.. by]`.
2018 ///
2019 /// The implementation is batch-accelerated where possible. It should have a
2020 /// runtime complexity much lower than `O(by)`.
2021 ///
2022 /// ## Original
2023 ///
2024 /// [`slice::rotate_left`](https://doc.rust-lang.org/std/primitive.slice.html#method.rotate_left)
2025 ///
2026 /// ## Examples
2027 ///
2028 /// ```rust
2029 /// use bitvec::prelude::*;
2030 ///
2031 /// let bits = bits![mut 0, 0, 1, 0, 1, 0];
2032 /// // split occurs here ^
2033 /// bits.rotate_left(2);
2034 /// assert_eq!(bits, bits![1, 0, 1, 0, 0, 0]);
2035 /// ```
2036 #[inline]
2037 pub fn rotate_left(&mut self, mut by: usize) {
2038 let len = self.len();
2039 assert!(
2040 by <= len,
2041 "bit-slices cannot be rotated by more than their length",
2042 );
2043 if by == 0 || by == len {
2044 return;
2045 }
2046 let mut tmp = BitArray::<usize, O>::ZERO;
2047 while by > 0 {
2048 let shamt = cmp::min(mem::bits_of::<usize>(), by);
2049 unsafe {
2050 let tmp_bits = tmp.get_unchecked_mut(.. shamt);
2051 tmp_bits.clone_from_bitslice(self.get_unchecked(.. shamt));
2052 self.copy_within_unchecked(shamt .., 0);
2053 self.get_unchecked_mut(len - shamt ..)
2054 .clone_from_bitslice(tmp_bits);
2055 }
2056 by -= shamt;
2057 }
2058 }
2059
2060 /// Rotates the contents of a bit-slice to the right (away from the zero
2061 /// index).
2062 ///
2063 /// This essentially splits the bit-slice at `self.len() - by`, then
2064 /// exchanges the two pieces. `self[len - by ..]` becomes the first section,
2065 /// and is then followed by `self[.. len - by]`.
2066 ///
2067 /// The implementation is batch-accelerated where possible. It should have a
2068 /// runtime complexity much lower than `O(by)`.
2069 ///
2070 /// ## Original
2071 ///
2072 /// [`slice::rotate_right`](https://doc.rust-lang.org/std/primitive.slice.html#method.rotate_right)
2073 ///
2074 /// ## Examples
2075 ///
2076 /// ```rust
2077 /// use bitvec::prelude::*;
2078 ///
2079 /// let bits = bits![mut 0, 0, 1, 1, 1, 0];
2080 /// // split occurs here ^
2081 /// bits.rotate_right(2);
2082 /// assert_eq!(bits, bits![1, 0, 0, 0, 1, 1]);
2083 /// ```
2084 #[inline]
2085 pub fn rotate_right(&mut self, mut by: usize) {
2086 let len = self.len();
2087 assert!(
2088 by <= len,
2089 "bit-slices cannot be rotated by more than their length",
2090 );
2091 if by == 0 || by == len {
2092 return;
2093 }
2094 let mut tmp = BitArray::<usize, O>::ZERO;
2095 while by > 0 {
2096 let shamt = cmp::min(mem::bits_of::<usize>(), by);
2097 let mid = len - shamt;
2098 unsafe {
2099 let tmp_bits = tmp.get_unchecked_mut(.. shamt);
2100 tmp_bits.clone_from_bitslice(self.get_unchecked(mid ..));
2101 self.copy_within_unchecked(.. mid, shamt);
2102 self.get_unchecked_mut(.. shamt)
2103 .clone_from_bitslice(tmp_bits);
2104 }
2105 by -= shamt;
2106 }
2107 }
2108
2109 /// Fills the bit-slice with a given bit.
2110 ///
2111 /// This is a recent stabilization in the standard library. `bitvec`
2112 /// previously offered this behavior as the novel API `.set_all()`. That
2113 /// method name is now removed in favor of this standard-library analogue.
2114 ///
2115 /// ## Original
2116 ///
2117 /// [`slice::fill`](https://doc.rust-lang.org/std/primitive.slice.html#method.fill)
2118 ///
2119 /// ## Examples
2120 ///
2121 /// ```rust
2122 /// use bitvec::prelude::*;
2123 ///
2124 /// let bits = bits![mut 0; 5];
2125 /// bits.fill(true);
2126 /// assert_eq!(bits, bits![1; 5]);
2127 /// ```
2128 #[inline]
2129 pub fn fill(&mut self, value: bool) {
2130 let fill = if value { T::Mem::ALL } else { T::Mem::ZERO };
2131 match self.domain_mut() {
2132 Domain::Enclave(mut elem) => {
2133 elem.store_value(fill);
2134 },
2135 Domain::Region { head, body, tail } => {
2136 if let Some(mut elem) = head {
2137 elem.store_value(fill);
2138 }
2139 for elem in body {
2140 elem.store_value(fill);
2141 }
2142 if let Some(mut elem) = tail {
2143 elem.store_value(fill);
2144 }
2145 },
2146 }
2147 }
2148
2149 /// Fills the bit-slice with bits produced by a generator function.
2150 ///
2151 /// ## Original
2152 ///
2153 /// [`slice::fill_with`](https://doc.rust-lang.org/std/primitive.slice.html#method.fill_with)
2154 ///
2155 /// ## API Differences
2156 ///
2157 /// The generator function receives the index of the bit being initialized
2158 /// as an argument.
2159 ///
2160 /// ## Examples
2161 ///
2162 /// ```rust
2163 /// use bitvec::prelude::*;
2164 ///
2165 /// let bits = bits![mut 0; 5];
2166 /// bits.fill_with(|idx| idx % 2 == 0);
2167 /// assert_eq!(bits, bits![1, 0, 1, 0, 1]);
2168 /// ```
2169 #[inline]
2170 pub fn fill_with<F>(&mut self, mut func: F)
2171 where F: FnMut(usize) -> bool {
2172 for (idx, ptr) in self.as_mut_bitptr_range().enumerate() {
2173 unsafe {
2174 ptr.write(func(idx));
2175 }
2176 }
2177 }
2178
2179 #[inline]
2180 #[cfg(not(tarpaulin_include))]
2181 #[deprecated = "use `.clone_from_bitslice()` instead"]
2182 #[allow(missing_docs, clippy::missing_docs_in_private_items)]
2183 pub fn clone_from_slice<T2, O2>(&mut self, src: &BitSlice<T2, O2>)
2184 where
2185 T2: BitStore,
2186 O2: BitOrder,
2187 {
2188 self.clone_from_bitslice(src);
2189 }
2190
2191 #[inline]
2192 #[cfg(not(tarpaulin_include))]
2193 #[deprecated = "use `.copy_from_bitslice()` instead"]
2194 #[allow(missing_docs, clippy::missing_docs_in_private_items)]
2195 pub fn copy_from_slice(&mut self, src: &Self) {
2196 self.copy_from_bitslice(src)
2197 }
2198
2199 /// Copies a span of bits to another location in the bit-slice.
2200 ///
2201 /// `src` is the range of bit-indices in the bit-slice to copy, and `dest is
2202 /// the starting index of the destination range. `src` and `dest .. dest +
2203 /// src.len()` are permitted to overlap; the copy will automatically detect
2204 /// and manage this. However, both `src` and `dest .. dest + src.len()`
2205 /// **must** fall within the bounds of `self`.
2206 ///
2207 /// ## Original
2208 ///
2209 /// [`slice::copy_within`](https://doc.rust-lang.org/std/primitive.slice.html#method.copy_within)
2210 ///
2211 /// ## Panics
2212 ///
2213 /// This panics if either the source or destination range exceed
2214 /// `self.len()`.
2215 ///
2216 /// ## Examples
2217 ///
2218 /// ```rust
2219 /// use bitvec::prelude::*;
2220 ///
2221 /// let bits = bits![mut 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0];
2222 /// bits.copy_within(1 .. 5, 8);
2223 /// // v v v v
2224 /// assert_eq!(bits, bits![1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0]);
2225 /// // ^ ^ ^ ^
2226 /// ```
2227 #[inline]
2228 pub fn copy_within<R>(&mut self, src: R, dest: usize)
2229 where R: RangeExt<usize> {
2230 let len = self.len();
2231 let src = src.normalize(0, len);
2232 self.assert_in_bounds(src.start, 0 .. len);
2233 self.assert_in_bounds(src.end, 0 ..= len);
2234 self.assert_in_bounds(dest, 0 .. len);
2235 self.assert_in_bounds(dest + src.len(), 0 ..= len);
2236 unsafe {
2237 self.copy_within_unchecked(src, dest);
2238 }
2239 }
2240
2241 #[inline]
2242 #[deprecated = "use `.swap_with_bitslice()` instead"]
2243 #[allow(missing_docs, clippy::missing_docs_in_private_items)]
2244 pub fn swap_with_slice<T2, O2>(&mut self, other: &mut BitSlice<T2, O2>)
2245 where
2246 T2: BitStore,
2247 O2: BitOrder,
2248 {
2249 self.swap_with_bitslice(other);
2250 }
2251
2252 /// Produces bit-slice view(s) with different underlying storage types.
2253 ///
2254 /// This may have unexpected effects, and you cannot assume that
2255 /// `before[idx] == after[idx]`! Consult the [tables in the manual][layout]
2256 /// for information about memory layouts.
2257 ///
2258 /// ## Original
2259 ///
2260 /// [`slice::align_to`](https://doc.rust-lang.org/std/primitive.slice.html#method.align_to)
2261 ///
2262 /// ## Notes
2263 ///
2264 /// Unlike the standard library documentation, this explicitly guarantees
2265 /// that the middle bit-slice will have maximal size. You may rely on this
2266 /// property.
2267 ///
2268 /// ## Safety
2269 ///
2270 /// You may not use this to cast away alias protections. Rust does not have
2271 /// support for higher-kinded types, so this cannot express the relation
2272 /// `Outer<T> -> Outer<U> where Outer: BitStoreContainer`, but memory safety
2273 /// does require that you respect this rule. Reälign integers to integers,
2274 /// `Cell`s to `Cell`s, and atomics to atomics, but do not cross these
2275 /// boundaries.
2276 ///
2277 /// ## Examples
2278 ///
2279 /// ```rust
2280 /// use bitvec::prelude::*;
2281 ///
2282 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2283 /// let bits = bytes.view_bits::<Lsb0>();
2284 /// let (pfx, mid, sfx) = unsafe {
2285 /// bits.align_to::<u16>()
2286 /// };
2287 /// assert!(pfx.len() <= 8);
2288 /// assert_eq!(mid.len(), 48);
2289 /// assert!(sfx.len() <= 8);
2290 /// ```
2291 ///
2292 /// [layout]: https://bitvecto-rs.github.io/bitvec/memory-layout.html
2293 #[inline]
2294 pub unsafe fn align_to<U>(&self) -> (&Self, &BitSlice<U, O>, &Self)
2295 where U: BitStore {
2296 let (l, c, r) = self.as_bitspan().align_to::<U>();
2297 (
2298 l.into_bitslice_ref(),
2299 c.into_bitslice_ref(),
2300 r.into_bitslice_ref(),
2301 )
2302 }
2303
2304 /// Produces bit-slice view(s) with different underlying storage types.
2305 ///
2306 /// This may have unexpected effects, and you cannot assume that
2307 /// `before[idx] == after[idx]`! Consult the [tables in the manual][layout]
2308 /// for information about memory layouts.
2309 ///
2310 /// ## Original
2311 ///
2312 /// [`slice::align_to_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.align_to_mut)
2313 ///
2314 /// ## Notes
2315 ///
2316 /// Unlike the standard library documentation, this explicitly guarantees
2317 /// that the middle bit-slice will have maximal size. You may rely on this
2318 /// property.
2319 ///
2320 /// ## Safety
2321 ///
2322 /// You may not use this to cast away alias protections. Rust does not have
2323 /// support for higher-kinded types, so this cannot express the relation
2324 /// `Outer<T> -> Outer<U> where Outer: BitStoreContainer`, but memory safety
2325 /// does require that you respect this rule. Reälign integers to integers,
2326 /// `Cell`s to `Cell`s, and atomics to atomics, but do not cross these
2327 /// boundaries.
2328 ///
2329 /// ## Examples
2330 ///
2331 /// ```rust
2332 /// use bitvec::prelude::*;
2333 ///
2334 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2335 /// let bits = bytes.view_bits_mut::<Lsb0>();
2336 /// let (pfx, mid, sfx) = unsafe {
2337 /// bits.align_to_mut::<u16>()
2338 /// };
2339 /// assert!(pfx.len() <= 8);
2340 /// assert_eq!(mid.len(), 48);
2341 /// assert!(sfx.len() <= 8);
2342 /// ```
2343 ///
2344 /// [layout]: https://bitvecto-rs.github.io/bitvec/memory-layout.html
2345 #[inline]
2346 pub unsafe fn align_to_mut<U>(
2347 &mut self,
2348 ) -> (&mut Self, &mut BitSlice<U, O>, &mut Self)
2349 where U: BitStore {
2350 let (l, c, r) = self.as_mut_bitspan().align_to::<U>();
2351 (
2352 l.into_bitslice_mut(),
2353 c.into_bitslice_mut(),
2354 r.into_bitslice_mut(),
2355 )
2356 }
2357}
2358
2359#[cfg(feature = "alloc")]
2360impl<T, O> BitSlice<T, O>
2361where
2362 T: BitStore,
2363 O: BitOrder,
2364{
2365 #[inline]
2366 #[deprecated = "use `.to_bitvec()` instead"]
2367 #[allow(missing_docs, clippy::missing_docs_in_private_items)]
2368 pub fn to_vec(&self) -> BitVec<T::Unalias, O> {
2369 self.to_bitvec()
2370 }
2371
2372 /// Creates a bit-vector by repeating a bit-slice `n` times.
2373 ///
2374 /// ## Original
2375 ///
2376 /// [`slice::repeat`](https://doc.rust-lang.org/std/primitive.slice.html#method.repeat)
2377 ///
2378 /// ## Panics
2379 ///
2380 /// This method panics if `self.len() * n` exceeds the `BitVec` capacity.
2381 ///
2382 /// ## Examples
2383 ///
2384 /// ```rust
2385 /// use bitvec::prelude::*;
2386 ///
2387 /// assert_eq!(bits![0, 1].repeat(3), bitvec![0, 1, 0, 1, 0, 1]);
2388 /// ```
2389 ///
2390 /// This panics by exceeding bit-vector maximum capacity:
2391 ///
2392 /// ```rust,should_panic
2393 /// use bitvec::prelude::*;
2394 ///
2395 /// bits![0, 1].repeat(BitSlice::<usize, Lsb0>::MAX_BITS);
2396 /// ```
2397 #[inline]
2398 pub fn repeat(&self, n: usize) -> BitVec<T::Unalias, O> {
2399 let len = self.len();
2400 let total = len.checked_mul(n).expect("capacity overflow");
2401
2402 let mut out = BitVec::repeat(false, total);
2403
2404 let iter = unsafe { out.chunks_exact_mut(len).remove_alias() };
2405 for chunk in iter {
2406 chunk.clone_from_bitslice(self);
2407 }
2408
2409 out
2410 }
2411
2412 /* As of 1.56, the `concat` and `join` methods use still-unstable traits
2413 * to govern the collection of multiple subslices into one vector. These
2414 * are possible to copy over and redefine locally, but unless a user asks
2415 * for it, doing so is considered a low priority.
2416 */
2417}
2418
2419#[inline]
2420#[allow(missing_docs, clippy::missing_docs_in_private_items)]
2421#[deprecated = "use `BitSlice::from_element()` instead"]
2422pub fn from_ref<T, O>(elem: &T) -> &BitSlice<T, O>
2423where
2424 T: BitStore,
2425 O: BitOrder,
2426{
2427 BitSlice::from_element(elem)
2428}
2429
2430#[inline]
2431#[allow(missing_docs, clippy::missing_docs_in_private_items)]
2432#[deprecated = "use `BitSlice::from_element_mut()` instead"]
2433pub fn from_mut<T, O>(elem: &mut T) -> &mut BitSlice<T, O>
2434where
2435 T: BitStore,
2436 O: BitOrder,
2437{
2438 BitSlice::from_element_mut(elem)
2439}
2440
2441#[inline]
2442#[doc = include_str!("../../doc/slice/from_raw_parts.md")]
2443pub unsafe fn from_raw_parts<'a, T, O>(
2444 data: BitPtr<Const, T, O>,
2445 len: usize,
2446) -> Result<&'a BitSlice<T, O>, BitSpanError<T>>
2447where
2448 O: BitOrder,
2449 T: 'a + BitStore,
2450{
2451 data.span(len).map(|bp| bp.into_bitslice_ref())
2452}
2453
2454#[inline]
2455#[doc = include_str!("../../doc/slice/from_raw_parts_mut.md")]
2456pub unsafe fn from_raw_parts_mut<'a, T, O>(
2457 data: BitPtr<Mut, T, O>,
2458 len: usize,
2459) -> Result<&'a mut BitSlice<T, O>, BitSpanError<T>>
2460where
2461 O: BitOrder,
2462 T: 'a + BitStore,
2463{
2464 data.span(len).map(|bp| bp.into_bitslice_mut())
2465}
2466
2467#[doc = include_str!("../../doc/slice/BitSliceIndex.md")]
2468pub trait BitSliceIndex<'a, T, O>
2469where
2470 T: BitStore,
2471 O: BitOrder,
2472{
2473 /// The output type of immutable access.
2474 type Immut;
2475
2476 /// The output type of mutable access.
2477 type Mut;
2478
2479 /// Immutably indexes into a bit-slice, returning `None` if `self` is out of
2480 /// bounds.
2481 ///
2482 /// ## Original
2483 ///
2484 /// [`SliceIndex::get`](core::slice::SliceIndex::get)
2485 fn get(self, bits: &'a BitSlice<T, O>) -> Option<Self::Immut>;
2486
2487 /// Mutably indexes into a bit-slice, returning `None` if `self` is out of
2488 /// bounds.
2489 ///
2490 /// ## Original
2491 ///
2492 /// [`SliceIndex::get_mut`](core::slice::SliceIndex::get_mut)
2493 fn get_mut(self, bits: &'a mut BitSlice<T, O>) -> Option<Self::Mut>;
2494
2495 /// Immutably indexes into a bit-slice without doing any bounds checking.
2496 ///
2497 /// ## Original
2498 ///
2499 /// [`SliceIndex::get_unchecked`](core::slice::SliceIndex::get_unchecked)
2500 ///
2501 /// ## Safety
2502 ///
2503 /// If `self` is not in bounds, then memory accesses through it are illegal
2504 /// and the program becomes undefined. You must ensure that `self` is
2505 /// appropriately within `0 .. bits.len()` at the call site.
2506 unsafe fn get_unchecked(self, bits: &'a BitSlice<T, O>) -> Self::Immut;
2507
2508 /// Mutably indexes into a bit-slice without doing any bounds checking.
2509 ///
2510 /// ## Original
2511 ///
2512 /// [`SliceIndex::get_unchecked_mut`][0]
2513 ///
2514 /// ## Safety
2515 ///
2516 /// If `self` is not in bounds, then memory accesses through it bare illegal
2517 /// and the program becomes undefined. You must ensure that `self` is
2518 /// appropriately within `0 .. bits.len()` at the call site.
2519 ///
2520 /// [0]: core::slice::SliceIndex::get_unchecked_mut
2521 unsafe fn get_unchecked_mut(self, bits: &'a mut BitSlice<T, O>)
2522 -> Self::Mut;
2523
2524 /// Immutably indexes into a bit-slice, panicking if `self` is out of
2525 /// bounds.
2526 ///
2527 /// ## Original
2528 ///
2529 /// [`SliceIndex::index`](core::slice::SliceIndex::index)
2530 ///
2531 /// ## Panics
2532 ///
2533 /// Implementations are required to panic if `self` exceeds `bits.len()` in
2534 /// any way.
2535 fn index(self, bits: &'a BitSlice<T, O>) -> Self::Immut;
2536
2537 /// Mutably indexes into a bit-slice, panicking if `self` is out of bounds.
2538 ///
2539 /// ## Original
2540 ///
2541 /// [`SliceIndex::index_mut`](core::slice::SliceIndex::index_mut)
2542 ///
2543 /// ## Panics
2544 ///
2545 /// Implementations are required to panic if `self` exceeds `bits.len()` in
2546 /// any way.
2547 fn index_mut(self, bits: &'a mut BitSlice<T, O>) -> Self::Mut;
2548}
2549
2550impl<'a, T, O> BitSliceIndex<'a, T, O> for usize
2551where
2552 T: BitStore,
2553 O: BitOrder,
2554{
2555 type Immut = BitRef<'a, Const, T, O>;
2556 type Mut = BitRef<'a, Mut, T, O>;
2557
2558 #[inline]
2559 fn get(self, bits: &'a BitSlice<T, O>) -> Option<Self::Immut> {
2560 if self < bits.len() {
2561 Some(unsafe { self.get_unchecked(bits) })
2562 }
2563 else {
2564 None
2565 }
2566 }
2567
2568 #[inline]
2569 fn get_mut(self, bits: &'a mut BitSlice<T, O>) -> Option<Self::Mut> {
2570 if self < bits.len() {
2571 Some(unsafe { self.get_unchecked_mut(bits) })
2572 }
2573 else {
2574 None
2575 }
2576 }
2577
2578 #[inline]
2579 unsafe fn get_unchecked(self, bits: &'a BitSlice<T, O>) -> Self::Immut {
2580 bits.as_bitptr().add(self).as_ref().unwrap()
2581 }
2582
2583 #[inline]
2584 unsafe fn get_unchecked_mut(
2585 self,
2586 bits: &'a mut BitSlice<T, O>,
2587 ) -> Self::Mut {
2588 bits.as_mut_bitptr().add(self).as_mut().unwrap()
2589 }
2590
2591 #[inline]
2592 fn index(self, bits: &'a BitSlice<T, O>) -> Self::Immut {
2593 self.get(bits).unwrap_or_else(|| {
2594 panic!("index {} out of bounds: {}", self, bits.len())
2595 })
2596 }
2597
2598 #[inline]
2599 fn index_mut(self, bits: &'a mut BitSlice<T, O>) -> Self::Mut {
2600 let len = bits.len();
2601 self.get_mut(bits)
2602 .unwrap_or_else(|| panic!("index {} out of bounds: {}", self, len))
2603 }
2604}
2605
2606/// Implements indexing on bit-slices by various range types.
2607macro_rules! range_impl {
2608 ($r:ty { check $check:expr; select $select:expr; }) => {
2609 #[allow(clippy::redundant_closure_call)]
2610 impl<'a, T, O> BitSliceIndex<'a, T, O> for $r
2611 where
2612 O: BitOrder,
2613 T: BitStore,
2614 {
2615 type Immut = &'a BitSlice<T, O>;
2616 type Mut = &'a mut BitSlice<T, O>;
2617
2618 #[inline]
2619 #[allow(
2620 clippy::blocks_in_if_conditions,
2621 clippy::redundant_closure_call
2622 )]
2623 fn get(self, bits: Self::Immut) -> Option<Self::Immut> {
2624 if ($check)(self.clone(), bits.as_bitspan()) {
2625 Some(unsafe { self.get_unchecked(bits) })
2626 }
2627 else {
2628 None
2629 }
2630 }
2631
2632 #[inline]
2633 #[allow(
2634 clippy::blocks_in_if_conditions,
2635 clippy::redundant_closure_call
2636 )]
2637 fn get_mut(self, bits: Self::Mut) -> Option<Self::Mut> {
2638 if ($check)(self.clone(), bits.as_bitspan()) {
2639 Some(unsafe { self.get_unchecked_mut(bits) })
2640 }
2641 else {
2642 None
2643 }
2644 }
2645
2646 #[inline]
2647 #[allow(clippy::redundant_closure_call)]
2648 unsafe fn get_unchecked(self, bits: Self::Immut) -> Self::Immut {
2649 ($select)(self, bits.as_bitspan()).into_bitslice_ref()
2650 }
2651
2652 #[inline]
2653 #[allow(clippy::redundant_closure_call)]
2654 unsafe fn get_unchecked_mut(self, bits: Self::Mut) -> Self::Mut {
2655 ($select)(self, bits.as_mut_bitspan()).into_bitslice_mut()
2656 }
2657
2658 #[inline]
2659 #[track_caller]
2660 fn index(self, bits: Self::Immut) -> Self::Immut {
2661 let r = self.clone();
2662 let l = bits.len();
2663 self.get(bits).unwrap_or_else(|| {
2664 panic!("range {:?} out of bounds: {}", r, l)
2665 })
2666 }
2667
2668 #[inline]
2669 #[track_caller]
2670 fn index_mut(self, bits: Self::Mut) -> Self::Mut {
2671 let r = self.clone();
2672 let l = bits.len();
2673 self.get_mut(bits).unwrap_or_else(|| {
2674 panic!("range {:?} out of bounds: {}", r, l)
2675 })
2676 }
2677 }
2678 };
2679}
2680
2681range_impl!(Range<usize> {
2682 check |Range { start, end }, span: BitSpan<_, _, _>| {
2683 let len = span.len();
2684 start <= len && end <= len && start <= end
2685 };
2686
2687 select |Range { start, end }, span: BitSpan<_, _, _>| {
2688 span.to_bitptr().add(start).span_unchecked(end - start)
2689 };
2690});
2691
2692range_impl!(RangeFrom<usize> {
2693 check |RangeFrom { start }, span: BitSpan<_, _, _>| {
2694 start <= span.len()
2695 };
2696
2697 select |RangeFrom { start }, span: BitSpan<_, _, _>| {
2698 span.to_bitptr().add(start).span_unchecked(span.len() - start)
2699 };
2700});
2701
2702range_impl!(RangeTo<usize> {
2703 check |RangeTo { end }, span: BitSpan<_, _, _>| {
2704 end <= span.len()
2705 };
2706
2707 select |RangeTo { end }, mut span: BitSpan<_, _, _>| {
2708 span.set_len(end);
2709 span
2710 };
2711});
2712
2713range_impl!(RangeInclusive<usize> {
2714 check |range: Self, span: BitSpan<_, _, _>| {
2715 let len = span.len();
2716 let start = *range.start();
2717 let end = *range.end();
2718
2719 start < len && end < len && start <= end
2720 };
2721
2722 select |range: Self, span: BitSpan<_, _, _>| {
2723 let start = *range.start();
2724 let end = *range.end();
2725 span.to_bitptr().add(start).span_unchecked(end + 1 - start)
2726 };
2727});
2728
2729range_impl!(RangeToInclusive<usize> {
2730 check |RangeToInclusive { end }, span: BitSpan<_, _, _>| {
2731 end < span.len()
2732 };
2733
2734 select |RangeToInclusive { end }, mut span: BitSpan<_, _, _>| {
2735 span.set_len(end + 1);
2736 span
2737 };
2738});
2739
2740#[cfg(not(tarpaulin_include))]
2741impl<'a, T, O> BitSliceIndex<'a, T, O> for RangeFull
2742where
2743 T: BitStore,
2744 O: BitOrder,
2745{
2746 type Immut = &'a BitSlice<T, O>;
2747 type Mut = &'a mut BitSlice<T, O>;
2748
2749 #[inline]
2750 fn get(self, bits: Self::Immut) -> Option<Self::Immut> {
2751 Some(bits)
2752 }
2753
2754 #[inline]
2755 fn get_mut(self, bits: Self::Mut) -> Option<Self::Mut> {
2756 Some(bits)
2757 }
2758
2759 #[inline]
2760 unsafe fn get_unchecked(self, bits: Self::Immut) -> Self::Immut {
2761 bits
2762 }
2763
2764 #[inline]
2765 unsafe fn get_unchecked_mut(self, bits: Self::Mut) -> Self::Mut {
2766 bits
2767 }
2768
2769 #[inline]
2770 fn index(self, bits: Self::Immut) -> Self::Immut {
2771 bits
2772 }
2773
2774 #[inline]
2775 fn index_mut(self, bits: Self::Mut) -> Self::Mut {
2776 bits
2777 }
2778}