nexus-bits
Bit field packing for integer IDs.
nexus-bits provides ergonomic bit field manipulation for packing multiple values into integers — common in trading systems for instrument IDs, order IDs, and wire protocols.
Why nexus-bits?
Several excellent bitfield crates exist (bitfield-struct, modular-bitfield, bitfield). nexus-bits targets a different use case:
| Feature | nexus-bits | Others |
|---|---|---|
| Bit positions | Explicit #[field(start = 4, len = 8)] |
Auto-sequential |
| Storage | Pack to/from raw integers (u64, i64) |
Wrapped in struct |
| Overflow | Result<T, FieldOverflow> |
Silent truncation |
| Tagged enums | Discriminant-based variant layouts | Not supported |
When to use nexus-bits:
- Matching existing wire formats or ID schemes with specific bit layouts
- Working with IDs that must be plain integers (database keys, protocol fields)
- Trading systems where silent truncation is unacceptable
- Packing different data into the same integer based on a discriminant
When to use other crates:
- Auto-layouting fields sequentially is fine
- You want the bitfield wrapped in a type (not a raw integer)
- Truncation on overflow is acceptable
Features
BitField<T>— Extract and set multi-bit fields at arbitrary positionsFlag<T>— Single-bit boolean flagsIntEnum— Derive macro for#[repr(u8)]enums to convert to/from integersBitPacked— Derive macro for structs with automatic pack/unpack generationno_stdcompatible- Compile-time validation — Field overlap and bounds checking at compile time
- Runtime overflow detection — Returns
Resulton pack if values exceed field capacity
Usage
Manual bit field manipulation
use ;
const KIND: = new;
const EXCHANGE: = new;
const SYMBOL: = new;
const IS_TEST: = new;
// Pack
let mut id: u64 = 0;
id = KIND.set.unwrap;
id = EXCHANGE.set.unwrap;
id = SYMBOL.set.unwrap;
id = IS_TEST.set;
// Unpack
assert_eq!;
assert_eq!;
assert_eq!;
assert!;
Derive macros (recommended)
use ;
let id = InstrumentId ;
// Pack to integer
let packed: u64 = id.pack.unwrap;
// Unpack from integer
let unpacked = unpack.unwrap;
assert_eq!;
Snowflake-style IDs
use BitPacked;
Error Handling
Pack returns Result<T, FieldOverflow<T>> if a value exceeds its field capacity:
let id = InstrumentId ;
assert!;
Unpack for structs with IntEnum fields returns Result<Self, UnknownDiscriminant<T>>:
let raw: u64 = 0xFF; // Invalid exchange value
let result = unpack;
assert!;
Structs with only primitive fields have infallible unpack returning Self directly.
Features
| Feature | Default | Description |
|---|---|---|
derive |
Yes | Enables #[derive(BitPacked)] and #[derive(IntEnum)] |
Disable derive macros for a minimal no_std build:
[]
= { = "0.1", = false }
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.