/
api.rs
2479 lines (2323 loc) · 70.6 KB
/
api.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! Reïmplementation of the `[T]` API.
This module tracks the [`slice`] primitive and [`core::slice`] module in the
version of Rust specified in the `rust-toolchain` file. It is required to
provide an exact or equivalent API surface matching the `Box<[T]>` type, to the
extent that it is possible in the language. Where differences occur, they must
be documented in a section called `API Differences`.
[`core::slice`]: https://doc.rust-lang.org/core/slice
[`slice`]: https://doc.rust-lang.org/std/primitive.slice.html
!*/
use crate::{
access::BitAccess,
indices::BitIdx,
order::BitOrder,
pointer::BitPtr,
slice::{
BitSlice,
iter::{
Chunks,
ChunksExact,
ChunksExactMut,
ChunksMut,
GenericSplitN,
Iter,
IterMut,
RChunks,
RChunksExact,
RChunksExactMut,
RChunksMut,
RSplit,
RSplitMut,
RSplitN,
RSplitNMut,
Split,
SplitMut,
SplitN,
SplitNMut,
Windows,
},
proxy::BitMut,
},
store::BitStore,
};
use core::{
cmp,
ops::{
Range,
RangeFrom,
RangeFull,
RangeInclusive,
RangeTo,
RangeToInclusive,
},
slice,
};
#[cfg(feature = "alloc")]
use crate::vec::BitVec;
/** Forms a `BitSlice` from a pointer, starting position, and length.
The `head` argument is the starting *index*, not the starting *bit position*.
The `bits` argumnent is the number of **bits**, not the number of elements `T`.
This function is the semantic equivalent to `[T]::from_raw_parts`, in contrast
to [`from_raw_parts`] which is the API equivalent.
# Safety
This function is unsafe as there is no guarantee that the given pointer is valid
for the elements required to hold `head + bits` bits, nor whether the lifetime
inferred is a suitable lifetime for the returned slice.
`data` must be non-null and aligned, even for zero-length slices. This is due to
requirements in the `bitvec` data structure operations. You can obtain a pointer
that is usable as `data` for zero-length slices from [`NonNull::dangling()`].
The total size of the bit slice must be no larger than `BitPtr::<T>::MAX_BITS`
**bits** in memory. See the safety documentation of `BitPtr` (if available).
# Caveat
The lifetime for the returned slice is inferred from its usage. To prevent
accidental misuse, it’s suggested to tie the lifetime to whichever source
lifetime is safe in the context, such as by providing a helper function taking
the lifetime of a host value for the slice, or by explicit annotation.
# Examples
```rust
use bitvec::{
indices::BitIdx,
order::Local,
slice,
slice::BitSlice,
};
// manifest a slice for a single element
let x = 42u8;
let ptr = &x as *const u8;
let bits: &BitSlice<Local, u8> = unsafe { slice::bits_from_raw_parts(
ptr,
BitIdx::new(2).unwrap(),
5
) };
assert_eq!(bits.len(), 5);
```
[`from_raw_parts`]: #fn.from_raw_parts
**/
pub unsafe fn bits_from_raw_parts<'a, O, T>(
data: *const T,
head: BitIdx<T>,
bits: usize,
) -> &'a BitSlice<O, T>
where O: BitOrder, T: 'a + BitStore {
BitPtr::new(data, head, bits).into_bitslice()
}
/** Performs the same functionality as [`bits_from_raw_parts`], except that a
mutable slice is returned.
This function is unsafe for the same reasons as [`bits_from_raw_parts`], as well
as not being able to provide a non-aliasing guarantee of the returned mutable
slice. `data` must be non-null and aligned even for zero-length slices as with
[`bits_from_raw_parts`]. The total size of the slice must be no larger than
`BitPtr::<T>::MAX_ELTS` **elements** `T` in memory.
See the documentation of [`bits_from_raw_parts`] for more details.
# Safety
Beyond the ordinary Rust requirements for aliasing, this function *also*
requires that the described region, when combined with the `O` [`BitOrder`]
type parameter, not cause aliasing with another `BitSlice` whose head and `O`
arguments cause aliasing in the underlying memory positions.
[`BitOrder`]: ../order/trait.BitOrder.html
[`bits_from_raw_parts`]: #fn.bits_from_raw_parts
**/
pub unsafe fn bits_from_raw_parts_mut<'a, O, T>(
data: *mut T,
head: BitIdx<T>,
bits: usize,
) -> &'a mut BitSlice<O, T>
where O: BitOrder, T: 'a + BitStore {
BitPtr::new(data, head, bits).into_bitslice_mut()
}
/** Converts a reference to `T` into a `BitSlice` of that element (without
copying).
# Original
[`core::slice::from_mut`](https://doc.rust-lang.org/core/slice/fn.from_mut.html)
**/
pub fn from_mut<O, T>(elt: &mut T) -> &mut BitSlice<O, T>
where O: BitOrder, T: BitStore {
BitSlice::from_element_mut(elt)
}
/** Forms a bit slice from a pointer and a length.
The `len` argument is the number of **elements**, not the number of bits.
# Safety
This function is unsafe as there is no guarantee that the given pointer is valid
for `len` elements, nor whether the lifetime inferred is a suitable lifetime for
the returned slice.
`data` must be non-null and aligned, even for zero-length slices. This is due to
requirements in the `bitvec` data structure operations. You can obtain a pointer
that is usable as `data` for zero-length slices from [`NonNull::dangling()`].
The total size of the bit slice must be no larger than `BitPtr::<T>::MAX_BITS`
**bits** in memory. See the safety documentation of `BitPtr` (if available).
# Caveat
The lifetime for the returned slice is inferred from its usage. To prevent
accidental misuse, it’s suggested to tie the lifetime to whichever source
lifetime is safe in the context, such as by providing a helper function taking
the lifetime of a host value for the slice, or by explicit annotation.
# Original
[`core::slice::from_raw_parts`](https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html)
# Examples
```rust
# use bitvec::prelude::*;
use bitvec::slice as bitslice;
// manifest a slice for a single element
let x = 42u8; // 0b0010_1010
let ptr = &x as *const _;
let bitslice = unsafe { bitslice::from_raw_parts::<Msb0, _>(ptr, 1) };
assert!(bitslice[2]);
```
**/
pub unsafe fn from_raw_parts<'a, O, T>(
data: *const T,
len: usize,
) -> &'a BitSlice<O, T>
where O: BitOrder, T: 'a + BitStore {
BitSlice::from_slice(slice::from_raw_parts(data, len))
}
/** Performs the same functionality as [`from_raw_parts`], except that a mutable
slice is returned.
This function is unsafe for the same reason as [`from_raw_parts`], as well as
not being able to provide a non-aliasing guarantee of the returned mutable
slice. `data` must be non-null and aligned even for zero-length slices as with
[`from_raw_parts`]. The total size of the slice must be no larger than
`BitPtr::<T>::MAX_ELTS` **elements** in memory.
See the documentation of [`from_raw_parts`] for more details.
# Safety
See `from_raw_parts`.
# Original
[`core::slice::from_raw_parts_mut`](https://doc.rust-lang.org/core/slice/fn.from_raw_parts_mut.html)
[`from_raw_parts`]: #fn.from_raw_parts
**/
pub unsafe fn from_raw_parts_mut<'a, O, T>(
data: *mut T,
len: usize,
) -> &'a mut BitSlice<O, T>
where O: BitOrder, T: 'a + BitStore {
BitSlice::from_slice_mut(slice::from_raw_parts_mut(data, len))
}
/** Converts a reference to `T` into a bit slice one element long (without
copying).
# Original
[`core::slice::from_ref`](https://doc.rust-lang.org/core/slice/fn.from_ref.html)
**/
pub fn from_ref<O, T>(elt: &T) -> &BitSlice<O, T>
where O: BitOrder, T: BitStore {
BitSlice::from_element(elt)
}
/// Reimplementation of the `[T]` inherent-method API.
impl<O, T> BitSlice<O, T>
where O: BitOrder, T: BitStore {
/// Returns the number of bits in the slice.
///
/// # Original
///
/// [`slice::len`](https://doc.rust-lang.org/std/primitive.slice.html#method.len)
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let bits = 0u8.bits::<Local>();
/// assert_eq!(bits.len(), 8);
/// ```
pub fn len(&self) -> usize {
self.bitptr().len()
}
/// Returns `true` if the slice has a length of 0.
///
/// # Original
///
/// [`slice::is_empty`](https://doc.rust-lang.org/std/primitive.slice.html#method.is_empty)
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let bits = 0u8.bits::<Local>();
/// assert!(!bits.is_empty());
///
/// assert!(BitSlice::<Local, usize>::empty().is_empty())
/// ```
pub fn is_empty(&self) -> bool {
self.bitptr().len() == 0
}
/// Returns the first bit of the slice, or `None` if it is empty.
///
/// # Original
///
/// [`slice::first`](https://doc.rust-lang.org/std/primitive.slice.html#method.first)
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let bits = 1u8.bits::<Lsb0>();
/// assert_eq!(bits.first(), Some(&true));
///
/// assert!(BitSlice::<Local, usize>::empty().first().is_none());
/// ```
#[inline]
pub fn first(&self) -> Option<&bool> {
0.get(self)
}
/// Returns a mutable pointer to the first bit of the slice, or `None` if it
/// is empty.
///
/// # Original
///
/// [`slice::first_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.first_mut)
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let mut data = 0u8;
/// let bits = data.bits_mut::<Lsb0>();
/// if let Some(mut first) = bits.first_mut() {
/// *first = true;
/// }
/// assert_eq!(data, 1u8);
/// ```
#[inline]
pub fn first_mut(&mut self) -> Option<BitMut<O, T>> {
0.get_mut(self)
}
/// Returns the first and all the rest of the bits of the slice, or `None`
/// if it is empty.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let bits = 1u8.bits::<Lsb0>();
/// if let Some((first, rest)) = bits.split_first() {
/// assert_eq!(first, &true);
/// assert_eq!(rest, &bits[1 ..]);
/// }
/// ```
#[inline]
pub fn split_first(&self) -> Option<(&bool, &Self)> {
if self.is_empty() {
None
}
else {
let (head, rest) = self.split_at(1);
unsafe { Some((0.get_unchecked(head), rest)) }
}
}
/// Returns the first and all the rest of the bits of the slice, or `None`
/// if it is empty.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let mut data = 0u8;
/// let bits = data.bits_mut::<Lsb0>();
/// if let Some((mut first, rest)) = bits.split_first_mut() {
/// *first = true;
/// *rest.at(0) = true;
/// *rest.at(1) = true;
/// }
/// assert_eq!(data, 7);
/// ```
#[inline]
pub fn split_first_mut(&mut self) -> Option<(BitMut<O, T>, &mut Self)> {
if self.is_empty() {
None
}
else {
let (head, rest) = self.split_at_mut(1);
Some((unsafe { 0.get_unchecked_mut(head) }, rest))
}
}
/// Returns the last and all the rest of the bits of the slice, or `None` if
/// it is empty.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let bits = 1u8.bits::<Msb0>();
/// if let Some((last, rest)) = bits.split_last() {
/// assert_eq!(last, &true);
/// assert_eq!(rest, &bits[.. 7]);
/// }
/// ```
#[inline]
pub fn split_last(&self) -> Option<(&bool, &Self)> {
match self.len() {
0 => None,
len => {
let (rest, tail) = self.split_at(len - 1);
Some((unsafe { 0.get_unchecked(tail) }, rest))
},
}
}
/// Returns the last and all the rest of the bits of the slice, or `None` if
/// it is empty.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let mut data = 0u8;
/// let bits = data.bits_mut::<Msb0>();
/// if let Some((mut last, rest)) = bits.split_last_mut() {
/// *last = true;
/// *rest.at(0) = true;
/// *rest.at(1) = true;
/// }
/// assert_eq!(data, 128 | 64 | 1);
/// ```
#[inline]
pub fn split_last_mut(&mut self) -> Option<(BitMut<O, T>, &mut Self)> {
match self.len() {
0 => None,
len => {
let (rest, tail) = self.split_at_mut(len - 1);
Some((unsafe { 0.get_unchecked_mut(tail) }, rest))
},
}
}
/// Returns the last bit of the slice, or `None` if it is empty.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let bits = 1u8.bits::<Msb0>();
/// assert_eq!(Some(&true), bits.last());
/// assert!(BitSlice::<Local, usize>::empty().last().is_none());
/// ```
#[inline]
pub fn last(&self) -> Option<&bool> {
match self.len() {
0 => None,
len => Some(unsafe { (len - 1).get_unchecked(self) }),
}
}
/// Returns a mutable pointer to the last bit in the slice.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let mut data = 0u8;
/// let bits = data.bits_mut::<Msb0>();
/// if let Some(mut last) = bits.last_mut() {
/// *last = true;
/// }
/// assert!(bits[7]);
#[inline]
pub fn last_mut(&mut self) -> Option<BitMut<O, T>> {
match self.len() {
0 => None,
len => Some(unsafe { (len - 1).get_unchecked_mut(self) }),
}
}
/// Returns a reference to a bit or subslice depending on the type of
/// `index`.
///
/// - If given a position, returns a reference to the bit at that position
/// or `None` if out of bounds.
/// - If given a range, returns the subslice corresponding to that range, or
/// `None` if out of bounds.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let data = 1u8;
/// let bits = data.bits::<Lsb0>();
/// assert_eq!(Some(&true), bits.get(0));
/// assert!(bits.get(8).is_none());
/// assert!(bits.get(1 ..).expect("in bounds").not_any());
/// assert!(bits.get(.. 12).is_none());
/// ```
#[inline]
pub fn get<'a, I>(&'a self, index: I) -> Option<I::Immut>
where I: BitSliceIndex<'a, O, T> {
index.get(self)
}
/// Returns a mutable reference to a bit or subslice depending on the type
/// of `index` (see [`get`]) or `None` if the index is out of bounds.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let mut data = 0u8;
/// let bits = data.bits_mut::<Lsb0>();
/// if let Some(mut bit) = bits.get_mut(1) {
/// *bit = true;
/// }
/// if let Some(bits) = bits.get_mut(5 .. 7) {
/// bits.set_all(true);
/// }
/// assert_eq!(data, 64 | 32 | 2);
/// ```
///
/// [`get`]: #method.get
#[inline]
pub fn get_mut<'a, I>(&'a mut self, index: I) -> Option<I::Mut>
where I: BitSliceIndex<'a, O, T> {
index.get_mut(self)
}
/// Returns a reference to a bit or subslice, without doing bounds checking.
///
/// This is generally not recommended; use with caution! For a safe
/// alternative, see [`get`].
///
/// # Safety
///
/// As this function does not perform boundary checking, the caller must
/// ensure that `self` is an index within the boundaries of `slice` before
/// calling in order to avoid boundary escapes and ensuing safety
/// violations.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let data = 4u8;
/// let bits = data.bits::<Lsb0>();
/// unsafe {
/// assert!(bits.get_unchecked(2));
/// assert!(!bits.get_unchecked(1));
/// }
/// ```
///
/// [`get`]: #method.get
#[inline]
pub unsafe fn get_unchecked<'a, I>(&'a self, index: I) -> I::Immut
where I: BitSliceIndex<'a, O, T> {
index.get_unchecked(self)
}
/// Returns a mutable reference to a bit or subslice, without doing bounds
/// checking.
///
/// This is generally not recommended; use with caution! For a safe
/// alternative, see [`get_mut`].
///
/// # Safety
///
/// As this function does not perform boundary checking, the caller must
/// ensure that `self` is an index within the boundaries of `slice` before
/// calling in order to avoid boundary escapes and ensuing safety
/// violations.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let mut data = 0u8;
/// let bits = data.bits_mut::<Msb0>();
/// unsafe {
/// let mut bit = bits.get_unchecked_mut(0);
/// *bit = true;
/// drop(bit); // release the borrow immediately
/// let bits = bits.get_unchecked_mut(6 ..);
/// bits.set_all(true);
/// }
/// assert_eq!(data, 1 | 2 | 128);
/// ```
///
/// [`get_mut`]: #method.get_mut
#[inline]
pub unsafe fn get_unchecked_mut<'a, I>(&'a mut self, index: I) -> I::Mut
where I: BitSliceIndex<'a, O, T> {
index.get_unchecked_mut(self)
}
/// Returns a raw pointer to the slice’s buffer.
///
/// The caller must ensure that the slice outlives the pointer this function
/// returns, or else it will end up pointing to garbage.
///
/// The caller must also ensure that the memory the pointer
/// (non-transitively) points to is never written to (except inside an
/// `UnsafeCell`) using this pointer or any pointer derived from it. If you
/// need to mutate the contents of the buffer, use [`as_mut_ptr`].
///
/// Modifying the container referenced by this slice may cause its buffer to
/// be reallocated, which would also make any pointers to it invalid.
///
/// # Notes
///
/// This pointer is always to the first `T` element in the backing storage,
/// even if that element is only partially used by the `self` slice.
/// Multiple separate `BitSlice` handles may produce the same pointer with
/// this method.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let data = [0u8; 2];
/// let bits = data.bits::<Msb0>();
/// let (head, rest) = bits.split_at(4);
/// assert_eq!(head.as_ptr(), rest.as_ptr());
/// ```
///
/// [`as_mut_ptr`]: #method.as_mut_ptr
// FIXME(myrrlyn, 2019-10-22): Blocked on issue #57563.
#[inline]
pub /* const */ fn as_ptr(&self) -> *const T {
self.bitptr().pointer().r()
}
/// Returns an unsafe mutable pointer to the slice’s buffer.
///
/// The caller must ensure thath the slice outlives the pointer this
/// function returns, or else it will end up pointing to garbage.
///
/// Modifying the container referenced by this slice may couse its buffer to
/// be reallocated, which would also make any pointers to it invalid.
///
/// # Notes
///
/// This pointer is always to the first `T` element in the backing storage,
/// even if that element is only partially used by the `self` slice.
/// Multiple separate `BitSlice` handles may produce the same pointer with
/// this method.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let mut data = [0u8; 2];
/// let bits = data.bits_mut::<Msb0>();
/// let (head, rest) = bits.split_at_mut(4);
/// assert_eq!(head.as_mut_ptr(), rest.as_mut_ptr());
/// unsafe { *head.as_mut_ptr() = 2; }
/// assert!(rest[2]);
/// ```
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut T {
self.bitptr().pointer().w()
}
/// Swaps two bits in the slice.
///
/// # Arguments
///
/// - `a`: The index of the first bit
/// - `b`: The index of the second bit
///
/// # Panics
///
/// Panics if `a` or `b` are out of bounds.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let mut data = 2u8;
/// let bits = data.bits_mut::<Lsb0>();
/// bits.swap(0, 1);
/// assert_eq!(data, 1);
/// ```
pub fn swap(&mut self, a: usize, b: usize) {
let len = self.len();
assert!(a < len, "Index {} out of bounds: {}", a, len);
assert!(b < len, "Index {} out of bounds: {}", b, len);
unsafe { self.swap_unchecked(a, b); }
}
/// Reverses the order of bits in the slice, in place.
///
/// # Examples
///
/// ```rust
/// use bitvec::prelude::*;
/// let mut data = 0b1_1001100u8;
/// let bits = data.bits_mut::<Msb0>();
/// bits[1 ..].reverse();
/// assert_eq!(data, 0b1_0011001);
/// ```
pub fn reverse(&mut self) {
/* This is better implemented as a recursive algorithm, but Rust doesn’t
yet flatten recursive tail calls into a loop, so it is done manually
here.
*/
let mut cur: &mut Self = self;
loop {
let len = cur.len();
// Terminate when only one or zero bits remain to switch.
if len < 2 {
return;
}
let back = len - 1;
unsafe {
cur.swap_unchecked(0, back);
cur = cur.get_unchecked_mut(1 .. back);
}
}
}
/// Returns an iterator over the slice.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let data = 3u8;
/// let bits = data.bits::<Lsb0>();
/// let mut iter = bits[.. 4].iter();
/// assert_eq!(iter.next(), Some(&true));
/// assert_eq!(iter.next(), Some(&true));
/// assert_eq!(iter.next(), Some(&false));
/// assert_eq!(iter.next(), Some(&false));
/// assert!(iter.next().is_none());
/// ```
#[inline]
pub fn iter(&self) -> Iter<O, T> {
self.into_iter()
}
/// Returns an iterator that allows modifying each bit.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let mut data = 0u8;
/// let bits = &mut data.bits_mut::<Lsb0>()[.. 2];
/// for mut bit in bits.iter_mut() {
/// *bit = true;
/// }
/// assert_eq!(data, 3);
/// ```
#[inline]
pub fn iter_mut(&mut self) -> IterMut<O, T> {
self.into_iter()
}
/// Returns an iterator over all contiguous windows of width `width`.
///
/// The windows overlap. If the slice is shorter than `width`, the iterator
/// returns no values.
///
/// # Panics
///
/// Panics if `width` is 0.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let data = 0b100_010_01u8;
/// let bits = data.bits::<Msb0>();
/// let mut iter = bits[.. 5].windows(3);
/// assert_eq!(iter.next().unwrap(), &bits[0 .. 3]);
/// assert_eq!(iter.next().unwrap(), &bits[1 .. 4]);
/// assert_eq!(iter.next().unwrap(), &bits[2 .. 5]);
/// assert!(iter.next().is_none());
/// ```
///
/// If the slice is shorter than `width`:
///
/// ```rust
/// # use bitvec::prelude::*;
/// let data = 0u8;
/// let bits = data.bits::<Local>();
/// let mut iter = bits[.. 3].windows(4);
/// assert!(iter.next().is_none());
pub fn windows(&self, width: usize) -> Windows<O, T> {
assert_ne!(width, 0, "Window width cannot be zero");
super::Windows {
inner: self,
width,
}
}
/// Returns an iterator over `chunk_size` bits of the slice at a time,
/// starting at the beginning of the slice.
///
/// The chunks are slices and do not overlap. If `chunk_size` does not
/// divide the length of the slice, then the last chunk will not have length
/// `chunk_size`.
///
/// See [`chunks_exact`] for a variant of this iterator that returns chunks
/// of always exactly `chunk_size` elements, and [`rchunks`] for the same
/// iterator but starting at the end of the slice.
///
/// # Panics
///
/// Panics if `chunk_size` is 0.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let data = 0b001_010_10u8;
/// let bits = data.bits::<Msb0>();
/// let mut iter = bits.chunks(3);
/// assert_eq!(iter.next().unwrap(), &bits[0 .. 3]);
/// assert_eq!(iter.next().unwrap(), &bits[3 .. 6]);
/// assert_eq!(iter.next().unwrap(), &bits[6 .. 8]);
/// assert!(iter.next().is_none());
/// ```
///
/// [`chunks_exact`]: #method.chunks_exact
/// [`rchunks`]: #method.rchunks
pub fn chunks(&self, chunk_size: usize) -> Chunks<O, T> {
assert_ne!(chunk_size, 0, "Chunk width cannot be zero");
super::Chunks {
inner: self,
width: chunk_size,
}
}
/// Returns an iterator over `chunk_size` bits of the slice at a time,
/// starting at the beginning of the slice.
///
/// The chunks are mutable slices, and do not overlap. If `chunk_size` does
/// not divide the length of the slice, then the last chunk will not have
/// length `chunk_size`.
///
/// See [`chunks_exact_mut`] for a variant of this iterator that returns
/// chunks of always exactly `chunk_size` bits, and [`rchunks_mut`] for the
/// same iterator but starting at the end of the slice.
///
/// # Panics
///
/// Panics if `chunk_size` is 0.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let mut data = 0u8;
/// let bits = data.bits_mut::<Msb0>();
/// let mut count = 0;
///
/// for chunk in bits.chunks_mut(3) {
/// chunk.store(4u8 >> count);
/// count += 1;
/// }
/// assert_eq!(count, 3);
/// assert_eq!(data, 0b100_010_01);
/// ```
///
/// [`chunks_exact_mut`]: #method.chunks_exact_mut
/// [`rchunks_mut`]: #method.rchunks_mut
pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<O, T> {
assert_ne!(chunk_size, 0, "Chunk width cannot be zero");
super::ChunksMut {
inner: self,
width: chunk_size,
}
}
/// Returns an iterator over `chunk_size` elements of the slice at a time,
/// starting at the beginning of the slice.
///
/// The chunks are slices and do not overlap. If `chunk_size` does not
/// divide the length of the slice, then the last up to `chunk_size - 1`
/// elements will be omitted and can be retrieved from the `remainder`
/// function of the iterator.
///
/// Due to each chunk having exactly `chunk_size` elements, the compiler can
/// often optimize the resulting code better than in the case of [`chunks`].
///
/// See [`chunks`] for a variant of this iterator that also returns the
/// remainder as a smaller chunk, and [`rchunks_exact`] for the same
/// iterator but starting at the end of the slice.
///
/// # Panics
///
/// Panics if `chunk_size` is 0.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let data = 0b100_010_01u8;
/// let bits = data.bits::<Msb0>();
/// let mut iter = bits.chunks_exact(3);
/// assert_eq!(iter.next().unwrap(), &bits[0 .. 3]);
/// assert_eq!(iter.next().unwrap(), &bits[3 .. 6]);
/// assert!(iter.next().is_none());
/// assert_eq!(iter.remainder(), &bits[6 .. 8]);
/// ```
///
/// [`chunks`]: #method.chunks
/// [`rchunks_exact`]: #method.rchunks_exact
pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<O, T> {
assert_ne!(chunk_size, 0, "Chunk width cannot be zero");
let len = self.len();
let rem = len % chunk_size;
let mid = len - rem;
let (inner, extra) = self.split_at(mid);
super::ChunksExact {
inner,
extra,
width: chunk_size,
}
}
/// Returns an iterator over `chunk_size` elements of the slice at a time,
/// starting at the beginning of the slice.
///
/// The chunks are mutable slices, and do not overlap. If `chunk_size` does
/// not divide the length of the slice, then the last up to `chunk_size - 1`
/// elements will be omitted and can be retrieved from the `into_remainder`
/// function of the iterator.
///
/// Due to each chunk having exactly `chunk_size` elements, the compiler can
/// often optimize the resulting code better than in the case of
/// [`chunks_mut`].
///
/// See [`chunks_mut`] for a variant of this iterator that also returns the
/// remainder as a smaller chunk, and [`rchunks_exact_mut`] for the same
/// iterator but starting at the end of the slice of the slice.
///
/// # Panics
///
/// Panics if `chunk_size` is 0.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let mut data = 0u8;
/// let bits = data.bits_mut::<Msb0>();
/// let mut count = 0u8;
///
/// let mut iter = bits.chunks_exact_mut(3);
/// for chunk in &mut iter {
/// chunk.store(4u8 >> count);
/// count += 1;
/// }
/// iter.into_remainder().store(1u8);
/// assert_eq!(count, 2);
/// assert_eq!(data, 0b100_010_01);
/// ```
///
/// [`chunks_mut`]: #method.chunks_mut
/// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<O, T> {
assert_ne!(chunk_size, 0, "Chunk width cannot be zero");
let len = self.len();
let rem = len % chunk_size;
let mid = len - rem;
let (inner, extra) = self.split_at_mut(mid);
super::ChunksExactMut {
inner,
extra,
width: chunk_size,
}
}
/// Returns an iterator over `chunk_size` bits of the slice at a time,
/// starting at the end of the slice.
///
/// The chunks are slices and do not overlap. If `chunk_size` does not
/// divide the length of the slice, then the last chunk will not have length
/// of the slice, then the last chunk will not have length `chunk_size`.
///
/// See [`rchunks_exact`] for a variant of this iterator that returns chunks
/// of always exactly `chunk_size` bits, and [`chunks`] for the same
/// iterator but starting at the beginning of the slice.
///
/// # Panics
///
/// Panics if `chunk_size` is 0.
///
/// # Examples
///
/// ```rust
/// # use bitvec::prelude::*;
/// let data = 0b01_010_100u8;
/// let bits = data.bits::<Msb0>();
/// let mut iter = bits.rchunks(3);
/// assert_eq!(iter.next().unwrap(), &bits[5 .. 8]);
/// assert_eq!(iter.next().unwrap(), &bits[2 .. 5]);
/// assert_eq!(iter.next().unwrap(), &bits[0 .. 2]);
/// assert!(iter.next().is_none());