forked from ferrilab/bitvec
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslice.rs
More file actions
1733 lines (1659 loc) · 46.9 KB
/
slice.rs
File metadata and controls
1733 lines (1659 loc) · 46.9 KB
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
#![doc = include_str!("../doc/slice.md")]
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::{
marker::PhantomData,
ops::RangeBounds,
};
use funty::Integral;
use tap::Pipe;
#[cfg(feature = "alloc")]
use tap::Tap;
use wyz::{
bidi::BidiIterator,
comu::{
Const,
Mut,
},
range::RangeExt,
};
#[cfg(feature = "alloc")]
use crate::vec::BitVec;
use crate::{
domain::{
BitDomain,
Domain,
},
mem,
order::{
BitOrder,
Lsb0,
Msb0,
},
ptr::{
self as bv_ptr,
BitPtr,
BitPtrRange,
BitSpan,
BitSpanError,
},
store::BitStore,
};
mod api;
mod iter;
mod ops;
mod specialization;
mod tests;
mod traits;
pub use self::{
api::*,
iter::*,
};
#[repr(transparent)]
#[doc = include_str!("../doc/slice/BitSlice.md")]
pub struct BitSlice<T = usize, O = Lsb0>
where
T: BitStore,
O: BitOrder,
{
/// The ordering of bits within a `T` register.
_ord: PhantomData<O>,
/// The register type used for storage.
_typ: PhantomData<[T]>,
/// Indicate that this is a newtype wrapper over a wholly-untyped slice.
///
/// This is necessary in order for the Rust compiler to remove restrictions
/// on the possible values of reference handles to this type. Any other
/// slice type here (such as `[u8]` or `[T]`) would require that `&/mut
/// BitSlice` handles have values that correctly describe the region, and
/// the encoding *does not* do this. As such, reference handles to
/// `BitSlice` must not be even implicitly dereferenceäble to real memory,
/// and the slice must be a ZST.
///
/// References to a ZST have no restrictions about what the values can be,
/// as they are never able to dereference real memory and thus both
/// addresses and lengths are meaningless to the memory inspector.
///
/// See `ptr::span` for more information on the encoding scheme used in
/// references to `BitSlice`.
_mem: [()],
}
/// Constructors.
impl<T, O> BitSlice<T, O>
where
T: BitStore,
O: BitOrder,
{
/// Produces an empty bit-slice with an arbitrary lifetime.
///
/// ## Original
///
/// This is equivalent to the `&[]` literal.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// assert!(BitSlice::<u16, LocalBits>::empty().is_empty());
/// assert_eq!(bits![], BitSlice::<u8, Msb0>::empty());
/// ```
pub fn empty<'a>() -> &'a Self {
unsafe { BitSpan::<Const, T, O>::EMPTY.into_bitslice_ref() }
}
/// Produces an empty bit-slice with an arbitrary lifetime.
///
/// ## Original
///
/// This is equivalent to the `&mut []` literal.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// assert!(BitSlice::<u16, LocalBits>::empty_mut().is_empty());
/// assert_eq!(bits![mut], BitSlice::<u8, Msb0>::empty_mut());
/// ```
pub fn empty_mut<'a>() -> &'a mut Self {
unsafe { BitSpan::<Mut, T, O>::EMPTY.into_bitslice_mut() }
}
/// Constructs a shared `&BitSlice` reference over a shared element.
///
/// The [`BitView`] trait, implemented on all [`BitStore`] implementors,
/// provides a [`.view_bits::<O>()`] method which delegates to this function
/// and may be more convenient for you to write.
///
/// ## Parameters
///
/// - `elem`: A shared reference to a memory element.
///
/// ## Returns
///
/// A shared `&BitSlice` over `elem`.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let elem = 0u8;
/// let bits = BitSlice::<_, Lsb0>::from_element(&elem);
/// assert_eq!(bits.len(), 8);
///
/// let bits = elem.view_bits::<Lsb0>();
/// ```
///
/// [`BitStore`]: crate::store::BitStore
/// [`BitView`]: crate::view::BitView
/// [`.view_bits::<O>()`]: crate::view::BitView::view_bits
pub fn from_element(elem: &T) -> &Self {
unsafe {
BitPtr::from_ref(elem)
.span_unchecked(mem::bits_of::<T::Mem>())
.into_bitslice_ref()
}
}
/// Constructs an exclusive `&mut BitSlice` reference over an element.
///
/// The [`BitView`] trait, implemented on all [`BitStore`] implementors,
/// provides a [`.view_bits_mut::<O>()`] method which delegates to this
/// function and may be more convenient for you to write.
///
/// ## Parameters
///
/// - `elem`: An exclusive reference to a memory element.
///
/// ## Returns
///
/// An exclusive `&mut BitSlice` over `elem`.
///
/// Note that the original `elem` reference will be inaccessible for the
/// duration of the returned bit-slice handle’s lifetime.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let mut elem = 0u8;
/// let bits = BitSlice::<_, Lsb0>::from_element_mut(&mut elem);
/// bits.set(1, true);
/// assert!(bits[1]);
/// assert_eq!(elem, 2);
///
/// let bits = elem.view_bits_mut::<Lsb0>();
/// ```
///
/// [`BitStore`]: crate::store::BitStore
/// [`BitView`]: crate::view::BitView
/// [`.view_bits_mut::<O>()`]: crate::view::BitView::view_bits_mut
pub fn from_element_mut(elem: &mut T) -> &mut Self {
unsafe {
BitPtr::from_mut(elem)
.span_unchecked(mem::bits_of::<T::Mem>())
.into_bitslice_mut()
}
}
/// Constructs a shared `&BitSlice` reference over a slice of elements.
///
/// The [`BitView`] trait, implemented on all `[T]` slices, provides a
/// [`.view_bits::<O>()`] method which delegates to this function and may be
/// more convenient for you to write.
///
/// ## Parameters
///
/// - `slice`: A shared reference to a slice of memory elements.
///
/// ## Returns
///
/// A shared `BitSlice` reference over all of `slice`.
///
/// ## Panics
///
/// This will panic if `slice` is too long to encode as a bit-slice view.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let data = [0u16, 1];
/// let bits = BitSlice::<_, Lsb0>::from_slice(&data);
/// assert!(bits[16]);
///
/// let bits = data.view_bits::<Lsb0>();
/// ```
///
/// [`BitView`]: crate::view::BitView
/// [`.view_bits::<O>()`]: crate::view::BitView::view_bits
pub fn from_slice(slice: &[T]) -> &Self {
Self::try_from_slice(slice).unwrap()
}
/// Attempts to construct a shared `&BitSlice` reference over a slice of
/// elements.
///
/// The [`BitView`], implemented on all `[T]` slices, provides a
/// [`.try_view_bits::<O>()`] method which delegates to this function and
/// may be more convenient for you to write.
///
/// This is *very hard*, if not impossible, to cause to fail. Rust will not
/// create excessive arrays on 64-bit architectures.
///
/// ## Parameters
///
/// - `slice`: A shared reference to a slice of memory elements.
///
/// ## Returns
///
/// A shared `&BitSlice` over `slice`. If `slice` is longer than can be
/// encoded into a `&BitSlice` (see [`MAX_ELTS`]), this will fail and return
/// the original `slice` as an error.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let data = [0u8, 1];
/// let bits = BitSlice::<_, Msb0>::try_from_slice(&data).unwrap();
/// assert!(bits[15]);
///
/// let bits = data.try_view_bits::<Msb0>().unwrap();
/// ```
///
/// [`BitView`]: crate::view::BitView
/// [`MAX_ELTS`]: Self::MAX_ELTS
/// [`.try_view_bits::<O>()`]: crate::view::BitView::try_view_bits
pub fn try_from_slice(slice: &[T]) -> Result<&Self, BitSpanError<T>> {
let elts = slice.len();
if elts >= Self::MAX_ELTS {
elts.saturating_mul(mem::bits_of::<T::Mem>())
.pipe(BitSpanError::TooLong)
.pipe(Err)
}
else {
Ok(unsafe { Self::from_slice_unchecked(slice) })
}
}
/// Constructs an exclusive `&mut BitSlice` reference over a slice of
/// elements.
///
/// The [`BitView`] trait, implemented on all `[T]` slices, provides a
/// [`.view_bits_mut::<O>()`] method which delegates to this function and
/// may be more convenient for you to write.
///
/// ## Parameters
///
/// - `slice`: An exclusive reference to a slice of memory elements.
///
/// ## Returns
///
/// An exclusive `&mut BitSlice` over all of `slice`.
///
/// ## Panics
///
/// This panics if `slice` is too long to encode as a bit-slice view.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let mut data = [0u16; 2];
/// let bits = BitSlice::<_, Lsb0>::from_slice_mut(&mut data);
/// bits.set(0, true);
/// bits.set(17, true);
/// assert_eq!(data, [1, 2]);
///
/// let bits = data.view_bits_mut::<Lsb0>();
/// ```
///
/// [`BitView`]: crate::view::BitView
/// [`.view_bits_mut::<O>()`]: crate::view::BitView::view_bits_mut
pub fn from_slice_mut(slice: &mut [T]) -> &mut Self {
Self::try_from_slice_mut(slice).unwrap()
}
/// Attempts to construct an exclusive `&mut BitSlice` reference over a
/// slice of elements.
///
/// The [`BitView`] trait, implemented on all `[T]` slices, provides a
/// [`.try_view_bits_mut::<O>()`] method which delegates to this function
/// and may be more convenient for you to write.
///
/// ## Parameters
///
/// - `slice`: An exclusive reference to a slice of memory elements.
///
/// ## Returns
///
/// An exclusive `&mut BitSlice` over `slice`. If `slice` is longer than can
/// be encoded into a `&mut BitSlice` (see [`MAX_ELTS`]), this will fail and
/// return the original `slice` as an error.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let mut data = [0u8; 2];
/// let bits = BitSlice::<_, Msb0>::try_from_slice_mut(&mut data).unwrap();
/// bits.set(7, true);
/// bits.set(15, true);
/// assert_eq!(data, [1; 2]);
///
/// let bits = data.try_view_bits_mut::<Msb0>().unwrap();
/// ```
///
/// [`BitView`]: crate::view::BitView
/// [`MAX_ELTS`]: Self::MAX_ELTS
/// [`.try_view_bits_mut::<O>()`]: crate::view::BitView::try_view_bits_mut
pub fn try_from_slice_mut(
slice: &mut [T],
) -> Result<&mut Self, BitSpanError<T>> {
let elts = slice.len();
if elts >= Self::MAX_ELTS {
elts.saturating_mul(mem::bits_of::<T::Mem>())
.pipe(BitSpanError::TooLong)
.pipe(Err)
}
else {
Ok(unsafe { Self::from_slice_unchecked_mut(slice) })
}
}
/// Constructs a shared `&BitSlice` over an element slice, without checking
/// its length.
///
/// If `slice` is too long to encode into a `&BitSlice`, then the produced
/// bit-slice’s length is unspecified.
///
/// ## Safety
///
/// You must ensure that `slice.len() < BitSlice::MAX_ELTS`.
///
/// Calling this function with an over-long slice is **library-level**
/// undefined behavior. You may not assume anything about its implementation
/// or behavior, and must conservatively assume that over-long slices cause
/// compiler UB.
pub unsafe fn from_slice_unchecked(slice: &[T]) -> &Self {
let bits = slice.len().wrapping_mul(mem::bits_of::<T::Mem>());
BitPtr::from_slice(slice)
.span_unchecked(bits)
.into_bitslice_ref()
}
/// Constructs an exclusive `&mut BitSlice` over an element slice, without
/// checking its length.
///
/// If `slice` is too long to encode into a `&mut BitSlice`, then the
/// produced bit-slice’s length is unspecified.
///
/// ## Safety
///
/// You must ensure that `slice.len() < BitSlice::MAX_ELTS`.
///
/// Calling this function with an over-long slice is **library-level**
/// undefined behavior. You may not assume anything about its implementation
/// or behavior, and must conservatively assume that over-long slices cause
/// compiler UB.
pub unsafe fn from_slice_unchecked_mut(slice: &mut [T]) -> &mut Self {
let bits = slice.len().wrapping_mul(mem::bits_of::<T::Mem>());
BitPtr::from_slice_mut(slice)
.span_unchecked(bits)
.into_bitslice_mut()
}
}
/// Alternates of standard APIs.
impl<T, O> BitSlice<T, O>
where
T: BitStore,
O: BitOrder,
{
/// Gets a raw pointer to the zeroth bit of the bit-slice.
///
/// ## Original
///
/// [`slice::as_ptr`](https://doc.rust-lang.org/std/primitive.slice.html#method.as_ptr)
///
/// ## API Differences
///
/// This is renamed in order to indicate that it is returning a `bitvec`
/// structure, not a raw pointer.
pub fn as_bitptr(&self) -> BitPtr<Const, T, O> {
self.as_bitspan().to_bitptr()
}
/// Gets a raw, write-capable pointer to the zeroth bit of the bit-slice.
///
/// ## Original
///
/// [`slice::as_mut_ptr`](https://doc.rust-lang.org/std/primitive.slice.html#method.as_mut_ptr)
///
/// ## API Differences
///
/// This is renamed in order to indicate that it is returning a `bitvec`
/// structure, not a raw pointer.
pub fn as_mut_bitptr(&mut self) -> BitPtr<Mut, T, O> {
self.as_mut_bitspan().to_bitptr()
}
/// Views the bit-slice as a half-open range of bit-pointers, to its first
/// bit *in* the bit-slice and first bit *beyond* it.
///
/// ## Original
///
/// [`slice::as_ptr_range`](https://doc.rust-lang.org/std/primitive.slice.html#method.as_ptr_range)
///
/// ## API Differences
///
/// This is renamed to indicate that it returns a `bitvec` structure, rather
/// than an ordinary `Range`.
///
/// ## Notes
///
/// `BitSlice` does define a [`.as_ptr_range()`], which returns a
/// `Range<BitPtr>`. `BitPtrRange` has additional capabilities that
/// `Range<*const T>` and `Range<BitPtr>` do not.
///
/// [`.as_ptr_range()`]: Self::as_ptr_range
pub fn as_bitptr_range(&self) -> BitPtrRange<Const, T, O> {
self.as_bitspan().to_bitptr_range()
}
/// Views the bit-slice as a half-open range of write-capable bit-pointers,
/// to its first bit *in* the bit-slice and the first bit *beyond* it.
///
/// ## Original
///
/// [`slice::as_mut_ptr_range`](https://doc.rust-lang.org/std/primitive.slice.html#method.as_mut_ptr_range)
///
/// ## API Differences
///
/// This is renamed to indicate that it returns a `bitvec` structure, rather
/// than an ordinary `Range`.
///
/// ## Notes
///
/// `BitSlice` does define a [`.as_mut_ptr_range()`], which returns a
/// `Range<BitPtr>`. `BitPtrRange` has additional capabilities that
/// `Range<*mut T>` and `Range<BitPtr>` do not.
pub fn as_mut_bitptr_range(&mut self) -> BitPtrRange<Mut, T, O> {
self.as_mut_bitspan().to_bitptr_range()
}
/// Copies the bits from `src` into `self`.
///
/// `self` and `src` must have the same length.
///
/// ## Performance
///
/// If `src` has the same type arguments as `self`, it will use the same
/// implementation as [`.copy_from_bitslice()`]; if you know that this will
/// always be the case, you should prefer to use that method directly.
///
/// Only `.copy_from_bitslice()` is *able* to perform acceleration; this
/// method is *always* required to perform a bit-by-bit crawl over both
/// bit-slices.
///
/// ## Original
///
/// [`slice::clone_from_slice`](https://doc.rust-lang.org/std/primitive.slice.html#method.clone_from_slice)
///
/// ## API Differences
///
/// This is renamed to reflect that it copies from another bit-slice, not
/// from an element slice.
///
/// In order to support general usage, it allows `src` to have different
/// type parameters than `self`, at the cost of performance optimizations.
///
/// ## Panics
///
/// This panics if the two bit-slices have different lengths.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
/// ```
///
/// [`.copy_from_bitslice()`]: Self::copy_from_bitslice
pub fn clone_from_bitslice<T2, O2>(&mut self, src: &BitSlice<T2, O2>)
where
T2: BitStore,
O2: BitOrder,
{
assert_eq!(
self.len(),
src.len(),
"cloning between bit-slices requires equal lengths",
);
if let Some(that) = src.coerce::<T, O>() {
self.copy_from_bitslice(that);
}
// TODO(myrrlyn): Test if `<T::Mem, O>` matches `<T2::Mem, O>` and
// specialize cloning.
else {
for (to, bit) in self.as_mut_bitptr_range().zip(src.iter().by_vals())
{
unsafe {
to.write(bit);
}
}
}
}
/// Copies all bits from `src` into `self`, using batched acceleration when
/// possible.
///
/// `self` and `src` must have the same length.
///
/// ## Original
///
/// [`slice::copy_from_slice`](https://doc.rust-lang.org/std/primitive.slice.html#method.copy_from_slice)
///
/// ## Panics
///
/// This panics if the two bit-slices have different lengths.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
/// ```
pub fn copy_from_bitslice(&mut self, src: &Self) {
assert_eq!(
self.len(),
src.len(),
"copying between bit-slices requires equal lengths",
);
let (to_head, from_head) =
(self.as_bitspan().head(), src.as_bitspan().head());
if to_head == from_head {
match (self.domain_mut(), src.domain()) {
(Domain::Enclave(mut to), Domain::Enclave(from)) => {
to.store_value(from.load_value());
},
(
Domain::Region {
head: to_head,
body: to_body,
tail: to_tail,
},
Domain::Region {
head: from_head,
body: from_body,
tail: from_tail,
},
) => {
if let (Some(mut to), Some(from)) = (to_head, from_head) {
to.store_value(from.load_value());
}
for (to, from) in to_body.iter_mut().zip(from_body) {
to.store_value(from.load_value());
}
if let (Some(mut to), Some(from)) = (to_tail, from_tail) {
to.store_value(from.load_value());
}
},
_ => unreachable!(
"bit-slices with equal type parameters, lengths, and heads \
will always have equal domains"
),
}
}
if let (Some(this), Some(that)) =
(self.coerce_mut::<T, Lsb0>(), src.coerce::<T, Lsb0>())
{
return this.sp_copy_from_bitslice(that);
}
if let (Some(this), Some(that)) =
(self.coerce_mut::<T, Msb0>(), src.coerce::<T, Msb0>())
{
return this.sp_copy_from_bitslice(that);
}
for (to, bit) in self.as_mut_bitptr_range().zip(src.iter().by_vals()) {
unsafe {
to.write(bit);
}
}
}
/// Swaps the contents of two bit-slices.
///
/// `self` and `other` must have the same length.
///
/// ## Original
///
/// [`slice::swap_with_slice`](https://doc.rust-lang.org/std/primitive.slice.html#method.swap_with_slice)
///
/// ## API Differences
///
/// This method is renamed, as it takes a bit-slice rather than an element
/// slice.
///
/// ## Panics
///
/// This panics if the two bit-slices have different lengths.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let mut one = [0xA5u8, 0x69];
/// let mut two = 0x1234u16;
/// let one_bits = one.view_bits_mut::<Msb0>();
/// let two_bits = two.view_bits_mut::<Lsb0>();
///
/// one_bits.swap_with_bitslice(two_bits);
///
/// assert_eq!(one, [0x2C, 0x48]);
/// # if cfg!(target_endian = "little") {
/// assert_eq!(two, 0x96A5);
/// # }
/// ```
pub fn swap_with_bitslice<T2, O2>(&mut self, other: &mut BitSlice<T2, O2>)
where
T2: BitStore,
O2: BitOrder,
{
assert_eq!(
self.len(),
other.len(),
"swapping between bit-slices requires equal lengths",
);
if let (Some(this), Some(that)) =
(self.coerce_mut::<T, Lsb0>(), other.coerce_mut::<T, Lsb0>())
{
return this.sp_swap_with_bitslice(that);
}
if let (Some(this), Some(that)) =
(self.coerce_mut::<T, Msb0>(), other.coerce_mut::<T, Msb0>())
{
return this.sp_swap_with_bitslice(that);
}
self.as_mut_bitptr_range()
.zip(other.as_mut_bitptr_range())
.for_each(|(a, b)| unsafe {
bv_ptr::swap(a, b);
});
}
}
/// Extensions of standard APIs.
impl<T, O> BitSlice<T, O>
where
T: BitStore,
O: BitOrder,
{
/// Writes a new value into a single bit.
///
/// This is the replacement for `*slice[index] = value;`, as `bitvec` is not
/// able to express that under the current `IndexMut` API signature.
///
/// ## Parameters
///
/// - `&mut self`
/// - `index`: The bit-index to set. It must be in `0 .. self.len()`.
/// - `value`: The new bit-value to write into the bit at `index`.
///
/// ## Panics
///
/// This panics if `index` is out of bounds.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let bits = bits![mut 0, 1];
/// bits.set(0, true);
/// bits.set(1, false);
///
/// assert_eq!(bits, bits![1, 0]);
/// ```
pub fn set(&mut self, index: usize, value: bool) {
self.replace(index, value);
}
/// Writes a new value into a single bit, without bounds checking.
///
/// ## Parameters
///
/// - `&mut self`
/// - `index`: The bit-index to set. It must be in `0 .. self.len()`.
/// - `value`: The new bit-value to write into the bit at `index`.
///
/// ## Safety
///
/// You must ensure that `index` is in the range `0 .. self.len()`.
///
/// This performs bit-pointer offset arithmetic without doing any bounds
/// checks. If `index` is out of bounds, then this will issue an
/// out-of-bounds access and will trigger memory unsafety.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let mut data = 0u8;
/// let bits = &mut data.view_bits_mut::<Lsb0>()[.. 2];
/// assert_eq!(bits.len(), 2);
/// unsafe {
/// bits.set_unchecked(3, true);
/// }
/// assert_eq!(data, 8);
/// ```
pub unsafe fn set_unchecked(&mut self, index: usize, value: bool) {
self.replace_unchecked(index, value);
}
/// Writes a new value into a bit, and returns its previous value.
///
/// ## Panics
///
/// This panics if `index` is not less than `self.len()`.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let bits = bits![mut 0];
/// assert!(!bits.replace(0, true));
/// assert!(bits[0]);
/// ```
pub fn replace(&mut self, index: usize, value: bool) -> bool {
self.assert_in_bounds(index, 0 .. self.len());
unsafe { self.replace_unchecked(index, value) }
}
/// Writes a new value into a bit, returning the previous value, without
/// bounds checking.
///
/// ## Safety
///
/// `index` must be less than `self.len()`.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let bits = bits![mut 0, 0];
/// let old = unsafe {
/// let a = &mut bits[.. 1];
/// a.replace_unchecked(1, true)
/// };
/// assert!(!old);
/// assert!(bits[1]);
/// ```
pub unsafe fn replace_unchecked(
&mut self,
index: usize,
value: bool,
) -> bool {
self.as_mut_bitptr().add(index).replace(value)
}
/// Swaps two bits in a bit-slice, without bounds checking.
///
/// See [`.swap()`] for documentation.
///
/// ## Safety
///
/// You must ensure that `a` and `b` are both in the range `0 ..
/// self.len()`.
///
/// This method performs bit-pointer offset arithmetic without doing any
/// bounds checks. If `a` or `b` are out of bounds, then this will issue an
/// out-of-bounds access and will trigger memory unsafety.
///
/// [`.swap()`]: Self::swap
pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize) {
let a = self.as_mut_bitptr().add(a);
let b = self.as_mut_bitptr().add(b);
bv_ptr::swap(a, b);
}
/// Splits a bit-slice at an index, without bounds checking.
///
/// See [`.split_at()`] for documentation.
///
/// ## Safety
///
/// You must ensure that `mid` is in the range `0 ..= self.len()`.
///
/// This method produces new bit-slice references. If `mid` is out of
/// bounds, its behavior is **library-level** undefined. You must
/// conservatively assume that an out-of-bounds split point produces
/// compiler-level UB.
///
/// [`.split_at()`]: Self::split_at
pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&Self, &Self) {
let len = self.len();
let left = self.as_bitptr();
let right = left.add(mid);
let left = left.span_unchecked(mid);
let right = right.span_unchecked(len - mid);
let left = left.into_bitslice_ref();
let right = right.into_bitslice_ref();
(left, right)
}
/// Splits a mutable bit-slice at an index, without bounds checking.
///
/// See [`.split_at_mut()`] for documentation.
///
/// ## Safety
///
/// You must ensure that `mid` is in the range `0 ..= self.len()`.
///
/// This method produces new bit-slice references. If `mid` is out of
/// bounds, its behavior is **library-level** undefined. You must
/// conservatively assume that an out-of-bounds split point produces
/// compiler-level UB.
///
/// [`.split_at_mut()`]: Self::split_at_mut
pub unsafe fn split_at_unchecked_mut(
&mut self,
mid: usize,
) -> (&mut BitSlice<T::Alias, O>, &mut BitSlice<T::Alias, O>) {
let len = self.len();
let left = self.alias_mut().as_mut_bitptr();
let right = left.add(mid);
(
left.span_unchecked(mid).into_bitslice_mut(),
right.span_unchecked(len - mid).into_bitslice_mut(),
)
}
/// Copies bits from one region of the bit-slice to another region of
/// itself, without doing bounds checks.
///
/// The regions are allowed to overlap.
///
/// ## Parameters
///
/// - `&mut self`
/// - `src`: The range within `self` from which to copy.
/// - `dst`: The starting index within `self` at which to paste.
///
/// ## Effects
///
/// `self[src]` is copied to `self[dest .. dest + src.len()]`. The bits of
/// `self[src]` are in an unspecified, but initialized, state.
///
/// ## Safety
///
/// `src.end()` and `dest + src.len()` must be entirely within bounds.
///
/// ## Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let mut data = 0b1011_0000u8;
/// let bits = data.view_bits_mut::<Msb0>();
///
/// unsafe {
/// bits.copy_within_unchecked(.. 4, 2);
/// }
/// assert_eq!(data, 0b1010_1100);
/// ```
pub unsafe fn copy_within_unchecked<R>(&mut self, src: R, dest: usize)
where R: RangeExt<usize> {
if let Some(this) = self.coerce_mut::<T, Lsb0>() {
return this.sp_copy_within_unchecked(src, dest);
}
if let Some(this) = self.coerce_mut::<T, Msb0>() {
return this.sp_copy_within_unchecked(src, dest);
}
let source = src.normalize(0, self.len());
let source_len = source.len();
let rev = source.contains(&dest);
let dest = dest .. dest + source_len;
for (from, to) in self
.get_unchecked(source)
.as_bitptr_range()
.zip(self.get_unchecked_mut(dest).as_mut_bitptr_range())
.bidi(rev)
{
to.write(from.read());
}
}
#[doc(hidden)]
#[cfg(not(tarpaulin_include))]
#[deprecated = "use `.iter_mut().enumerate()`"]
pub fn for_each(&mut self, mut func: impl FnMut(usize, bool) -> bool) {
for (idx, ptr) in self.as_mut_bitptr_range().enumerate() {
unsafe {
ptr.write(func(idx, ptr.read()));
}
}
}
}
/// Views of underlying memory.
impl<T, O> BitSlice<T, O>
where
T: BitStore,
O: BitOrder,
{
/// Partitions a bit-slice into maybe-contended and known-uncontended parts.
///
/// The documentation of `BitDomain` goes into this in more detail. In
/// short, this produces a `&BitSlice` that is as large as possible without
/// requiring alias protection, as well as any bits that were not able to be
/// included in the unaliased bit-slice.
#[cfg(not(tarpaulin_include))]
pub fn bit_domain(&self) -> BitDomain<Const, T, O> {
self.domain().into_bit_domain()
}
/// Partitions a mutable bit-slice into maybe-contended and
/// known-uncontended parts.
///
/// The documentation of `BitDomain` goes into this in more detail. In
/// short, this produces a `&mut BitSlice` that is as large as possible
/// without requiring alias protection, as well as any bits that were not
/// able to be included in the unaliased bit-slice.
#[cfg(not(tarpaulin_include))]
pub fn bit_domain_mut(&mut self) -> BitDomain<Mut, T, O> {
self.domain_mut().into_bit_domain()
}
/// Views the underlying memory of a bit-slice, removing alias protections
/// where possible.
///
/// The documentation of `Domain` goes into this in more detail. In short,
/// this produces a `&[T]` slice with alias protections removed, covering
/// all elements that `self` completely fills. Partially-used elements on
/// either the front or back edge of the slice are returned separately.
#[cfg(not(tarpaulin_include))]
pub fn domain(&self) -> Domain<Const, T, O> {
Domain::new(self)
}
/// Views the underlying memory of a bit-slice, removing alias protections