#serialization #deserialization #network #bytes #big-endian

bin+lib bebytes

A Rust library for serialization and deserialization of network structs

8 releases

0.2.1 Jan 15, 2024
0.2.0 Dec 29, 2023
0.1.5 Oct 15, 2023
0.1.3 Aug 30, 2023
0.1.2 Jul 8, 2023

#925 in Network programming

Download history 9/week @ 2023-11-06 14/week @ 2023-11-13 32/week @ 2023-11-20 29/week @ 2023-11-27 13/week @ 2023-12-04 44/week @ 2023-12-11 67/week @ 2023-12-18 86/week @ 2023-12-25 16/week @ 2024-01-01 11/week @ 2024-01-08 54/week @ 2024-01-15 7/week @ 2024-01-22 47/week @ 2024-01-29 14/week @ 2024-02-05 53/week @ 2024-02-12 237/week @ 2024-02-19

351 downloads per month
Used in 2 crates

MIT license

19KB
432 lines

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) using big endian order. 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:

[dependencies]
bebytes = "*"

Then, import the BeBytes trait from the bebytes_derive crate and derive it for your struct:

use bebytes::BeBytes;

#[derive(BeBytes)]
struct Dummy {
    a: u8,
}

fn build_with_bebytes(input: impl BeBytes) -> Vec<u8> {
    input.to_be_bytes()
}

fn build_from_bytes(input: &[u8]) -> Result<(Dummy, usize), Box<dyn std::error::Error>> {
    Dummy::try_from_be_bytes(input)
}

The BeBytes derive macro will generate the following methods for your struct:

  • try_from_be_bytes(&[u8]) -> Result<(Self, usize), Box<dyn std::error::Error>>: A method to convert a 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 byte representation. It returns a Vec<u8> containing the serialized bytes.
  • field_size() -> usize: A method to calculate the size (in bytes) of the struct.

Contribute

I'm doing this for fun, but all help is appreciated.

License

This project is licensed under the MIT License

Dependencies

~315–760KB
~18K SLoC