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

postcard is a no_std and serde-compatible message library for Rust.

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

//! This example demonstrates how to use the `postcard` crate for serialization
//! and deserialization without an external schema file.
//!
//! Add to your `Cargo.toml` file:
//! ```toml
//! [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:
//! ```toml
//! serde = { version = "1.0.*", default-features = false }
//! ```
//! Example adapted from https://lib.rs/crates/postcard
use std::ops::Deref;

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

#[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

rkyv is a fast zero-copy deserialization framework that allows arbitrary field types and safe zero-copy mutation.

//! `rkyv` (short for "archive") is a high-performance, zero-copy
//! (de)serialization framework that allows arbitrary field types
//! and safe zero-copy mutation.
//!
//! This example demonstrates how to serialize and deserialize a struct
//! using `rkyv` without an external schema file.
use rkyv::Archive;
use rkyv::Deserialize;
use rkyv::Serialize;
use rkyv::rancor::Error;

#[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(())
}