BeBytes
BeBytes is a trait wrapper around the BeBytes derive crate.
BeBytes Derive
Derive is a procedural macro crate that provides a custom derive macro for generating serialization and deserialization methods for network structs in Rust. The macro generates code to convert the struct into a byte representation (serialization) and vice versa (deserialization) supporting both big endian and little endian byte orders. It aims to simplify the process of working with network protocols and message formats by automating the conversion between Rust structs and byte arrays.
For more information, see the BeBytes Derive crate.
Usage
To use BeBytes, add it as a dependency in your Cargo.toml file:
[]
= "1.3.0"
Then, import the BeBytes trait from the bebytes crate and derive it for your struct:
use BeBytes;
// Using big-endian serialization
// Using little-endian serialization
// Deserializing from big-endian bytes
// Deserializing from little-endian bytes
Features
The BeBytes derive macro generates the following methods for your struct:
field_size() -> usize: A method to calculate the size (in bytes) of the struct.
Big-endian methods:
try_from_be_bytes(&[u8]) -> Result<(Self, usize), Box<dyn std::error::Error>>: A method to convert a big-endian byte slice into an instance of your struct. It returns a Result containing the deserialized struct and the number of consumed bytes.to_be_bytes(&self) -> Vec<u8>: A method to convert the struct into a big-endian byte representation. It returns aVec<u8>containing the serialized bytes.
Little-endian methods:
try_from_le_bytes(&[u8]) -> Result<(Self, usize), Box<dyn std::error::Error>>: A method to convert a little-endian byte slice into an instance of your struct. It returns a Result containing the deserialized struct and the number of consumed bytes.to_le_bytes(&self) -> Vec<u8>: A method to convert the struct into a little-endian byte representation. It returns aVec<u8>containing the serialized bytes.
Bit Field Manipulation
BeBytes provides fine-grained control over bit fields through the bits attribute:
The bits attribute takes a single parameter:
bits(n): The number of bits this field uses
Key points:
- Bit positions are automatically calculated based on field order
- Bits fields MUST complete a full byte before any non-bits field
- The sum of all bits within a group must equal 8 (or a multiple of 8)
Multi-Byte Bit Fields
BeBytes supports bit manipulation on all integer types from u8/i8 to u128/i128:
The same rules apply - all bits fields must complete a byte boundary together.
Enum Bit Packing
Enums can be used with the #[bits()] attribute for automatic bit-width calculation. While #[repr(u8)] is not strictly required, it is recommended as it makes the u8 constraint explicit and provides compile-time guarantees:
// Recommended: ensures discriminants fit in u8 at compile time
Key features:
- Automatic bit calculation:
ceil(log2(max_discriminant + 1)) - No need to specify the bit width in both enum definition and usage
- Type-safe conversion with generated
TryFrom<u8>implementation - Supports byte-spanning fields automatically
- Compile-time validation: discriminants exceeding u8 range (255) will produce an error
- Works without
#[repr(u8)], but using it is recommended for clarity and compile-time safety
Flag Enums
BeBytes supports flag-style Enums marked with #[bebytes(flags)]. These Enums automatically implement bitwise operations (|, &, ^, !) allowing them to be used as bit flags:
// Usage
let read_write = Read | Write; // = 3
let all_perms = Read | Write | Execute | Delete; // = 15
// Check if a flag is set
assert!;
assert!;
// Toggle flags
let perms = Read | Execute;
let toggled = perms ^ Execute as u8; // Removes Execute
// Validate flag combinations
assert_eq!; // Valid: Read|Write|Execute
assert_eq!; // Invalid: 16 is not a valid flag
Key features:
- All Enum variants must have power-of-2 values (1, 2, 4, 8, etc.)
- Zero value is allowed for "None" or empty flags
- Automatic implementation of bitwise operators
contains()method to check if a flag is setfrom_bits()method to validate flag combinations
Supported Types
BeBytes supports:
- Primitives:
u8,u16,u32,u64,u128,i8,i16,i32,i64,i128 - Arrays:
[u8; N],[u16; N], etc. - Enums with named fields (serialized as a single byte)
- Enums with
#[bits()]for automatic bit-width calculation Option<T>where T is a primitive- Nested structs that also implement
BeBytes Vec<T>with some restrictions (see below)
Vector Support
Vectors require special handling since their size is dynamic. BeBytes provides several ways to handle vectors:
1. Last Field
A vector can be used as the last field in a struct without additional attributes:
2. With Size Hint
Use #[With(size(n))] to specify the exact number of bytes:
3. From Field
Use #[FromField(field_name)] to read the size from another field:
3.1 Nested Field Access
You can also reference fields in nested structures using dot notation:
// Even deeply nested fields are supported:
4. Vectors of Custom Types
BeBytes supports vectors containing custom types that implement the BeBytes trait:
For vectors of custom types, the following rules apply:
- When used as the last field, it will consume all remaining bytes, parsing them as instances of the custom type
- When used elsewhere, you must specify size information with
#[FromField]or#[With] - Each item in the vector is serialized/deserialized using its own BeBytes implementation
No-STD Support
BeBytes supports no_std environments through feature flags:
[]
= { = "1.3.0", = false }
By default, the std feature is enabled. Disable it for no_std support.
Example: DNS Name Parsing
This example shows how BeBytes can be used to parse a DNS name with dynamic length segments, demonstrating both #[FromField] attribute and vectors of custom types:
// Usage example
Contribute
I'm doing this for fun, but all help is appreciated.
License
This project is licensed under the MIT License