| 1 |
# Raw Bit-Slice Construction |
| 2 |
|
| 3 |
This produces an `&BitSlice<T, O>` reference handle from a `BitPtr<Const, T, O>` |
| 4 |
bit-pointer and a length. |
| 5 |
|
| 6 |
## Parameters |
| 7 |
|
| 8 |
1. `data`: a bit-pointer to the starting bit of the produced bit-slice. This |
| 9 |
should generally have been produced by `BitSlice::as_ptr`, but you are able |
| 10 |
to construct these pointers directly if you wish. |
| 11 |
1. `len`: the number of bits, beginning at `data`, that the produced bit-slice |
| 12 |
includes. This value cannot depart an allocation area, or exceed `BitSlice`’s |
| 13 |
encoding limitations. |
| 14 |
|
| 15 |
## Returns |
| 16 |
|
| 17 |
This returns a `Result`, because it can detect and gracefully fail if `len` |
| 18 |
is too large, or if `data` is ill-formed. This fails if it has an error while |
| 19 |
encoding the `&BitSlice`, and succeeds if it is able to produce a correctly |
| 20 |
encoded value. |
| 21 |
|
| 22 |
Note that this is not able to detect semantic violations of the memory model. |
| 23 |
You are responsible for upholding memory safety. |
| 24 |
|
| 25 |
## Original |
| 26 |
|
| 27 |
[`slice::from_raw_parts`](core::slice::from_raw_parts) |
| 28 |
|
| 29 |
## API Differences |
| 30 |
|
| 31 |
This takes a [`BitPtr<Const, T, O>`] instead of a hypothetical `*const Bit`, |
| 32 |
because `bitvec` is not able to express raw Rust pointers to individual bits. |
| 33 |
|
| 34 |
Additionally, it returns a `Result` rather than a direct bit-slice, because the |
| 35 |
given `len` argument may be invalid to encode into a `&BitSlice` reference. |
| 36 |
|
| 37 |
## Safety |
| 38 |
|
| 39 |
This has the same memory safety requirements as the standard-library function: |
| 40 |
|
| 41 |
- `data` must be valid for reads and writes of at least `len` bits, |
| 42 |
- The bits that the produced bit-slice refers to must be wholly unreachable by |
| 43 |
any other part of the program for the duration of the lifetime `'a`, |
| 44 |
|
| 45 |
and additionally imposes some of its own: |
| 46 |
|
| 47 |
- `len` cannot exceed [`BitSlice::MAX_BITS`]. |
| 48 |
|
| 49 |
## Examples |
| 50 |
|
| 51 |
```rust |
| 52 |
use bitvec::{ |
| 53 |
prelude::*, |
| 54 |
index::BitIdx, |
| 55 |
ptr::Const, |
| 56 |
slice as bv_slice, |
| 57 |
}; |
| 58 |
|
| 59 |
let elem = 6u16; |
| 60 |
let addr = (&elem).into(); |
| 61 |
let head = BitIdx::new(1).unwrap(); |
| 62 |
|
| 63 |
let data: BitPtr<Const, u16> = BitPtr::new(addr, head).unwrap(); |
| 64 |
let bits = unsafe { bv_slice::from_raw_parts(data, 3) }; |
| 65 |
assert_eq!(bits.unwrap(), bits![1, 1, 0]); |
| 66 |
``` |
| 67 |
|
| 68 |
[`BitSlice::MAX_BITS`]: crate::slice::BitSlice::MAX_BITS |