| 1 |
<div style="text-align: center;" align="center"> |
| 2 |
|
| 3 |
# `bitvec` |
| 4 |
|
| 5 |
## A Magnifying Glass for Memory <!-- omit in toc --> |
| 6 |
|
| 7 |
[![Crate][crate_img]][crate_link] |
| 8 |
[![MSRV][msrv_img]][crate_link] |
| 9 |
[![License][license_img]][license_file] |
| 10 |
|
| 11 |
[![Documentation][docs_img]][docs_link] |
| 12 |
[![Crate Downloads][downloads_img]][crate_link] |
| 13 |
|
| 14 |
</div> |
| 15 |
|
| 16 |
1. [Summary](#summary) |
| 17 |
1. [Introduction](#introduction) |
| 18 |
1. [Highlights](#highlights) |
| 19 |
1. [Usage](#usage) |
| 20 |
1. [Examples](#examples) |
| 21 |
1. [User Stories](#user-stories) |
| 22 |
1. [Bit Collections](#bit-collections) |
| 23 |
1. [Bit-Field Memory Access](#bit-field-memory-access) |
| 24 |
1. [Transport Protocols](#transport-protocols) |
| 25 |
1. [Feature Flags](#feature-flags) |
| 26 |
1. [Deeper Reading](#deeper-reading) |
| 27 |
|
| 28 |
## Summary |
| 29 |
|
| 30 |
`bitvec` provides a foundational API for bitfields in Rust. It specializes |
| 31 |
standard-library data structures (slices, arrays, and vectors of `bool`) to use |
| 32 |
one-bit-per-`bool` storage, similar to [`std::bitset<N>`] and |
| 33 |
[`std::vector<bool>`] in C++. |
| 34 |
|
| 35 |
Additionally, it allows a memory region to be divided into arbitrary regions of |
| 36 |
integer storage, like [binaries][erl_bit] in Erlang. |
| 37 |
|
| 38 |
If you need to view memory as bit-addressed instead of byte-addressed, then |
| 39 |
`bitvec` is the most capable, complete, and Rust-idiomatic crate for you. |
| 40 |
|
| 41 |
## Introduction |
| 42 |
|
| 43 |
Computers do not operate on bits. The memory bus is byte-addressed, and |
| 44 |
processors operate on register words, which are typically four to eight bytes, |
| 45 |
or even wider. This means that when programmers wish to operate on individual |
| 46 |
bits within a byte of memory or a word of register, they have to do so manually, |
| 47 |
using shift and mask operations that are likely familiar to anyone who has done |
| 48 |
this before. |
| 49 |
|
| 50 |
`bitvec` brings the capabilities of C++’s compact `bool` storage and Erlang’s |
| 51 |
decomposable bit-streams to Rust, in a package that fits in with your existing |
| 52 |
Rust idioms and in the most capable, performant, implementation possible. The |
| 53 |
bit-stream behavior provides the logic necessary for C-style structural |
| 54 |
bitfields, and syntax sugar for it can be found in [`deku`]. |
| 55 |
|
| 56 |
`bitvec` enables you to write code for bit-addressed memory that is simple, |
| 57 |
easy, and fast. It compiles to the same, or even better, object code than you |
| 58 |
would get from writing shift/mask instructions manually. It leverages Rust’s |
| 59 |
powerful reference and type systems to create a system that seamlessly bridges |
| 60 |
single-bit addressing, precise control of in-memory layout, and Rust-native |
| 61 |
ownership and borrowing mechanisms. |
| 62 |
|
| 63 |
## Highlights |
| 64 |
|
| 65 |
`bitvec` has a number of unique capabilities related to its place as a Rust |
| 66 |
library and as a bit-addressing system. |
| 67 |
|
| 68 |
- It supports arbitrary bit-addressing, and its bit slices can be munched from |
| 69 |
the front. |
| 70 |
- `BitSlice` is a region type equivalent to `[bool]`, and can be described by |
| 71 |
Rust references and thus fit into reference-based APIs. |
| 72 |
- Type parameters enable users to select the precise memory representation they |
| 73 |
desire. |
| 74 |
- A memory model accounts for element-level aliasing and is safe for concurrent |
| 75 |
use. In particular, the “Beware Bitfields” bug described in |
| 76 |
[this Mozilla report][moz] is simply impossible to produce. |
| 77 |
- Native support for atomic integers as bit-field storage. |
| 78 |
- Users can supply their own translation layer for memory representation if the |
| 79 |
built-in translations are insufficient. |
| 80 |
|
| 81 |
However, it does also have some small costs associated with its capabilities: |
| 82 |
|
| 83 |
- `BitSlice` cannot be used as a referent type in pointers, such as `Box`, `Rc`, |
| 84 |
or `Arc`. |
| 85 |
- `BitSlice` cannot implement `IndexMut`, so `bitslice[index] = true;` does not |
| 86 |
work. |
| 87 |
|
| 88 |
## Usage |
| 89 |
|
| 90 |
`bitvec` strives to follow the sequence APIs in the standard library. However, |
| 91 |
as most of its functionality is a reïmplementation that does not require the |
| 92 |
standard library to actually have the symbols present, doing so may not require |
| 93 |
an MSRV raise. |
| 94 |
|
| 95 |
Now that `bitvec` is at 1.0, it will only raise MSRV in minor-edition releases. |
| 96 |
If you have a pinned Rust toolchain, you should depend on `bitvec` with a |
| 97 |
limiting minor-version constraint like `"~1.0"`. |
| 98 |
|
| 99 |
First, depend on it in your Cargo manifest: |
| 100 |
|
| 101 |
```toml |
| 102 |
[dependencies] |
| 103 |
bitvec = "1" |
| 104 |
``` |
| 105 |
|
| 106 |
> Note: `bitvec` supports `#![no_std]` targets. If you do not have `std`, |
| 107 |
> disable the default features, and explicitly restore any features that you do |
| 108 |
> have: |
| 109 |
> |
| 110 |
> ```toml |
| 111 |
> [dependencies.bitvec] |
| 112 |
> version = "1" |
| 113 |
> default-features = false |
| 114 |
> features = ["atomic", "alloc"] |
| 115 |
> ``` |
| 116 |
|
| 117 |
Once Cargo knows about it, bring its prelude into scope: |
| 118 |
|
| 119 |
```rust |
| 120 |
use bitvec::prelude::*; |
| 121 |
``` |
| 122 |
|
| 123 |
You can read the [prelude reëxports][prelude] to see exactly which symbols are |
| 124 |
being imported. The prelude brings in many symbols, and while name collisions |
| 125 |
are not likely, you may wish to instead import the prelude *module* rather than |
| 126 |
its contents: |
| 127 |
|
| 128 |
```rust |
| 129 |
use bitvec::prelude as bv; |
| 130 |
``` |
| 131 |
|
| 132 |
You should almost certainly use type aliases to make names for specific |
| 133 |
instantiations of `bitvec` type parameters, and use that rather than attempting |
| 134 |
to remain generic over an `<T: BitStore, O: BitOrder>` pair throughout your |
| 135 |
project. |
| 136 |
|
| 137 |
## Examples |
| 138 |
|
| 139 |
```rust |
| 140 |
use bitvec::prelude::*; |
| 141 |
|
| 142 |
// All data-types have macro |
| 143 |
// constructors. |
| 144 |
let arr = bitarr![u32, Lsb0; 0; 80]; |
| 145 |
let bits = bits![u16, Msb0; 0; 40]; |
| 146 |
|
| 147 |
// Unsigned integers (scalar, array, |
| 148 |
// and slice) can be borrowed. |
| 149 |
let data = 0x2021u16; |
| 150 |
let bits = data.view_bits::<Msb0>(); |
| 151 |
let data = [0xA5u8, 0x3C]; |
| 152 |
let bits = data.view_bits::<Lsb0>(); |
| 153 |
|
| 154 |
// Bit-slices can split anywhere. |
| 155 |
let (head, rest) = bits.split_at(4); |
| 156 |
assert_eq!(head, bits[.. 4]); |
| 157 |
assert_eq!(rest, bits[4 ..]); |
| 158 |
|
| 159 |
// And they are writable! |
| 160 |
let mut data = [0u8; 2]; |
| 161 |
let bits = data.view_bits_mut::<Lsb0>(); |
| 162 |
// l and r each own one byte. |
| 163 |
let (l, r) = bits.split_at_mut(8); |
| 164 |
|
| 165 |
// but now a, b, c, and d own a nibble! |
| 166 |
let ((a, b), (c, d)) = ( |
| 167 |
l.split_at_mut(4), |
| 168 |
r.split_at_mut(4), |
| 169 |
); |
| 170 |
|
| 171 |
// and all four of them are writable. |
| 172 |
a.set(0, true); |
| 173 |
b.set(1, true); |
| 174 |
c.set(2, true); |
| 175 |
d.set(3, true); |
| 176 |
|
| 177 |
assert!(bits[0]); // a[0] |
| 178 |
assert!(bits[5]); // b[1] |
| 179 |
assert!(bits[10]); // c[2] |
| 180 |
assert!(bits[15]); // d[3] |
| 181 |
|
| 182 |
// `BitSlice` is accessed by reference, |
| 183 |
// which means it respects NLL styles. |
| 184 |
assert_eq!(data, [0x21u8, 0x84]); |
| 185 |
|
| 186 |
// Furthermore, bit-slices can store |
| 187 |
// ordinary integers: |
| 188 |
let eight = [0u8, 4, 8, 12, 16, 20, 24, 28]; |
| 189 |
// a b c d e f g h |
| 190 |
let mut five = [0u8; 5]; |
| 191 |
for (slot, byte) in five |
| 192 |
.view_bits_mut::<Msb0>() |
| 193 |
.chunks_mut(5) |
| 194 |
.zip(eight.iter().copied()) |
| 195 |
{ |
| 196 |
slot.store_be(byte); |
| 197 |
assert_eq!(slot.load_be::<u8>(), byte); |
| 198 |
} |
| 199 |
|
| 200 |
assert_eq!(five, [ |
| 201 |
0b00000_001, |
| 202 |
// aaaaa bbb |
| 203 |
0b00_01000_0, |
| 204 |
// bb ccccc d |
| 205 |
0b1100_1000, |
| 206 |
// dddd eeee |
| 207 |
0b0_10100_11, |
| 208 |
// e fffff gg |
| 209 |
0b000_11100, |
| 210 |
// ggg hhhhh |
| 211 |
]); |
| 212 |
``` |
| 213 |
|
| 214 |
The `BitSlice` type is a view that alters the behavior of a borrowed memory |
| 215 |
region. It is never held directly, but only by references (created by borrowing |
| 216 |
integer memory) or the `BitArray` value type. In addition, the presence of a |
| 217 |
dynamic allocator enables the `BitBox` and `BitVec` buffer types, which can be |
| 218 |
used for more advanced buffer manipulation: |
| 219 |
|
| 220 |
```rust |
| 221 |
#[cfg(feature = "alloc")] |
| 222 |
fn main() { |
| 223 |
|
| 224 |
use bitvec::prelude::*; |
| 225 |
|
| 226 |
let mut bv = bitvec![u8, Msb0;]; |
| 227 |
bv.push(false); |
| 228 |
bv.push(true); |
| 229 |
bv.extend([false; 4].iter()); |
| 230 |
bv.extend(&15u8.view_bits::<Lsb0>()[.. 4]); |
| 231 |
|
| 232 |
assert_eq!(bv.as_raw_slice(), &[ |
| 233 |
0b01_0000_11, 0b11_000000 |
| 234 |
// ^ dead |
| 235 |
]); |
| 236 |
|
| 237 |
} |
| 238 |
``` |
| 239 |
|
| 240 |
While place expressions like `bits[index] = value;` are not available, `bitvec` |
| 241 |
instead provides a proxy structure that can be used as *nearly* an `&mut bit` |
| 242 |
reference: |
| 243 |
|
| 244 |
```rust |
| 245 |
use bitvec::prelude::*; |
| 246 |
|
| 247 |
let bits = bits![mut 0]; |
| 248 |
// `bit` is not a reference, so |
| 249 |
// it must be bound with `mut`. |
| 250 |
let mut bit = bits.get_mut(0).unwrap(); |
| 251 |
assert!(!*bit); |
| 252 |
*bit = true; |
| 253 |
assert!(*bit); |
| 254 |
// `bit` is not a reference, |
| 255 |
// so NLL rules do not apply. |
| 256 |
drop(bit); |
| 257 |
assert!(bits[0]); |
| 258 |
``` |
| 259 |
|
| 260 |
The `bitvec` data types implement a complete replacement for their |
| 261 |
standard-library counterparts, including all of the inherent methods, traits, |
| 262 |
and operator behaviors. |
| 263 |
|
| 264 |
## User Stories |
| 265 |
|
| 266 |
Uses of `bitvec` generally fall into three major genres. |
| 267 |
|
| 268 |
- compact, fast, `usize => bit` collections |
| 269 |
- truncated integer storage |
| 270 |
- precise control of memory layout |
| 271 |
|
| 272 |
### Bit Collections |
| 273 |
|
| 274 |
At its most basic, `bitvec` provides sequence types analogous to the standard |
| 275 |
library’s `bool` collections. The default behavior is optimized for fast memory |
| 276 |
access and simple codegen, and can compact `[bool]` or `Vec<bool>` with minimal |
| 277 |
overhead. |
| 278 |
|
| 279 |
While `bitvec` does not attempt to take advantage of SIMD or other vectorized |
| 280 |
instructions in its default work, its codegen should be a good candidate for |
| 281 |
autovectorization in LLVM. If explicit vectorization is important to you, please |
| 282 |
[file an issue][issue]. |
| 283 |
|
| 284 |
Example uses might be implementing a Sieve of Eratosthenes to store primes, or |
| 285 |
other collections that test a yes/no property of a number; or replacing |
| 286 |
`Vec<Option<T>>` with `(BitVec, Vec<MaybeUninit<T>>`). |
| 287 |
|
| 288 |
To get started, you can perform basic text replacement on your project. |
| 289 |
Translate any existing types as follows: |
| 290 |
|
| 291 |
- `[bool; N]` becomes `BitArray` |
| 292 |
- `[bool]` becomes `BitSlice` |
| 293 |
- `Vec<bool>` becomes `BitVec` |
| 294 |
- `Box<[bool]>` becomes `BitBox` |
| 295 |
|
| 296 |
and then follow any compiler errors that arise. |
| 297 |
|
| 298 |
### Bit-Field Memory Access |
| 299 |
|
| 300 |
A single bit of information has very few uses. `bitvec` also enables you to |
| 301 |
store integers wider than a single bit, by selecting a bit-slice and using the |
| 302 |
[`BitField`] trait on it. You can store and retrieve both unsigned and signed |
| 303 |
integers, as long as the ordering type parameter is [`Lsb0`] or [`Msb0`]. |
| 304 |
|
| 305 |
If your bit-field storage buffers are never serialized for exchange between |
| 306 |
machines, then you can get away with using the default type parameters and |
| 307 |
unadorned load/store methods. While the in-memory layout of stored integers may |
| 308 |
be surprising if directly inspected, the overall behavior should be optimal for |
| 309 |
your target. |
| 310 |
|
| 311 |
Remember: `bitvec` only provides array place expressions, using integer start |
| 312 |
and end points. You can use [`deku`] if you want C-style named structural fields |
| 313 |
with bit-field memory storage. |
| 314 |
|
| 315 |
However, if you are de/serializing buffers for transport, then you fall into the |
| 316 |
third category. |
| 317 |
|
| 318 |
### Transport Protocols |
| 319 |
|
| 320 |
Many protocols use sub-element fields in order to save space in transport; for |
| 321 |
example, TCP headers have single-bit and 4-bit fields in order to pack all the |
| 322 |
needed information into a desirable amount of space. In C or Erlang, these TCP |
| 323 |
protocol fields could be mapped by record fields in the language. In Rust, they |
| 324 |
can be mapped by indexing into a bit-slice. |
| 325 |
|
| 326 |
When using `bitvec` to manage protocol buffers, you will need to select the |
| 327 |
exact type parameters that match your memory layout. For instance, TCP uses |
| 328 |
`<u8, Msb0>`, while IPv6 on a little-endian machine uses `<u32, Lsb0>`. Once you |
| 329 |
have done this, you can replace all of your `(memory & mask) >> shift` or |
| 330 |
`memory |= (value & mask) << shift` expressions with `memory[start .. end]`. |
| 331 |
|
| 332 |
As a direct example, the Itanium instruction set IA-64 uses very-long |
| 333 |
instruction words containing three 41-bit fields in a `[u8; 16]`. One IA-64 |
| 334 |
disassembler replaced its manual shift/mask implementation with `bitvec` range |
| 335 |
indexing, taking the bit numbers directly from the datasheet, and observed that |
| 336 |
their code was both easier to maintain and also had better performance as a |
| 337 |
result! |
| 338 |
|
| 339 |
## Feature Flags |
| 340 |
|
| 341 |
`bitvec` has a few Cargo features that govern its API surface. The default |
| 342 |
feature set is: |
| 343 |
|
| 344 |
```toml |
| 345 |
[dependencies.bitvec] |
| 346 |
version = "1" |
| 347 |
features = [ |
| 348 |
"alloc", |
| 349 |
"atomic", |
| 350 |
# "serde", |
| 351 |
"std", |
| 352 |
] |
| 353 |
``` |
| 354 |
|
| 355 |
Use `default-features = false` to disable all of them, then `features = []` to |
| 356 |
restore the ones you need. |
| 357 |
|
| 358 |
- `alloc`: This links against the `alloc` distribution crate, and provides the |
| 359 |
`BitVec` and `BitBox` types. It can be used on `#![no_std]` targets that |
| 360 |
possess a dynamic allocator but not an operating system. |
| 361 |
|
| 362 |
- `atomic`: This controls whether atomic instructions can be used for aliased |
| 363 |
memory. `bitvec` uses the [`radium`] crate to perform automatic detection of |
| 364 |
atomic capability, and targets that do not possess atomic instructions can |
| 365 |
still function with this feature *enabled*. Its only effect is that targets |
| 366 |
which do have atomic instructions may choose to disable it and enforce |
| 367 |
single-threaded behavior that never incurs atomic synchronization. |
| 368 |
|
| 369 |
- `serde`: This enables the de/serialization of `bitvec` buffers through the |
| 370 |
`serde` system. This can be useful if you need to transmit `usize => bool` |
| 371 |
collections. |
| 372 |
|
| 373 |
- `std`: This provides some `std::io::{Read,Write}` implementations, as well as |
| 374 |
`std::error::Error` for the various error types. It is otherwise unnecessary. |
| 375 |
|
| 376 |
## Deeper Reading |
| 377 |
|
| 378 |
The [API Documentation][docsrs] explores `bitvec`’s usage and implementation in |
| 379 |
great detail. In particular, you should read the documentation for the |
| 380 |
[`order`], [`store`], and [`field`] modules, as well as the [`BitSlice`] and |
| 381 |
[`BitArray`] types. |
| 382 |
|
| 383 |
In addition, the [user guide][guide] explores the philosophical and academic |
| 384 |
concepts behind `bitvec`’s construction, its goals, and the more intricate parts |
| 385 |
of its behavior. |
| 386 |
|
| 387 |
While you should be able to get started with `bitvec` with only dropping it into |
| 388 |
your code and using the same habits you have with the standard library, both of |
| 389 |
these resources contain all of the information needed to understand what it |
| 390 |
does, how it works, and how it can be useful to you. |
| 391 |
|
| 392 |
<!-- Badges --> |
| 393 |
[crate_link]: https://crates.io/crates/bitvec "Crate listing" |
| 394 |
[crate_img]: https://img.shields.io/crates/v/bitvec.svg?style=for-the-badge&color=f46623 "Crate badge" |
| 395 |
[docs_link]: https://docs.rs/bitvec/latest/bitvec "Crate documentation" |
| 396 |
[docs_img]: https://img.shields.io/docsrs/bitvec/latest.svg?style=for-the-badge "Documentation badge" |
| 397 |
[downloads_img]: https://img.shields.io/crates/dv/bitvec.svg?style=for-the-badge "Crate downloads" |
| 398 |
[license_file]: https://github.com/bitvecto-rs/bitvec/blob/main/LICENSE.txt "Project license" |
| 399 |
[license_img]: https://img.shields.io/crates/l/bitvec.svg?style=for-the-badge "License badge" |
| 400 |
[msrv_img]: https://img.shields.io/badge/MSRV-1.56-f46623?style=for-the-badge&logo=rust "Minimum Supported Rust Version: 1.56" |
| 401 |
|
| 402 |
<!-- Documentation --> |
| 403 |
[`BitArray`]: https://docs.rs/bitvec/latest/bitvec/array/struct.BitArray.html |
| 404 |
[`BitField`]: https://docs.rs/bitvec/latest/bitvec/field/trait.BitField.html |
| 405 |
[`BitSlice`]: https://docs.rs/bitvec/latest/bitvec/slice/struct.BitSlice.html |
| 406 |
[`Lsb0`]: https://docs.rs/bitvec/latest/bitvec/order/struct.Lsb0.html |
| 407 |
[`Msb0`]: https://docs.rs/bitvec/latest/bitvec/order/struct.Msb0.html |
| 408 |
[`field`]: https://docs.rs/bitvec/latest/bitvec/field/index.html |
| 409 |
[`order`]: https://docs.rs/bitvec/latest/bitvec/order/index.html |
| 410 |
[`store`]: https://docs.rs/bitvec/latest/bitvec/store/index.html |
| 411 |
[prelude]: https://docs.rs/bitvec/latest/bitvec/prelude |
| 412 |
|
| 413 |
<!-- External References --> |
| 414 |
[`deku`]: https://crates.io/crates/deku |
| 415 |
[docsrs]: https://docs.rs/bitvec/latest/bitvec |
| 416 |
[erl_bit]: https://www.erlang.org/doc/programming_examples/bit_syntax.html |
| 417 |
[guide]: https://bitvecto-rs.github.io/bitvec/ |
| 418 |
[issue]: https://github.com/bitvecto-rs/bitvec/issues/new |
| 419 |
[moz]: https://hacks.mozilla.org/2021/04/eliminating-data-races-in-firefox-a-technical-report/ "Mozilla Hacks article describing various concurrency bugs in FireFox" |
| 420 |
[`radium`]: https://crates.io/crates/radium |
| 421 |
[`std::bitset<N>`]: https://en.cppreference.com/w/cpp/utility/bitset |
| 422 |
[`std::vector<bool>`]: https://en.cppreference.com/w/cpp/container/vector_bool |