Bitpiece
bitfields implementation for rust
Install / Use
/learn @roeeshoshani/BitpieceREADME
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
use bitpiece::*;
// Define a 2-bit enum
#[bitpiece(2, all)]
#[derive(Debug, PartialEq, Eq)]
enum Priority {
Low = 0,
Medium = 1,
High = 2,
Critical = 3,
}
// Define an 8-bit struct containing multiple fields
#[bitpiece(8, all)]
#[derive(Debug, PartialEq, Eq)]
struct StatusByte {
enabled: bool, // 1 bit
priority: Priority, // 2 bits
count: B5, // 5 bits (unsigned, 0-31)
}
fn main() {
// Create from raw bits
let status = StatusByte::from_bits(0b10101_01_1);
assert_eq!(status.enabled(), true);
assert_eq!(status.priority(), Priority::Medium);
assert_eq!(status.count(), B5::new(21));
// Modify fields
let updated = status
.with_priority(Priority::Critical)
.with_count(B5::new(7));
assert_eq!(updated.to_bits(), 0b00111_11_1);
}
Table of Contents
- The
#[bitpiece]Attribute - Built-in Types
- Defining Bitfield Structs
- Defining Bitfield Enums
- Generated Methods and Types
- Opt-in Features
- Attributes and Derives
- 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
#[bitpiece] // Auto-calculate bit length, basic features
#[bitpiece(all)] // Auto-calculate bit length, all features
#[bitpiece(32)] // Explicit 32-bit length, basic features
#[bitpiece(32, all)] // Explicit 32-bit length, all features
#[bitpiece(get, set)] // Auto-calculate, specific features only
#[bitpiece(16, get, set, with)] // 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 bitpiece::*;
let three_bits: B3 = B3::new(0b101); // 3-bit value (0-7)
let five_bits: B5 = B5::new(31); // 5-bit value (0-31)
assert_eq!(three_bits.get(), 5);
assert_eq!(B3::MAX.get(), 7);
// Validation
assert!(B3::try_new(7).is_some()); // Valid: fits in 3 bits
assert!(B3::try_new(8).is_none()); // Invalid: requires 4 bits
Signed Arbitrary-Width Types (SB1 - SB64)
Types for signed integers of specific bit widths using two's complement:
use bitpiece::*;
let signed: SB5 = SB5::new(-10); // 5-bit signed value (-16 to 15)
assert_eq!(signed.get(), -10);
assert_eq!(SB5::MIN.get(), -16);
assert_eq!(SB5::MAX.get(), 15);
// Validation
assert!(SB3::try_new(3).is_some()); // Valid: fits in 3 bits
assert!(SB3::try_new(-4).is_some()); // Valid: minimum for SB3
assert!(SB3::try_new(4).is_none()); // Invalid: too large
assert!(SB3::try_new(-5).is_none()); // Invalid: too small
Standard Integer Types
All standard Rust integer types implement BitPiece:
- Unsigned:
u8,u16,u32,u64 - Signed:
i8,i16,i32,i64
use bitpiece::*;
#[bitpiece(48, all)]
struct MixedTypes {
byte: u8, // 8 bits
word: u16, // 16 bits
flags: B8, // 8 bits
signed: i16, // 16 bits
}
Boolean Type
bool is a 1-bit type:
use bitpiece::*;
#[bitpiece(3, all)]
struct Flags {
read: bool, // 1 bit
write: bool, // 1 bit
execute: bool, // 1 bit
}
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 bitpiece::*;
#[bitpiece(16, all)]
#[derive(Debug, PartialEq, Eq)]
struct Instruction {
opcode: B4, // Bits 0-3 (LSB)
reg_a: B3, // Bits 4-6
reg_b: B3, // Bits 7-9
immediate: B6, // Bits 10-15 (MSB)
}
// 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:
#[bitpiece(8, all)]
struct Example {
a: B2, // Bits 0-1
b: B3, // Bits 2-4
c: B3, // Bits 5-7
}
let val = Example::from_bits(0b111_010_01);
assert_eq!(val.a(), B2::new(0b01));
assert_eq!(val.b(), B3::new(0b010));
assert_eq!(val.c(), B3::new(0b111));
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 bitpiece::*;
#[bitpiece(2, all)] // 2 bits = 4 possible values
#[derive(Debug, PartialEq, Eq)]
enum Direction {
North = 0,
East = 1,
South = 2,
West = 3,
}
// All 2-bit values (0-3) are valid
let dir = Direction::from_bits(2);
assert_eq!(dir, Direction::South);
Non-Exhaustive Enums
When not all bit patterns are valid variants:
use bitpiece::*;
#[bitpiece(all)] // Auto-calculated: 7 bits needed for value 100
#[derive(Debug, PartialEq, Eq)]
enum ErrorCode {
Success = 0,
NotFound = 10,
PermissionDenied = 50,
InternalError = 100,
}
// Valid variant
assert_eq!(ErrorCode::from_bits(10), ErrorCode::NotFound);
// Invalid bit pattern panics in from_bits
// Use try_from_bits for safe conversion
assert!(ErrorCode::try_from_bits(25).is_none());
assert!(ErrorCode::try_from_bits(50).is_some());
Explicit Bit Length for Enums
You can specify a larger bit length than required:
use bitpiece::*;
#[bitpiece(16, all)] // Use 16 bits even though values fit in fewer
#[derive(Debug, PartialEq, Eq)]
enum Command {
Nop = 0,
Load = 1,
Store = 2,
}
// Can accept 16-bit values
assert!(Command::try_from_bits(1000).is_none());
Generated Methods and Types
When you apply #[bitpiece] to a struct, several methods and types are generated.
Generated Constants
#[bitpiece(16, all)]
struct MyStruct { /* ... */ }
// 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:
#[bitpiece(8, all)]
struct Example {
a: B3,
b: B5,
}
// Generated:
// Example::A_OFFSET = 0
// Example::A_LEN = 3
// Example::B_OFFSET = 3
// Example::B_LEN = 5
Core Methods
impl MyStruct {
// Create from raw bits (panics if invalid for non-exhaustive types)
pub const fn from_bits(bits: StorageTy) -> Self;
// Try to create from raw bits (returns None if invalid)
pub const fn try_from_bits(bits: StorageTy) -> Option<Self>;
// Convert to raw bits
pub const fn to_bits(self) -> StorageTy;
}
Associated Constants
impl BitPiece for MyStruct {
const BITS: usize; // Total bit length
const ZEROES: Self; // All bits set to 0 (for structs: each field's ZEROES)
const ONES: Self; // All bits set to 1 (for structs: each field's ONES)
const MIN: Self; // The minimum value (for structs: each field's MIN)
const MAX: Self; // The maximum value (for structs: each field's MAX)
}
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 bitpiece::*;
// For unsigned types: ZEROES == MIN, ONES == MAX
assert_eq!(B8::ZEROES.get(), 0);
assert_eq!(B8::ONES.get(), 255);
assert_eq!(B8::MIN.get(), 0);
assert_eq!(B8::MAX.get(), 255);
// For signed types: ONES != MAX, ZEROES != MIN
assert_eq!(SB8::ZEROES.get(), 0); // All bits 0 = 0
assert_eq!(SB8::ONES.get(), -1); // All bits 1 = -1 in two's complement
assert_eq!(SB8::MIN.get(), -128); // Minimum value
assert_eq!(SB8::MAX.get(), 127); // Maximum value
Non-exhaustive enums: For enums where not all bit patterns are valid variants, ZEROES and ONES represent the c
