Non-self-describing, no external schema file

RecipeCratesCategories
postcardpostcardcat-encoding
rkyvrkyvcat-encoding

postcard

postcard postcard-crates.io postcard-github postcard-lib.rs cat-embedded cat-no-std

A no_std + serde compatible message library for Rust.

no_std-focused serde serializer/deserializer, aimed at constrained environments.

use std::ops::Deref;

use heapless::Vec;
use postcard::from_bytes;
use postcard::to_vec;
use serde::Deserialize;
use serde::Serialize;

// [dependencies]
// postcard = "1.0.0"

// # By default, `serde` has the `std` feature enabled, which makes it
// unsuitable for embedded targets # disabling default-features fixes this
// serde = { version = "1.0.*", default-features = false }

// Example from https://lib.rs/crates/postcard

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct RefStruct<'a> {
    bytes: &'a [u8],
    str_s: &'a str,
}

fn main() {
    let message = "hElLo";

    let bytes = [0x01, 0x10, 0x02, 0x20];

    let output: Vec<u8, 11> = to_vec(&RefStruct {
        bytes: &bytes,
        str_s: message,
    })
    .unwrap();

    assert_eq!(
        &[
            0x04, 0x01, 0x10, 0x02, 0x20, 0x05, b'h', b'E', b'l', b'L', b'o',
        ],
        output.deref()
    );

    let out: RefStruct = from_bytes(output.deref()).unwrap();
    assert_eq!(
        out,
        RefStruct {
            bytes: &bytes,
            str_s: message,
        }
    );
}

rkyv

rkyv rkyv-crates.io rkyv-github rkyv-lib.rs cat-encoding cat-no-std cat-no-std::no-alloc

Fast zero-copy deserialization framework that allows arbitrary field types and safe zero-copy mutation.

use rkyv::Archive;
use rkyv::Deserialize;
use rkyv::Serialize;
use rkyv::rancor::Error;

// `rkyv` (short for "archive") is a high-performance, zero-copy
// (de)serialization framework that allows arbitrary field types
// and safe zero-copy mutation.

#[derive(Archive, Deserialize, Serialize, Debug)]
struct MyStruct {
    field1: String,
    field2: i32,
}

fn main() -> anyhow::Result<()> {
    // Create an instance of MyStruct
    let data = MyStruct {
        field1: "Hello, world!".to_string(),
        field2: 42,
    };

    // Serialize the data to a byte array
    let buffer = rkyv::to_bytes::<Error>(&data)?;

    // Print the serialized data
    println!("Serialized data: {:?}", buffer);

    // Deserialize the data from the byte array
    let deserialized_data = rkyv::from_bytes::<MyStruct, Error>(&buffer[..])?;

    println!("{:?}", deserialized_data);

    Ok(())
}