Bitfield Struct
Procedural macro for bitfields that allows specifying bitfields as structs.
As this library provides a procedural macro, it has no runtime dependencies and works for no-std environments.
- Ideal for driver/OS/embedded development (defining HW registers/structures)
- Supports bool flags, integers, and custom types convertible into integers (structs/enums)
- Generates minimalistic, pure, safe rust functions
- Compile-time checks for type and field sizes
- Rust-analyzer/docrs friendly (carries over docs to accessor functions)
- Exports field offsets and sizes as constants (useful for const asserts)
- Optional generation of
Default,Clone,Debug,Hash,defmt::Format, orbinrw::(BinRead|BinWrite)traits - Custom internal representation (endianness)
- Auto-generate enum conversion functions
#[bitenum]
Usage
Add this to your Cargo.toml:
[]
= "0.11"
Basics
Let's begin with a simple example. Suppose we want to store multiple data inside a single Byte, as shown below:
This crate generates a nice wrapper type that makes it easy to do this:
use bitfield;
/// Define your type like this with the bitfield attribute
// The macro creates three accessor functions for each field:
// <name>, with_<name> and set_<name>
let my_byte = new
.with_kind
.with_system
.with_level
.with_present;
assert!;
Features
Additionally, this crate has a few useful features, which are shown here in more detail.
The example below shows how attributes are carried over and how signed integers, padding, and custom types are handled.
use bitfield;
/// A test bitfield with documentation
// <- Attributes after `bitfield` are carried over
/// A custom enum
// Usage:
let mut val = new
.with_int
.with_tiny
.with_negative
.with_custom
.with_public
// .with_read_only(true) <- Would not compile
.with_write_only;
println!;
let raw: u64 = val.into;
println!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
// const members
assert_eq!;
assert_eq!;
val.set_negative;
assert_eq!;
The macro generates three accessor functions for each field. Each accessor also inherits the documentation of its field.
The signatures for int are:
// generated struct
;
// Also generates From<u64>, Into<u64>, Default, and Debug implementations...
Hint: You can use the rust-analyzer "Expand macro recursively" action to view the generated code.
Custom Types
The macro supports any types that are convertible into the underlying bitfield type. This can be enums like in the following example or any other struct.
The conversion and default values can be specified with the following #[bits] parameters:
from: Function converting from raw bits into the custom type, defaults to<ty>::from_bitsinto: Function converting from the custom type into raw bits, defaults to<ty>::into_bitsdefault: Custom expression, defaults to calling<ty>::from_bits(0)
use bitfield;
/// Bitfields implement the conversion functions automatically
Field Order
The optional order macro argument determines the layout of the bits, with the default being
Lsb (least significant bit) first:
use bitfield;
let my_byte_lsb = new
.with_kind
.with_system
.with_level
.with_present;
// .- present
// | .- level
// | | .- system
// | | | .- kind
assert_eq!;
The macro generates the reverse order when Msb (most significant bit) is specified:
use bitfield;
let my_byte_msb = new
.with_kind
.with_system
.with_level
.with_present;
// .- kind
// | .- system
// | | .- level
// | | | .- present
assert_eq!;
Custom Representation and Endianness
The macro supports custom types for the representation of the bitfield struct.
This can be an endian-defining type like in the following examples (from endian-num) or any other struct that can be converted to and from the main bitfield type.
The representation and its conversion functions can be specified with the following #[bitfield] parameters:
reprspecifies the bitfield's representation in memoryfromto specify a conversion function from repr to the bitfield's integer typeintoto specify a conversion function from the bitfield's integer type to repr
This example has a little-endian byte order even on big-endian machines:
use bitfield;
use le16;
let my_be_bitfield = new
.with_first_nibble
.with_other;
assert_eq!;
This example has a big-endian byte order even on little-endian machines:
use bitfield;
use be16;
let my_be_bitfield = new
.with_first_nibble
.with_other;
assert_eq!;
Automatic Trait Implementations
Clone, Copy
By default, this macro derives Clone and Copy.
You can disable this with the extra clone argument if the semantics of cloning your type require it (e.g. the type holds a pointer to owned data that must also be cloned).
In this case, you can provide your own implementations for Clone and Copy.
use bitfield;
// optionally:
fmt::Debug, Default
By default, it also generates suitable fmt::Debug and Default implementations similar to the ones created for normal structs by #[derive(Debug, Default)].
You can disable this with the extra debug and default arguments.
use ;
use bitfield;
let val = default;
println!
Support for defmt::Format
This macro can automatically implement a defmt::Format that mirrors the default fmt::Debug implementation by passing the extra defmt argument.
This implementation requires the defmt crate to be available as defmt, and has the same rules and caveats as #[derive(defmt::Format)].
use bitfield;
Support for std::hash::Hash
This macro can also implement Hash, which ignores any padding when hashing.
use bitfield;
Conditionally Enable new/Clone/Debug/Default/defmt::Format/Hash
Instead of booleans, you can specify cfg(...) attributes for new, clone, debug, default, defmt and hash:
use bitfield;
Auto-Generate Enum from_bits/into_bits
Enums are very helpful inside bitfields. However, manually writing conversion functions is tedious; thus, this crate contains a macro for autogenerating them.
use bitenum;
assert_eq!;
assert_eq!;