Function to_bytes

Source
pub fn to_bytes<T>(value: &T) -> Result<BytesMut>
where T: BinarySerialize,
Expand description

Serializes a given value into a binary format using the default configuration.

§Default Configuration

  • Optional Strategy: Tagged (uses a single byte to indicate Some or None)
  • Endianness: Little-endian
  • Limit: No size limit
  • Container Length: 4 bytes (used to encode the length of sequences, strings, etc.)

§Parameters

  • value: A reference to the value to be serialized. The value must implement the Serialize trait.

§Returns

  • Ok(BytesMut): The serialized binary representation of the value.
  • Err(Error): An error if serialization fails or exceeds the configured limit.

§Example

use binja::{to_bytes, BinarySerialize};

#[derive(BinarySerialize)]
struct Example {
    field1: u32,
    field2: Option<u32>,
}

let value = Example {
    field1: 42,
    field2: Some(7),
};

let serialized = to_bytes(&value).unwrap().to_vec();
assert_eq!(serialized, vec![0x2A, 0x0, 0x0, 0x0, 0x1, 0x7, 0x0, 0x0, 0x0]);