bitpiece
A powerful Rust crate for working with bitfields. Define compact, type-safe bitfield structures with automatic bit packing and extraction.
Features
- Const-compatible: All operations work in
constcontexts no_stdcompatible: Works in embedded and bare-metal environments- Type-safe: Strong typing prevents mixing up different bitfield types
- Flexible bit widths: Support for arbitrary bit widths from 1 to 64 bits
- Signed and unsigned: Both signed (
SB*) and unsigned (B*) arbitrary-width types - Nested bitfields: Compose complex structures from simpler bitfield types
- Enum support: Use enums as bitfield members with automatic bit width calculation
- Zero-cost abstractions: Compiles down to efficient bit manipulation operations
Quick Start
Add to your Cargo.toml:
[]
= "1.0"
Basic usage:
use *;
// Define a 2-bit enum
// Define an 8-bit struct containing multiple fields
Table of Contents
- The
#[bitpiece]Attribute - Built-in Types
- Defining Bitfield Structs
- Defining Bitfield Enums
- Generated Methods and Types
- Opt-in Features
- Working with Fields
- Nested Bitfields
- Signed Types
- Const Context Usage
- The BitPiece Trait
- Error Handling
The #[bitpiece] Attribute
The #[bitpiece] attribute macro is the main entry point for defining bitfield types. It can be applied to structs and enums.
Syntax
// Auto-calculate bit length, basic features
// Auto-calculate bit length, all features
// Explicit 32-bit length, basic features
// Explicit 32-bit length, all features
// Auto-calculate, specific features only
// Explicit length with specific features
Arguments
-
Bit length (optional): An integer specifying the exact bit length. If omitted, the bit length is calculated automatically from the fields (for structs) or variant values (for enums).
-
Feature flags (optional): Control which methods and types are generated. See Opt-in Features for details.
Built-in Types
Unsigned Arbitrary-Width Types (B1 - B64)
Types for unsigned integers of specific bit widths:
use *;
let three_bits: B3 = B3new; // 3-bit value (0-7)
let five_bits: B5 = B5new; // 5-bit value (0-31)
assert_eq!;
assert_eq!;
// Validation
assert!; // Valid: fits in 3 bits
assert!; // Invalid: requires 4 bits
Signed Arbitrary-Width Types (SB1 - SB64)
Types for signed integers of specific bit widths using two's complement:
use *;
let signed: SB5 = SB5new; // 5-bit signed value (-16 to 15)
assert_eq!;
assert_eq!;
assert_eq!;
// Validation
assert!; // Valid: fits in 3 bits
assert!; // Valid: minimum for SB3
assert!; // Invalid: too large
assert!; // Invalid: too small
Standard Integer Types
All standard Rust integer types implement BitPiece:
- Unsigned:
u8,u16,u32,u64 - Signed:
i8,i16,i32,i64
use *;
Boolean Type
bool is a 1-bit type:
use *;
Defining Bitfield Structs
Structs are the primary way to define composite bitfields. Fields are packed in order from least significant bit (LSB) to most significant bit (MSB).
use *;
// Bit layout:
// [immediate: 6 bits][reg_b: 3 bits][reg_a: 3 bits][opcode: 4 bits]
// MSB LSB
Field Ordering
Fields are packed starting from bit 0:
let val = from_bits;
assert_eq!;
assert_eq!;
assert_eq!;
Defining Bitfield Enums
Enums can be used as bitfield types. The bit width is automatically calculated from the variant values, or can be specified explicitly.
Exhaustive Enums
When all possible bit patterns map to valid variants:
use *;
// 2 bits = 4 possible values
// All 2-bit values (0-3) are valid
let dir = from_bits;
assert_eq!;
Non-Exhaustive Enums
When not all bit patterns are valid variants:
use *;
// Auto-calculated: 7 bits needed for value 100
// Valid variant
assert_eq!;
// Invalid bit pattern panics in from_bits
// Use try_from_bits for safe conversion
assert!;
assert!;
Explicit Bit Length for Enums
You can specify a larger bit length than required:
use *;
// Use 16 bits even though values fit in fewer
// Can accept 16-bit values
assert!;
Generated Methods and Types
When you apply #[bitpiece] to a struct, several methods and types are generated.
Generated Constants
// Generated constants:
const MY_STRUCT_BIT_LEN: usize = 16;
type MyStructStorageTy = u16; // Smallest type that fits
Field Constants
For each field, offset and length constants are generated:
// Generated:
// Example::A_OFFSET = 0
// Example::A_LEN = 3
// Example::B_OFFSET = 3
// Example::B_LEN = 5
Core Methods
Associated Constants
Important distinction between ONES/ZEROES and MAX/MIN:
ZEROES: All bits are 0. For unsigned types, this equalsMIN. For signed types, this is 0 (not the minimum).ONES: All bits are 1. For unsigned types, this equalsMAX. For signed types likei8, this represents-1(not the maximum).MIN: The minimum representable value. Fori8, this is-128.MAX: The maximum representable value. Fori8, this is127.
use *;
// For unsigned types: ZEROES == MIN, ONES == MAX
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
// For signed types: ONES != MAX, ZEROES != MIN
assert_eq!; // All bits 0 = 0
assert_eq!; // All bits 1 = -1 in two's complement
assert_eq!; // Minimum value
assert_eq!; // Maximum value
Non-exhaustive enums: For enums where not all bit patterns are valid variants, ZEROES and ONES represent the closest valid variant to the all-zeros or all-ones bit pattern (i.e., MIN and MAX respectively). If an enum has no variant with value 0, ZEROES will be the variant with the smallest value, not a value with all bits set to zero.
// No variant has value 0, so ZEROES is the minimum variant
assert_eq!; // Value 10, not 0
assert_eq!;
assert_eq!; // Maximum variant
assert_eq!;
Opt-in Features
Control which methods and types are generated using feature flags.
Feature Flags
| Flag | Description |
|---|---|
get |
Field getter methods: field_name() |
set |
Field setter methods: set_field_name(value) |
with |
Builder-style methods: with_field_name(value) |
get_noshift |
Raw bit access: field_name_noshift() |
get_mut |
Mutable field references: field_name_mut() |
const_eq |
Const equality comparison |
fields_struct |
Generate TypeNameFields struct |
mut_struct |
Generate TypeNameMutRef type |
mut_struct_field_get |
Getter methods on MutRef |
mut_struct_field_set |
Setter methods on MutRef |
mut_struct_field_get_noshift |
Noshift getters on MutRef |
mut_struct_field_mut |
Nested mutable references on MutRef |
Presets
| Preset | Includes |
|---|---|
basic |
get, set, with (default if no flags specified) |
all |
All features |
mut_struct_all |
All mut_struct* features |
Examples
// Only getters
// Getters and setters, no builder pattern
// Everything
// Custom combination
Working with Fields
Getting Field Values
let packet = from_bits;
// Get individual fields
let version = packet.version; // B2
let flags = packet.flags; // B3
let length = packet.length; // B3
assert_eq!;
assert_eq!;
assert_eq!;
Setting Field Values (Immutable)
The with_* methods return a new instance with the field modified:
let packet = ZEROES;
// Chain modifications
let updated = packet
.with_version
.with_flags
.with_length;
// Original unchanged
assert_eq!;
Setting Field Values (Mutable)
The set_* methods modify the instance in place:
let mut packet = ZEROES;
packet.set_version;
packet.set_flags;
packet.set_length;
Raw Bit Access (Noshift)
Get field bits at their original position without shifting:
let val = from_bits;
// Normal getter: shifts to bit 0
assert_eq!;
// Noshift: keeps original position
assert_eq!;
Mutable References
Get a mutable reference to a field within the bitfield:
let mut container = ZEROES;
assert_eq!;
Nested Bitfields
Bitfield types can be nested within other bitfields:
use *;
let outer = from_bits;
// Access nested fields
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Deep Nesting
let l3 = from_bits;
let nested_data = l3.l2.l1_a.data;
Signed Types
Using Standard Signed Integers
let val = from_fields;
assert_eq!;
assert_eq!;
Using Arbitrary-Width Signed Types
let val = from_bits;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Const Context Usage
All operations work in const contexts:
use *;
// Const construction
const DEFAULT_CONFIG: Config = from_bits;
// Const field access
const DEFAULT_MODE: B2 = DEFAULT_CONFIG.mode;
const DEFAULT_SPEED: B3 = DEFAULT_CONFIG.speed;
const IS_ENABLED: bool = DEFAULT_CONFIG.enabled;
// Const modification
const DISABLED_CONFIG: Config = DEFAULT_CONFIG.with_enabled;
// Const assertions
const _: = assert!;
const _: = assert!;
const _: = assert!;
Const Functions
const
const PACKET: Packet = create_packet;
The BitPiece Trait
All bitfield types implement the BitPiece trait:
Using the Trait Generically
use *;
Error Handling
Safe Conversion with try_from_bits
use *;
// Safe conversion
match try_from_bits
// For exhaustive enums, try_from_bits still validates range
assert!;
Validation for B* and SB* Types
// B types validate that value fits in bit width
assert!; // Max for 4 bits
assert!; // Too large
// SB types validate signed range
assert!; // Max for 4-bit signed
assert!; // Min for 4-bit signed
assert!; // Too large
assert!; // Too small
Panicking Constructors
The new and from_bits methods panic on invalid input:
// These will panic:
// let _ = B3::new(8); // Value doesn't fit
// let _ = Status::from_bits(5); // Invalid variant
Fields Struct
When fields_struct is enabled, a companion struct is generated for convenient construction:
// Generated: PacketFields struct
let fields = PacketFields ;
let packet = from_fields;
// Convert back to fields
let extracted: PacketFields = packet.to_fields;
assert_eq!;
// From/Into implementations
let packet2: Packet = fields.into;
let fields2: PacketFields = packet2.into;
Nested Fields
For nested bitfields, the fields struct uses the direct bitfield type (not its *Fields type):
// OuterFields uses Inner directly for field 'a'
let fields = OuterFields ;
let outer = from_fields;
// You can also construct the inner type from its fields and convert:
let fields2 = OuterFields ;
Storage Types
The crate automatically selects the smallest storage type that fits the bit length:
| Bit Length | Storage Type |
|---|---|
| 1-8 | u8 |
| 9-16 | u16 |
| 17-32 | u32 |
| 33-64 | u64 |
Access the storage directly:
let val = from_bits;
// Direct storage access
assert_eq!;
// Storage type is u16 for 12 bits
let storage: u16 = val.storage;
License
MIT License - see LICENSE for details.