Declarative binary reading and writing for Rust
Describe a binary layout with annotated structs and enums, then derive bit-level reading and writing implementations from the same definition. It is designed for network protocols, file formats, and embedded data.
- Symmetric reading and writing from a single type definition
- Designed for efficient binary reading and writing
- Bit-sized fields with configurable byte and bit order
- Tagged enums, variable-length collections, and conditional fields
- Validation, context-aware types, and custom readers and writers
- Byte slices and
Read/Writestreams std,no_std, and fixed-size, no-allocation workflows withDekuSize
Compiler support: requires rustc 1.88+
[dependencies]
deku = "0.20"This example reads a red pixel in the 16-bit RGB565 format, adds blue, then writes the resulting magenta pixel back to bytes.
use deku::prelude::*;
#[derive(Debug, PartialEq, DekuRead, DekuWrite)]
#[deku(endian = "big")]
struct Rgb565 {
#[deku(bits = 5)]
red: u8,
#[deku(bits = 6)]
green: u8,
#[deku(bits = 5)]
blue: u8,
}
fn main() {
let input = [0xf8, 0x00];
let (_, mut pixel) = Rgb565::from_bytes((&input, 0)).unwrap();
assert_eq!(pixel, Rgb565 { red: 31, green: 0, blue: 0 });
pixel.blue = 31;
let output = pixel.to_bytes().unwrap();
assert_eq!(output, [0xf8, 0x1f]);
}The attributes describe the binary layout; DekuRead and DekuWrite generate
the matching operations in both directions.
See the API documentation,
#[deku] attribute reference,
and examples for
complete protocol layouts and more advanced use cases.
The default feature set selects std, bits, and descriptive-errors.
alloc is enabled by both std and descriptive-errors.
| Feature | Default | Description |
|---|---|---|
std |
Yes | Standard library integration; also enables alloc |
alloc |
Indirectly | Heap-backed types such as Vec and allocating APIs such as to_bytes |
bits |
Yes | Bit-sized and non-byte-aligned fields, including #[deku(bits = ...)] |
descriptive-errors |
Yes | Detailed, dynamically formatted error messages; requires alloc |
logging |
No | Trace-level read and write diagnostics through the log crate |
Deku supports no_std with or without allocation. Disable the default features
for a minimal no-allocation build:
[dependencies]
deku = { version = "0.20", default-features = false }Features can be combined as needed. For example, enable bits for bit-level
formats and alloc for heap-backed types:
[dependencies]
deku = { version = "0.20", default-features = false, features = ["bits", "alloc"] }See the contribution guide for development, testing, linting, and CI instructions.
Licensed under either the MIT license or Apache License 2.0.