Debian Codegraph @

debian/rust-vendor/bitvec/doc/slice/BitSlice.md

raw
1 # Bit-Addressable Memory
2
3 A slice of individual bits, anywhere in memory.
4
5 `BitSlice<T, O>` is an unsized region type; you interact with it through
6 `&BitSlice<T, O>` and `&mut BitSlice<T, O>` references, which work exactly like
7 all other Rust references. As with the standard slice’s relationship to arrays
8 and vectors, this is `bitvec`’s primary working type, but you will probably
9 hold it through one of the provided [`BitArray`], [`BitBox`], or [`BitVec`]
10 containers.
11
12 `BitSlice` is conceptually a `[bool]` slice, and provides a nearly complete
13 mirror of `[bool]`’s API.
14
15 Every bit-vector crate can give you an opaque type that hides shift/mask
16 calculations from you. `BitSlice` does far more than this: it offers you the
17 full Rust guarantees about reference behavior, including lifetime tracking,
18 mutability and aliasing awareness, and explicit memory control, *as well as* the
19 full set of tools and APIs available to the standard `[bool]` slice type.
20 `BitSlice` can arbitrarily split and subslice, just like `[bool]`. You can write
21 a linear consuming function and keep the patterns you already know.
22
23 For example, to trim all the bits off either edge that match a condition, you
24 could write
25
26 ```rust
27 use bitvec::prelude::*;
28
29 fn trim<T: BitStore, O: BitOrder>(
30 bits: &BitSlice<T, O>,
31 to_trim: bool,
32 ) -> &BitSlice<T, O> {
33 let stop = |b: bool| b != to_trim;
34 let front = bits.iter()
35 .by_vals()
36 .position(stop)
37 .unwrap_or(0);
38 let back = bits.iter()
39 .by_vals()
40 .rposition(stop)
41 .map_or(0, |p| p + 1);
42 &bits[front .. back]
43 }
44 # assert_eq!(trim(bits![0, 0, 1, 1, 0, 1, 0], false), bits![1, 1, 0, 1]);
45 ```
46
47 to get behavior something like
48 `trim(&BitSlice[0, 0, 1, 1, 0, 1, 0], false) == &BitSlice[1, 1, 0, 1]`.
49
50 ## Documentation
51
52 All APIs that mirror something in the standard library will have an `Original`
53 section linking to the corresponding item. All APIs that have a different
54 signature or behavior than the original will have an `API Differences` section
55 explaining what has changed, and how to adapt your existing code to the change.
56
57 These sections look like this:
58
59 ## Original
60
61 [`[bool]`](https://doc.rust-lang.org/stable/std/primitive.slice.html)
62
63 ## API Differences
64
65 The slice type `[bool]` has no type parameters. `BitSlice<T, O>` has two: one
66 for the integer type used as backing storage, and one for the order of bits
67 within that integer type.
68
69 `&BitSlice<T, O>` is capable of producing `&bool` references to read bits out
70 of its memory, but is not capable of producing `&mut bool` references to write
71 bits *into* its memory. Any `[bool]` API that would produce a `&mut bool` will
72 instead produce a [`BitRef<Mut, T, O>`] proxy reference.
73
74 ## Behavior
75
76 `BitSlice` is a wrapper over `[T]`. It describes a region of memory, and must be
77 handled indirectly. This is most commonly done through the reference types
78 `&BitSlice` and `&mut BitSlice`, which borrow memory owned by some other value
79 in the program. These buffers can be directly owned by the sibling types
80 [`BitBox`], which behaves like [`Box<[T]>`](alloc::boxed::Box), and [`BitVec`],
81 which behaves like [`Vec<T>`]. It cannot be used as the type parameter to a
82 pointer type such as `Box`, `Rc`, `Arc`, or any other indirection.
83
84 The `BitSlice` region provides access to each individual bit in the region, as
85 if each bit had a memory address that you could use to dereference it. It packs
86 each logical bit into exactly one bit of storage memory, just like
87 [`std::bitset`] and [`std::vector<bool>`] in C++.
88
89 ## Type Parameters
90
91 `BitSlice` has two type parameters which propagate through nearly every public
92 API in the crate. These are very important to its operation, and your choice
93 of type arguments informs nearly every part of this library’s behavior.
94
95 ### `T: BitStore`
96
97 [`BitStore`] is the simpler of the two parameters. It refers to the integer type
98 used to hold bits. It must be one of the Rust unsigned integer fundamentals:
99 `u8`, `u16`, `u32`, `usize`, and on 64-bit systems only, `u64`. In addition, it
100 can also be an alias-safe wrapper over them (see the [`access`] module) in
101 order to permit bit-slices to share underlying memory without interfering with
102 each other.
103
104 `BitSlice` references can only be constructed over the integers, not over their
105 aliasing wrappers. `BitSlice` will only use aliasing types in its `T` slots when
106 you invoke APIs that produce them, such as [`.split_at_mut()`].
107
108 The default type argument is `usize`.
109
110 The argument you choose is used as the basis of a `[T]` slice, over which the
111 `BitSlice` view is produced. `BitSlice<T, _>` is subject to all of the rules
112 about alignment that `[T]` is. If you are working with in-memory representation
113 formats, chances are that you already have a `T` type with which you’ve been
114 working, and should use it here.
115
116 If you are only using this crate to discard the seven wasted bits per `bool`
117 in a collection of `bool`s, and are not too concerned about the in-memory
118 representation, then you should use the default type argument of `usize`. This
119 is because most processors work best when moving an entire `usize` between
120 memory and the processor itself, and using a smaller type may cause it to slow
121 down. Additionally, processor instructions are typically optimized for the whole
122 register, and the processor might need to do additional clearing work for
123 narrower types.
124
125 ### `O: BitOrder`
126
127 [`BitOrder`] is the more complex parameter. It has a default argument which,
128 like `usize`, is a good baseline choice when you do not explicitly need to
129 control the representation of bits in memory.
130
131 This parameter determines how `bitvec` indexes the bits within a single `T`
132 memory element. Computers all agree that in a slice of `T` elements, the element
133 with the lower index has a lower memory address than the element with the higher
134 index. But the individual bits within an element do not have addresses, and so
135 there is no uniform standard of which bit is the zeroth, which is the first,
136 which is the penultimate, and which is the last.
137
138 To make matters even more confusing, there are two predominant ideas of
139 in-element ordering that often *correlate* with the in-element *byte* ordering
140 of integer types, but are in fact wholly unrelated! `bitvec` provides these two
141 main orderings as types for you, and if you need a different one, it also
142 provides the tools you need to write your own.
143
144 #### Least Significant Bit Comes First
145
146 This ordering, named the [`Lsb0`] type, indexes bits within an element by
147 placing the `0` index at the least significant bit (numeric value `1`) and the
148 final index at the most significant bit (numeric value [`T::MIN`][minval] for
149 signed integers on most machines).
150
151 For example, this is the ordering used by most C compilers to lay out bit-field
152 struct members on little-endian **byte**-ordered machines.
153
154 #### Most Significant Bit Comes First
155
156 This ordering, named the [`Msb0`] type, indexes bits within an element by
157 placing the `0` index at the most significant bit (numeric value
158 [`T::MIN`][minval] for most signed integers) and the final index at the least
159 significant bit (numeric value `1`).
160
161 For example, this is the ordering used by the [TCP wire format][tcp], and by
162 most C compilers to lay out bit-field struct members on big-endian
163 **byte**-ordered machines.
164
165 #### Default Ordering
166
167 The default ordering is [`Lsb0`], as it typically produces shorter object code
168 than [`Msb0`] does. If you are implementing a collection, then `Lsb0` will
169 likely give you better performance; if you are implementing a buffer protocol,
170 then your choice of ordering is dictated by the protocol definition.
171
172 ## Safety
173
174 `BitSlice` is designed to never introduce new memory unsafety that you did not
175 provide yourself, either before or during the use of this crate. However, safety
176 bugs have been identified before, and you are welcome to submit any discovered
177 flaws as a defect report.
178
179 The `&BitSlice` reference type uses a private encoding scheme to hold all of the
180 information needed in its stack value. This encoding is **not** part of the
181 public API of the library, and is not binary-compatible with `&[T]`.
182 Furthermore, in order to satisfy Rust’s requirements about alias conditions,
183 `BitSlice` performs type transformations on the `T` parameter to ensure that it
184 never creates the potential for undefined behavior or data races.
185
186 You must never attempt to type-cast a reference to `BitSlice` in any way. You
187 must not use [`mem::transmute`] with `BitSlice` anywhere in its type arguments.
188 You must not use `as`-casting to convert between `*BitSlice` and any other type.
189 You must not attempt to modify the binary representation of a `&BitSlice`
190 reference value. These actions will all lead to runtime memory unsafety, are
191 (hopefully) likely to induce a program crash, and may possibly cause undefined
192 behavior at compile-time.
193
194 Everything in the `BitSlice` public API, even the `unsafe` parts, are guaranteed
195 to have no more unsafety than their equivalent items in the standard library.
196 All `unsafe` APIs will have documentation explicitly detailing what the API
197 requires you to uphold in order for it to function safely and correctly. All
198 safe APIs will do so themselves.
199
200 ## Performance
201
202 Like the standard library’s `[T]` slice, `BitSlice` is designed to be very easy
203 to use safely, while supporting `unsafe` usage when necessary. Rust has a
204 powerful optimizing engine, and `BitSlice` will frequently be compiled to have
205 zero runtime cost. Where it is slower, it will not be significantly slower than
206 a manual replacement.
207
208 As the machine instructions operate on registers rather than bits, your choice
209 of [`T: BitStore`] type parameter can influence your bits-slice’s performance.
210 Using larger register types means that bit-slices can gallop over
211 completely-used interior elements faster, while narrower register types permit
212 more graceful handling of subslicing and aliased splits.
213
214 ## Construction
215
216 `BitSlice` views of memory can be constructed over borrowed data in a number of
217 ways. As this is a reference-only type, it can only ever be built by borrowing
218 an existing memory buffer and taking temporary control of your program’s view of
219 the region.
220
221 ### Macro Constructor
222
223 `BitSlice` buffers can be constructed at compile-time through the [`bits!`]
224 macro. This macro accepts a superset of the [`vec!`] arguments, and creates an
225 appropriate buffer in the local scope. The macro expands to a borrowed
226 [`BitArray`] temporary, which will live for the duration of the bound name.
227
228 ```rust
229 use bitvec::prelude::*;
230
231 let immut = bits![u8, Lsb0; 0, 1, 0, 0, 1, 0, 0, 1];
232 let mutable: &mut BitSlice<_, _> = bits![mut u8, Msb0; 0; 8];
233
234 assert_ne!(immut, mutable);
235 mutable.clone_from_bitslice(immut);
236 assert_eq!(immut, mutable);
237 ```
238
239 ### Borrowing Constructors
240
241 You may borrow existing elements or slices with the following functions:
242
243 - [`from_element`] and [`from_element_mut`],
244 - [`from_slice`] and [`from_slice_mut`],
245 - [`try_from_slice`] and [`try_from_slice_mut`]
246
247 These take references to existing memory and construct `BitSlice` references
248 from them. These are the most basic ways to borrow memory and view it as bits;
249 however, you should prefer the [`BitView`] trait methods instead.
250
251 ```rust
252 use bitvec::prelude::*;
253
254 let data = [0u16; 3];
255 let local_borrow = BitSlice::<_, Lsb0>::from_slice(&data);
256
257 let mut data = [0u8; 5];
258 let local_mut = BitSlice::<_, Lsb0>::from_slice_mut(&mut data);
259 ```
260
261 ### Trait Method Constructors
262
263 The [`BitView`] trait implements [`.view_bits::<O>()`] and
264 [`.view_bits_mut::<O>()`] methods on elements, arrays, and slices. This trait,
265 imported in the crate prelude, is *probably* the easiest way for you to borrow
266 memory as bits.
267
268 ```rust
269 use bitvec::prelude::*;
270
271 let data = [0u32; 5];
272 let trait_view = data.view_bits::<Lsb0>();
273
274 let mut data = 0usize;
275 let trait_mut = data.view_bits_mut::<Msb0>();
276 ```
277
278 ### Owned Bit Slices
279
280 If you wish to take ownership of a memory region and enforce that it is always
281 viewed as a `BitSlice` by default, you can use one of the [`BitArray`],
282 [`BitBox`], or [`BitVec`] types, rather than pairing ordinary buffer types with
283 the borrowing constructors.
284
285 ```rust
286 use bitvec::prelude::*;
287
288 let slice = bits![0; 27];
289 let array = bitarr![u8, LocalBits; 0; 10];
290 # #[cfg(feature = "alloc")] fn allocates() {
291 let boxed = bitbox![0; 10];
292 let vec = bitvec![0; 20];
293 # } #[cfg(feature = "alloc")] allocates();
294
295 // arrays always round up
296 assert_eq!(array.as_bitslice(), slice[.. 16]);
297 # #[cfg(feature = "alloc")] fn allocates2() {
298 # let slice = bits![0; 27];
299 # let boxed = bitbox![0; 10];
300 # let vec = bitvec![0; 20];
301 assert_eq!(boxed.as_bitslice(), slice[.. 10]);
302 assert_eq!(vec.as_bitslice(), slice[.. 20]);
303 # } #[cfg(feature = "alloc")] allocates2();
304 ```
305
306 ## Usage
307
308 `BitSlice` implements the full standard-library `[bool]` API. The documentation
309 for these API surfaces is intentionally sparse, and forwards to the standard
310 library rather than try to replicate it.
311
312 `BitSlice` also has a great deal of novel API surfaces. These are broken into
313 separate `impl` blocks below. A short summary:
314
315 - Since there is no `BitSlice` literal, the constructor functions `::empty()`,
316 `::from_element()`, `::from_slice()`, and `::try_from_slice()`, and their
317 `_mut` counterparts, create bit-slices as needed.
318 - Since `bits[idx] = value` does not exist, you can use `.set()` or `.replace()`
319 (as well as their `_unchecked` and `_aliased` counterparts) to write into a
320 bit-slice.
321 - Raw memory can be inspected with `.domain()` and `.domain_mut()`, and a
322 bit-slice can be split on aliasing lines with `.bit_domain()` and
323 `.bit_domain_mut()`.
324 - The population can be queried for which indices have `0` or `1` bits by
325 iterating across all such indices, counting them, or counting leading or
326 trailing blocks. Additionally, `.any()`, `.all()`, `.not_any()`, `.not_all()`,
327 and `.some()` test whether bit-slices satisfy aggregate Boolean qualities.
328 - Buffer contents can be relocated internally by shifting or rotating to the
329 left or right.
330
331 ## Trait Implementations
332
333 `BitSlice` adds trait implementations that `[bool]` and `[T]` do not necessarily
334 have, including numeric formatting and Boolean arithmetic operators.
335 Additionally, the [`BitField`] trait allows bit-slices to act as a buffer for
336 wide-value storage.
337
338 [minval]: https://doc.rust-lang.org/stable/std/primitive.usize.html#associatedconstant.MIN
339 [tcp]: https://en.wikipedia.org/wiki/Transmission_Control_Protocol#TCP_segment_structure
340
341 [`BitArray`]: crate::array::BitArray
342 [`BitBox`]: crate::boxed::BitBox
343 [`BitField`]: crate::field::BitField
344 [`BitRef<Mut, T, O>`]: crate::ptr::BitRef
345 [`BitOrder`]: crate::order::BitOrder
346 [`BitStore`]: crate::store::BitStore
347 [`BitVec`]: crate::vec::BitVec
348 [`BitView`]: crate::view::BitView
349 [`Cell<T>`]: core::cell::Cell
350 [`Lsb0`]: crate::order::Lsb0
351 [`Msb0`]: crate::order::Msb0
352 [`T: BitStore`]: crate::store::BitStore
353 [`Vec<T>`]: alloc::vec::Vec
354
355 [`access`]: crate::access
356 [`bits!`]: macro@crate::bits
357 [`bitvec::prelude::LocalBits`]: crate::order::LocalBits
358 [`from_element`]: Self::from_element
359 [`from_element_mut`]: Self::from_element_mut
360 [`from_slice`]: Self::from_slice
361 [`from_slice_mut`]: Self::from_slice_mut
362 [`mem::transmute`]: core::mem::transmute
363 [`std::bitset`]: https://en.cppreference.com/w/cpp/utility/bitset
364 [`std::vector<bool>`]: https://en.cppreference.com/w/cpp/container/vector_bool
365 [`try_from_slice`]: Self::try_from_slice
366 [`try_from_slice_mut`]: Self::try_from_slice_mut
367 [`vec!`]: macro@alloc::vec
368
369 [`.split_at_mut()`]: Self::split_at_mut
370 [`.view_bits::<O>()`]: crate::view::BitView::view_bits
371 [`.view_bits_mut::<O>()`]: crate::view::BitView::view_bits_mut