#encode-decode #serialization #encode #decode #binary #deserialize #binary-format

macro databuf-derive

This library used to serialize and deserialize data in binary format

8 releases (4 breaking)

0.5.0 Jul 17, 2023
0.4.0 Jul 4, 2023
0.3.1 Feb 20, 2023
0.2.1 Feb 15, 2023
0.1.0 Dec 24, 2022

#130 in #encode-decode

Download history 19/week @ 2024-07-22 1/week @ 2024-07-29 101/week @ 2024-08-05 231/week @ 2024-08-12 207/week @ 2024-08-19 215/week @ 2024-08-26 253/week @ 2024-09-02 143/week @ 2024-09-09 117/week @ 2024-09-16 147/week @ 2024-09-23 57/week @ 2024-09-30 219/week @ 2024-10-07 141/week @ 2024-10-14 81/week @ 2024-10-21 149/week @ 2024-10-28 108/week @ 2024-11-04

506 downloads per month
Used in 2 crates (via databuf)

Apache-2.0

17KB
383 lines

Doc

This library used to serialize and deserialize structured data in binary format.

Examples

[dependencies]
databuf = "0.5"
use databuf::{*, config::num::LE};

#[derive(Encode, Decode)]
struct Car<'a> {
    year: u16,
    is_new: bool,
    name: &'a str,
}

#[derive(Encode, Decode)]
struct Company<'a> { name: String, cars: Vec<Car<'a>> }

let old = Company {
    name: "Tesla".into(),
    cars: vec![
        Car { name: "Model S", year: 2018, is_new: true },
        Car { name: "Model X", year: 2019, is_new: false },
    ],
};
let bytes = old.to_bytes::<LE>();
let new = Company::from_bytes::<LE>(&bytes).unwrap();

Vec, String, &[T], &str etc.. are encoded with their length value first, Following by each entry.

By default, length of collections is represented with BEU30.

use databuf::{*, config::num::LE};

#[derive(Encode, Decode)]
struct Msg<'a> {
    id: u16,
    data: &'a str,
}
let bytes = [42, 0, 13, 72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33];
//           ^^^^^  ^^  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//            Id    Len                         Data

let msg = Msg::from_bytes::<LE>(&bytes).unwrap();
assert_eq!(msg.id, 42);
assert_eq!(msg.data, "Hello, World!"); // Here, data is referenced.
  • Example: Encoding data into a buffer of specified size.
use databuf::{*, config::{num, len}};
/// Use big endian byte order + Encode `msg` length with `databuf::var_int::BEU15` 
const CONFIG: u16 = num::BE | len::BEU15;

#[derive(Encode, Decode)]
struct Date {
    year: u16,
    month: u8,
    day: u8,
}

#[derive(Encode, Decode)]
struct Record<T> {
    id: T,
    date: Date,
    msg: String,
}

let record = Record { id: 42_u32, date: Date { year: 2018, month: 3, day: 7 }, msg: "Hello!".into() };

let mut buf = [0; 20];
let remaining = &mut buf.as_mut_slice();
record.encode::<CONFIG>(remaining).unwrap();

let amt = 20 - remaining.len();
assert_eq!(amt, 15); // 15 bytes written to `buf`

Dependencies

~260–710KB
~17K SLoC