Repository navigation
Expand file tree
/
Copy pathslice.rs
More file actions
2808 lines (2638 loc) · 81.4 KB
/
Copy pathslice.rs
File metadata and controls
2808 lines (2638 loc) · 81.4 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
/*! A dynamically-sized view into individual bits of a memory region.
You can read the language’s [`slice` module documentation][std] here.
This module defines the [`BitSlice`] region, and all of its associated support
code.
[`BitSlice`] is the primary working type of this crate. It is a wrapper type
over `[T]` which enables you to view, manipulate, and take the address of
individual bits in memory. It behaves in every possible respect exactly like an
ordinary slice: it is dynamically-sized, and must be held by `&` or `&mut`
reference, just like `[T]`, and implements every inherent method and trait that
`[T]` does, to the absolute limits of what Rust permits.
The key to [`BitSlice`]’s powerful capability is that references to it use a
special encoding that store, in addition to the address of the base element and
the bit length, the index of the starting bit in the base element. This custom
reference encoding has some costs in what APIs are possible – for instance, Rust
forbids it from supporting `&mut BitSlice[index] = bool` write indexing – but in
exchange, enables it to be *far* more capable than any other bit-slice crate in
existence.
Because of the volume of code that must be written to match the `[T]` standard
API, this module is organized very differently than the slice implementation in
the [`core`] and [`std`] distribution libraries.
- the root module `slice` contains new APIs that have no counterpart in `[T]`
- `slice/api` contains reïmplementations of the `[T]` inherent methods
- `slice/iter` implements all of the iteration capability
- `slice/ops` implements the traits in `core::ops`
- `slice/proxy` implements the proxy reference used in place of `&mut bool`
- `slice/traits` implements all other traits not in `core::ops`
- lastly, `slice/tests` contains all the unit tests.
[`BitSlice`]: struct.BitSlice.html
[`core`]: core
[`std`]: std
[std]: https://doc.rust-lang.org/stable/std/slice
!*/
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
#[cfg(feature = "alloc")]
use core::mem::ManuallyDrop;
use core::{
marker::PhantomData,
ops::RangeBounds,
ptr,
slice,
};
use funty::{
IsInteger,
IsNumber,
};
use radium::Radium;
#[cfg(feature = "alloc")]
use tap::pipe::Pipe;
// Match the `core::slice` module topology.
pub use self::{
api::{
from_mut,
from_raw_parts,
from_raw_parts_mut,
from_ref,
BitSliceIndex,
},
iter::{
BitRefIter,
BitValIter,
Chunks,
ChunksExact,
ChunksExactMut,
ChunksMut,
Iter,
IterMut,
IterOnes,
IterZeros,
RChunks,
RChunksExact,
RChunksExactMut,
RChunksMut,
RSplit,
RSplitMut,
RSplitN,
RSplitNMut,
Split,
SplitMut,
SplitN,
SplitNMut,
Windows,
},
};
use crate::{
access::BitAccess,
devel as dvl,
domain::{
BitDomain,
BitDomainMut,
Domain,
DomainMut,
},
index::BitMask,
mem::BitRegister,
order::{
BitOrder,
Lsb0,
Msb0,
},
ptr::{
BitPtr,
BitPtrRange,
BitRef,
BitSpan,
BitSpanError,
Const,
Mut,
},
store::BitStore,
};
#[cfg(feature = "alloc")]
use crate::{
ptr::AddressExt,
vec::BitVec,
};
mod api;
mod iter;
mod ops;
mod specialization;
mod traits;
/** A slice of individual bits, anywhere in memory.
`BitSlice<O, T>` is an unsized region type; you interact with it through
`&BitSlice<O, T>` and `&mut BitSlice<O, T>` references, which work exactly like
all other Rust references. As with the standard slice’s relationship to arrays
and vectors, this is [`bitvec`]’s primary working type, but you will probably
hold it through one of the provided [`BitArray`], [`BitBox`], or [`BitVec`]
containers.
`BitSlice` is conceptually a `[bool]` slice, and provides a nearly complete
mirror of `[bool]`’s API.
Every bit-vector crate can give you an opaque type that hides shift/mask
calculations from you. `BitSlice` does far more than this: it offers you the
full Rust guarantees about reference behavior, including lifetime tracking,
mutability and aliasing awareness, and explicit memory control, *as well as* the
full set of tools and APIs available to the standard `[bool]` slice type.
`BitSlice` can arbitrarily split and subslice, just like `[bool]`. You can write
a linear consuming function and keep the patterns you already know.
For example, to trim all the bits off either edge that match a condition, you
could write
```rust
use bitvec::prelude::*;
fn trim<O: BitOrder, T: BitStore>(
bits: &BitSlice<O, T>,
to_trim: bool,
) -> &BitSlice<O, T> {
let stop = |b: &bool| *b != to_trim;
let front = bits.iter().by_ref().position(stop).unwrap_or(0);
let back = bits.iter().by_ref().rposition(stop).map_or(0, |p| p + 1);
&bits[front .. back]
}
# assert_eq!(trim(bits![0, 0, 1, 1, 0, 1, 0], false), bits![1, 1, 0, 1]);
```
to get behavior something like
`trim(&BitSlice[0, 0, 1, 1, 0, 1, 0], false) == &BitSlice[1, 1, 0, 1]`.
# Documentation
All APIs that mirror something in the standard library will have an `Original`
section linking to the corresponding item. All APIs that have a different
signature or behavior than the original will have an `API Differences` section
explaining what has changed, and how to adapt your existing code to the change.
These sections look like this:
# Original
[`slice`](https://doc.rust-lang.org/stable/std/primitive.slice.html)
# API Differences
The slice type `[bool]` has no type parameters. `BitSlice<O, T>` has two: one
for the memory type used as backing storage, and one for the order of bits
within that memory type.
`&BitSlice<O, T>` is capable of producing `&bool` references to read bits out
of its memory, but is not capable of producing `&mut bool` references to write
bits *into* its memory. Any `[bool]` API that would produce a `&mut bool` will
instead produce a [`BitRef<Mut, O, T>`] proxy reference.
# Behavior
`BitSlice` is a wrapper over `[T]`. It describes a region of memory, and must be
handled indirectly. This is most commonly through the reference types
`&BitSlice` and `&mut BitSlice`, which borrow memory owned by some other value
in the program. These buffers can be directly owned by the sibling types
[`BitBox`], which behaves like [`Box<[T]>`](alloc::boxed::Box), and [`BitVec`],
which behaves like [`Vec<T>`]. It cannot be used as the type parameter to a
standard-library-provided handle type.
The `BitSlice` region provides access to each individual bit in the region, as
if each bit had a memory address that you could use to dereference it. It packs
each logical bit into exactly one bit of storage memory, just like
[`std::bitset`] and [`std::vector<bool>`] in C++.
# Type Parameters
`BitSlice` has two type parameters which propagate through nearly every public
API in the crate. These are very important to its operation, and your choice
of type arguments informs nearly every part of this library’s behavior.
## `T: BitStore`
[`BitStore`] is the simpler of the two parameters. It refers to the integer type
used to hold bits. It must be one of the Rust unsigned integer fundamentals:
`u8`, `u16`, `u32`, `usize`, and on 64-bit systems only, `u64`. In addition, it
can also be an alias-safe wrapper over them (see the [`access`] module) in
order to permit bit-slices to share underlying memory without interfering with
each other.
`BitSlice` references can only be constructed over the integers, not over their
aliasing wrappers. `BitSlice` will only use aliasing types in its `T` slots when
you invoke APIs that produce them, such as [`.split_at_mut()`].
The default type argument is `usize`.
The argument you choose is used as the basis of a `[T]` slice, over which the
`BitSlice` view type is placed. `BitSlice<_, T>` is subject to all of the rules
about alignment that `[T]` is. If you are working with in-memory representation
formats, chances are that you already have a `T` type with which you’ve been
working, and should use it here.
If you are only using this crate to discard the seven wasted bits per `bool`
of a collection of `bool`s, and are not too concerned about the in-memory
representation, then you should use the default type argument of `usize`. This
is because most processors work best when moving an entire `usize` between
memory and the processor itself, and using a smaller type may cause it to slow
down.
## `O: BitOrder`
[`BitOrder`] is the more complex parameter. It has a default argument which,
like `usize`, is the good-enough choice when you do not explicitly need to
control the representation of bits in memory.
This parameter determines how to index the bits within a single memory element
`T`. Computers all agree that in a slice of elements `T`, the element with the
lower index has a lower memory address than the element with the higher index.
But the individual bits within an element do not have addresses, and so there is
no uniform standard of which bit is the zeroth, which is the first, which is the
penultimate, and which is the last.
To make matters even more confusing, there are two predominant ideas of
in-element ordering that often *correlate* with the in-element *byte* ordering
of integer types, but are in fact wholly unrelated! [`bitvec`] provides these
two main orders as types for you, and if you need a different one, it also
provides the tools you need to make your own.
### Least Significant Bit Comes First
This ordering, named the [`Lsb0`] type, indexes bits within an element by
placing the `0` index at the least significant bit (numeric value `1`) and the
final index at the most significant bit (numeric value [`T::MIN`][minval] for
signed integers on most machines).
For example, this is the ordering used by most C compilers to lay out bit-field
struct members on little-endian **byte**-ordered machines.
### Most Significant Bit Comes First
This ordering, named the [`Msb0`] type, indexes bits within an element by
placing the `0` index at the most significant bit (numeric value
[`T::MIN`][minval] for most signed integers) and the final index at the least
significant bit (numeric value `1`).
For example, this is the ordering used by the [TCP wire format], and by most C
compilers to lay out bit-field struct members on big-endian **byte**-ordered
machines.
### Default Ordering
The default ordering is [`Lsb0`], as it typically produces shorter object code
than [`Msb0`] does. If you are implementing a collection, then `Lsb0` is likely
the more performant ordering; if you are implementing a buffer protocol, then
your choice of ordering is dictated by the protocol definition.
# Safety
`BitSlice` is designed to never introduce new memory unsafety that you did not
provide yourself, either before or during the use of this crate. Bugs do, and
have, occurred, and you are encouraged to submit any discovered flaw as a defect
report.
The `&BitSlice` reference type uses a private encoding scheme to hold all the
information needed in its stack value. This encoding is **not** part of the
public API of the library, and is not binary-compatible with `&[T]`.
Furthermore, in order to satisfy Rust’s requirements about alias conditions,
`BitSlice` performs type transformations on the `T` parameter to ensure that it
never creates the potential for undefined behavior.
You must never attempt to type-cast a reference to `BitSlice` in any way. You
must not use [`mem::transmute`] with `BitSlice` anywhere in its type arguments.
You must not use `as`-casting to convert between `*BitSlice` and any other type.
You must not attempt to modify the binary representation of a `&BitSlice`
reference value. These actions will all lead to runtime memory unsafety, are
(hopefully) likely to induce a program crash, and may possibly cause undefined
behavior at compile-time.
Everything in the `BitSlice` public API, even the `unsafe` parts, are guaranteed
to have no more unsafety than their equivalent parts in the standard library.
All `unsafe` APIs will have documentation explicitly detailing what the API
requires you to uphold in order for it to function safely and correctly. All
safe APIs will do so themselves.
# Performance
Like the standard library’s `[T]` slice, `BitSlice` is designed to be very easy
to use safely, while supporting `unsafe` when necessary. Rust has a powerful
optimizing engine, and `BitSlice` will frequently be compiled to have zero
runtime cost. Where it is slower, it will not be significantly slower than a
manual replacement.
As the machine instructions operate on registers rather than bits, your choice
of [`T: BitStore`] type parameter can influence your slice’s performance. Using
larger register types means that slices can gallop over completely-filled
interior elements faster, while narrower register types permit more graceful
handling of subslicing and aliased splits.
# Construction
`BitSlice` views of memory can be constructed over borrowed data in a number of
ways. As this is a reference-only type, it can only ever be built by borrowing
an existing memory buffer and taking temporary control of your program’s view of
the region.
## Macro Constructor
`BitSlice` buffers can be constructed at compile-time through the [`bits!`]
macro. This macro accepts a superset of the [`vec!`] arguments, and creates an
appropriate buffer in the local scope. The macro expands to a borrowed
[`BitArray`] temporary; currently, it cannot be assigned to a `static` binding.
```rust
use bitvec::prelude::*;
let immut = bits![Lsb0, u8; 0, 1, 0, 0, 1, 0, 0, 1];
let mutable: &mut BitSlice<_, _> = bits![mut Msb0, u8; 0; 8];
assert_ne!(immut, mutable);
mutable.clone_from_bitslice(immut);
assert_eq!(immut, mutable);
```
## Borrowing Constructors
The functions [`from_element`], [`from_element_mut`], [`from_slice`], and
[`from_slice_mut`] take references to existing memory, and construct
`BitSlice` references over them. These are the most basic ways to borrow memory
and view it as bits.
```rust
use bitvec::prelude::*;
let data = [0u16; 3];
let local_borrow = BitSlice::<Lsb0, _>::from_slice(&data);
let mut data = [0u8; 5];
let local_mut = BitSlice::<Lsb0, _>::from_slice_mut(&mut data);
```
## Trait Method Constructors
The [`BitView`] trait implements [`.view_bits::<O>()`] and
[`.view_bits_mut::<O>()`] methods on elements, arrays not larger than 64
elements, and slices. This trait, imported in the crate prelude, is *probably*
the easiest way for you to borrow memory.
```rust
use bitvec::prelude::*;
let data = [0u32; 5];
let trait_view = data.view_bits::<Lsb0>();
let mut data = 0usize;
let trait_mut = data.view_bits_mut::<Msb0>();
```
## Owned Bit Slices
If you wish to take ownership of a memory region and enforce that it is always
viewed as a `BitSlice` by default, you can use one of the [`BitArray`],
[`BitBox`], or [`BitVec`] types, rather than pairing ordinary buffer types with
the borrowing constructors.
```rust
use bitvec::prelude::*;
let slice = bits![0; 27];
let array = bitarr![LocalBits, u8; 0; 10];
# #[cfg(feature = "alloc")] fn allocs() {
let boxed = bitbox![0; 10];
let vec = bitvec![0; 20];
# } #[cfg(feature = "alloc")] allocs();
// arrays always round up
assert_eq!(array.as_bitslice(), slice[.. 16]);
# #[cfg(feature = "alloc")] fn allocs2() {
# let slice = bits![0; 27];
# let boxed = bitbox![0; 10];
# let vec = bitvec![0; 20];
assert_eq!(boxed.as_bitslice(), slice[.. 10]);
assert_eq!(vec.as_bitslice(), slice[.. 20]);
# } #[cfg(feature = "alloc")] allocs2();
```
[TCP wire format]: https://en.wikipedia.org/wiki/Transmission_Control_Protocol#TCP_segment_structure
[minval]: https://doc.rust-lang.org/stable/std/primitive.usize.html#associatedconstant.MIN
[`BitArray`]: crate::array::BitArray
[`BitBox`]: crate::boxed::BitBox
[`BitRef<Mut, O, T>`]: crate::ptr::BitRef
[`BitOrder`]: crate::order::BitOrder
[`BitStore`]: crate::store::BitStore
[`BitVec`]: crate::vec::BitVec
[`BitView`]: crate::view::BitView
[`Cell<T>`]: core::cell::Cell
[`Lsb0`]: crate::order::Lsb0
[`Msb0`]: crate::order::Msb0
[`T: BitStore`]: crate::store::BitStore
[`Vec<T>`]: alloc::vec::Vec
[`access`]: crate::access
[`bits!`]: macro@crate::bits
[`bitvec`]: crate
[`bitvec::prelude::LocalBits`]: crate::order::LocalBits
[`from_element`]: Self::from_element
[`from_element_mut`]: Self::from_element_mut
[`from_slice`]: Self::from_slice
[`from_slice_mut`]: Self::from_slice_mut
[`mem::transmute`]: core::mem::transmute
[`std::bitset`]: https://en.cppreference.com/w/cpp/utility/bitset
[`std::vector<bool>`]: https://en.cppreference.com/w/cpp/container/vector_bool
[`vec!`]: macro@alloc::vec
[`.split_at_mut()`]: Self::split_at_mut
[`.view_bits::<O>()`]: crate::view::BitView::view_bits
[`.view_bits_mut::<O>()`]: crate::view::BitView::view_bits_mut
**/
#[repr(transparent)]
pub struct BitSlice<O = Lsb0, T = usize>
where
O: BitOrder,
T: BitStore,
{
/// The ordering of bits within a register `T`.
_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 references to this slice `&BitSlice` and
/// `&mut BitSlice`.
///
/// Rust has firm requirements that *any* reference that is directly usable
/// to dereference a real value must conform to its rules about address
/// liveness, type alignment, and for slices, trustworthy length. It is
/// undefined behavior for a slice reference *to a dereferenceable type* to
/// violate any of these restrictions.
///
/// However, the value of a reference to a zero-sized type has *no* such
/// restrictions, because that reference can never perform direct memory
/// access. The compiler will accept any value in a slot typed as `&[()]`,
/// because the values in it will never be used for a load or store
/// instruction. If this were `[T]`, then Rust would make the pointer
/// encoding used to manage values of `&BitSlice` become undefined behavior.
///
/// See the `ptr` module for information on the encoding used.
_mem: [()],
}
/// General-purpose functions not present on `[T]`.
impl<O, T> BitSlice<O, T>
where
O: BitOrder,
T: BitStore,
{
/// Constructs a shared `&BitSlice` reference over a shared element.
///
/// The [`BitView`] trait, implemented on all [`BitStore`] implementors,
/// provides a method [`.view_bits::<O>()`] 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 the `elem` element.
///
/// # Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let elem = 0u8;
/// let bits = BitSlice::<Lsb0, _>::from_element(&elem);
/// assert_eq!(bits.len(), 8);
/// ```
///
/// [`BitStore`]: crate::store::BitStore
/// [`BitView`]: crate::view::BitView
/// [`.view_bits::<O>()`]: crate::view::BitView::view_bits
#[inline]
pub fn from_element(elem: &T) -> &Self {
unsafe { BitPtr::from_ref(elem).span_unchecked(T::Mem::BITS as usize) }
.to_bitslice_ref()
}
/// Constructs an exclusive `&mut BitSlice` reference over an element.
///
/// The [`BitView`] trait, implemented on all [`BitStore`] implementors,
/// provides a method [`.view_bits_mut::<O>()`] 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 the `elem` element.
///
/// Note that the original `elem` reference will be inaccessible for the
/// duration of the returned slice handle’s lifetime.
///
/// # Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let mut elem = 0u16;
/// let bits = BitSlice::<Msb0, _>::from_element_mut(&mut elem);
/// bits.set(15, true);
/// assert!(bits.get(15).unwrap());
/// assert_eq!(elem, 1);
/// ```
///
/// [`BitStore`]: crate::store::BitStore
/// [`BitView`]: crate::view::BitView
/// [`.view_bits_mut::<O>()`]: crate::view::BitView::view_bits_mut
#[inline]
pub fn from_element_mut(elem: &mut T) -> &mut Self {
unsafe { BitPtr::from_mut(elem).span_unchecked(T::Mem::BITS as usize) }
.to_bitslice_mut()
}
/// Constructs a shared `&BitSlice` reference over a slice.
///
/// The [`BitView`] trait, implemented on all `[T]` slices, provides a
/// method [`.view_bits::<O>()`] which delegates to this function and may be
/// more convenient for you to write.
///
/// # Parameters
///
/// - `slice`: A shared reference over a sequence of memory elements.
///
/// # Returns
///
/// A `&BitSlice` view of the provided slice. The error condition is only
/// encountered if the source slice is too long to be encoded in a
/// `&BitSlice` handle, but such a slice is likely impossible to produce
/// without causing errors long before calling this function.
///
/// # Conditions
///
/// The produced `&BitSlice` handle always begins at the zeroth bit of the
/// zeroth element in `slice`.
///
/// # Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let slice = &[0u8, 1];
/// let bits = BitSlice::<Msb0, _>::from_slice(slice).unwrap();
/// assert!(bits[15]);
/// ```
///
/// An example showing this function failing would require a slice exceeding
/// `!0usize >> 3` bytes in size, which is infeasible to produce.
///
/// [`BitView`]: crate::view::BitView
/// [`MAX_ELTS`]: Self::MAX_ELTS
/// [`.view_bits::<O>()`]: crate::view::BitView::view_bits
#[inline]
pub fn from_slice(slice: &[T]) -> Result<&Self, BitSpanError<T>> {
let elts = slice.len();
// Starting at the zeroth bit makes this counter an exclusive cap, not
// an inclusive cap. This is also pretty much impossible to hit.
if elts >= Self::MAX_ELTS {
return Err(BitSpanError::TooLong(
elts.saturating_mul(T::Mem::BITS as usize),
));
}
Ok(unsafe { Self::from_slice_unchecked(slice) })
}
/// Constructs an exclusive `&mut BitSlice` reference over a slice.
///
/// The [`BitView`] trait, implemented on all `[T]` slices, provides a
/// method [`.view_bits_mut::<O>()`] which delegates to this function and
/// may be more convenient for you to write.
///
/// # Parameters
///
/// - `slice`: An exclusive reference over a sequence of memory elements.
///
/// # Returns
///
/// A `&mut BitSlice` view of the provided slice. The error condition is
/// only encountered if the source slice is too long to be encoded in a
/// `&mut BitSlice` handle, but such a slice is likely impossible to produce
/// without causing errors long before calling this function.
///
/// Note that the original `slice` reference will be inaccessible for the
/// duration of the returned slice handle’s lifetime.
///
/// # Conditions
///
/// The produced `&mut BitSlice` handle always begins at the zeroth bit of
/// the zeroth element in `slice`.
///
/// # Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let mut slice = [0u8; 2];
/// let bits = BitSlice::<Lsb0, _>::from_slice_mut(&mut slice).unwrap();
///
/// assert!(!bits[0]);
/// bits.set(0, true);
/// assert!(bits[0]);
/// assert_eq!(slice[0], 1);
/// ```
///
/// This example attempts to construct a `&mut BitSlice` handle from a slice
/// that is too large to index. Either the `vec!` allocation will fail, or
/// the bit-slice constructor will fail.
///
/// ```rust,should_panic
/// # #[cfg(feature = "alloc")] {
/// use bitvec::prelude::*;
///
/// let mut data = vec![0usize; BitSlice::<Lsb0, usize>::MAX_ELTS];
/// let bits = BitSlice::<Lsb0, _>::from_slice_mut(&mut data[..]).unwrap();
/// # }
/// # #[cfg(not(feature = "alloc"))] panic!("No allocator present");
/// ```
///
/// [`BitView`]: crate::view::BitView
/// [`MAX_ELTS`]: Self::MAX_ELTS
/// [`.view_bits_mut::<O>()`]: crate::view::BitView::view_bits_mut
#[inline]
pub fn from_slice_mut(
slice: &mut [T],
) -> Result<&mut Self, BitSpanError<T>> {
let elts = slice.len();
if elts >= Self::MAX_ELTS {
return Err(BitSpanError::TooLong(
elts.saturating_mul(T::Mem::BITS as usize),
));
}
Ok(unsafe { Self::from_slice_unchecked_mut(slice) })
}
/// Converts a slice reference into a `BitSlice` reference without checking
/// that its size can be safely used.
///
/// # Safety
///
/// If the `slice` length is longer than [`MAX_ELTS`], then the returned
/// `BitSlice` will have its length severely truncated. This is not a safety
/// violation, but it is behavior that callers must avoid to remain correct.
///
/// Prefer [`::from_slice()`].
///
/// [`MAX_ELTS`]: Self::MAX_ELTS
/// [`::from_slice()`]: Self::from_slice
#[inline]
pub unsafe fn from_slice_unchecked(slice: &[T]) -> &Self {
let bits = slice.len().wrapping_mul(T::Mem::BITS as usize);
BitPtr::from_slice(slice)
.span_unchecked(bits)
.to_bitslice_ref()
}
/// Converts a slice reference into a `BitSlice` reference without checking
/// that its size can be safely used.
///
/// # Safety
///
/// If the `slice` length is longer than [`MAX_ELTS`], then the returned
/// `BitSlice` will have its length severely truncated. This is not a safety
/// violation, but it is behavior that callers must avoid to remain correct.
///
/// Prefer [`::from_slice_mut()`].
///
/// [`MAX_ELTS`]: Self::MAX_ELTS
/// [`::from_slice_mut()`]: Self::from_slice_mut
#[inline]
pub unsafe fn from_slice_unchecked_mut(slice: &mut [T]) -> &mut Self {
let bits = slice.len().wrapping_mul(T::Mem::BITS as usize);
BitPtr::from_mut_slice(slice)
.span_unchecked(bits)
.to_bitslice_mut()
}
/// Produces the empty slice reference.
///
/// This is equivalent to `&[]` for ordinary slices.
///
/// # Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let bits: &BitSlice = BitSlice::empty();
/// assert!(bits.is_empty());
/// ```
#[inline(always)]
pub fn empty<'a>() -> &'a Self {
BitSpan::<Const, O, T>::EMPTY.to_bitslice_ref()
}
/// Produces the empty mutable slice reference.
///
/// This is equivalent to `&mut []` for ordinary slices.
///
/// # Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let bits: &mut BitSlice = BitSlice::empty_mut();
/// assert!(bits.is_empty());
/// ```
#[inline(always)]
pub fn empty_mut<'a>() -> &'a mut Self {
BitSpan::EMPTY.to_bitslice_mut()
}
/// Writes a new bit at a given index.
///
/// # Parameters
///
/// - `&mut self`
/// - `index`: The bit index at which to write. It must be in the range `0
/// .. self.len()`.
/// - `value`: The value to be written; `true` for `1` or `false` for `0`.
///
/// # Effects
///
/// If `index` is valid, then the bit to which it refers is set to `value`.
///
/// # Panics
///
/// This method panics if `index` is not less than [`self.len()`].
///
/// # Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let bits = bits![mut 0];
///
/// assert!(!bits[0]);
/// bits.set(0, true);
/// assert!(bits[0]);
/// ```
///
/// This example panics when it attempts to set a bit that is out of bounds.
///
/// ```rust,should_panic
/// use bitvec::prelude::*;
///
/// let bits = bits![mut 0];
/// bits.set(1, false);
/// ```
///
/// [`self.len()`]: Self::len
#[inline]
pub fn set(&mut self, index: usize, value: bool) {
self.assert_in_bounds(index, 0 .. self.len());
unsafe {
self.set_unchecked(index, value);
}
}
/// Tests if *any* bit in the slice is set (logical `∨`).
///
/// # Truth Table
///
/// ```text
/// 0 0 => 0
/// 0 1 => 1
/// 1 0 => 1
/// 1 1 => 1
/// ```
///
/// # Parameters
///
/// - `&self`
///
/// # Returns
///
/// Whether any bit in the slice domain is set. The empty slice returns
/// `false`.
///
/// # Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let bits = bits![0, 1, 0, 0];
/// assert!(bits[.. 2].any());
/// assert!(!bits[2 ..].any());
/// ```
#[inline]
pub fn any(&self) -> bool {
match self.domain() {
Domain::Enclave { head, elem, tail } => {
O::mask(head, tail) & elem.load_value() != BitMask::ZERO
},
Domain::Region { head, body, tail } => {
head.map_or(false, |(head, elem)| {
O::mask(head, None) & elem.load_value() != BitMask::ZERO
}) || body
.iter()
.any(|e| e.load_value() != <T::Mem as IsInteger>::ZERO)
|| tail.map_or(false, |(elem, tail)| {
O::mask(None, tail) & elem.load_value() != BitMask::ZERO
})
},
}
}
/// Tests if *all* bits in the slice domain are set (logical `∧`).
///
/// # Truth Table
///
/// ```text
/// 0 0 => 0
/// 0 1 => 0
/// 1 0 => 0
/// 1 1 => 1
/// ```
///
/// # Parameters
///
/// - `&self`
///
/// # Returns
///
/// Whether all bits in the slice domain are set. The empty slice returns
/// `true`.
///
/// # Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let bits = bits![1, 1, 0, 1];
/// assert!(bits[.. 2].all());
/// assert!(!bits[2 ..].all());
/// ```
#[inline]
pub fn all(&self) -> bool {
match self.domain() {
Domain::Enclave { head, elem, tail } => {
/* Due to a bug in `rustc`, calling `.value()` on the two
`BitMask` types, to use `T::Mem | T::Mem == T::Mem`, causes type
resolution failure and only discovers the
`for<'a> BitOr<&'a Self>` implementation in the trait bounds
`T::Mem: BitMemory: IsUnsigned: BitOr<Self> + for<'a> BitOr<&'a Self>`.
Until this is fixed, routing through the `BitMask`
implementation suffices. The by-val and by-ref operator traits
are at the same position in the bounds chain, making this quite
a strange bug.
*/
!O::mask(head, tail) | elem.load_value() == BitMask::ALL
},
Domain::Region { head, body, tail } => {
head.map_or(true, |(head, elem)| {
!O::mask(head, None) | elem.load_value() == BitMask::ALL
}) && body
.iter()
.map(BitStore::load_value)
.all(|e| e == T::Mem::ALL)
&& tail.map_or(true, |(elem, tail)| {
!O::mask(None, tail) | elem.load_value() == BitMask::ALL
})
},
}
}
/// Tests if *all* bits in the slice are unset (logical `¬∨`).
///
/// # Truth Table
///
/// ```text
/// 0 0 => 1
/// 0 1 => 0
/// 1 0 => 0
/// 1 1 => 0
/// ```
///
/// # Parameters
///
/// - `&self`
///
/// # Returns
///
/// Whether all bits in the slice domain are unset.
///
/// # Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let bits = bits![0, 1, 0, 0];
/// assert!(!bits[.. 2].not_any());
/// assert!(bits[2 ..].not_any());
/// ```
#[inline(always)]
pub fn not_any(&self) -> bool {
!self.any()
}
/// Tests if *any* bit in the slice is unset (logical `¬∧`).
///
/// # Truth Table
///
/// ```text
/// 0 0 => 1
/// 0 1 => 1
/// 1 0 => 1
/// 1 1 => 0
/// ```
///
/// # Parameters
///
/// - `&self`
///
/// # Returns
///
/// Whether any bit in the slice domain is unset.
///
/// # Examples
///
/// ```rust
/// use bitvec::prelude::*;
///
/// let bits = bits![1, 1, 0, 1];
/// assert!(!bits[.. 2].not_all());
/// assert!(bits[2 ..].not_all());
/// ```
#[inline(always)]
pub fn not_all(&self) -> bool {
!self.all()
}
/// Tests whether the slice has some, but not all, bits set and some, but
/// not all, bits unset.
///
/// This is `false` if either [`.all()`] or [`.not_any()`] are `true`.
///
/// # Truth Table
///
/// ```text
/// 0 0 => 0
/// 0 1 => 1
/// 1 0 => 1
/// 1 1 => 0
/// ```
///
/// # Parameters
///
/// - `&self`