jamesmunns / postcard

A no_std + serde compatible message library for Rust
Apache License 2.0
788 stars 76 forks source link

Deserializing a Map fails with `DeserializeUnexpectedEnd` #141

Closed jounathaen closed 2 months ago

jounathaen commented 2 months ago

I don't know if "I'm holding it wrong" or anything, but I can't deserialize a map with postcard. The error is DeserializeUnexpectedEnd, which does not really give me a clue on what the problem is.

Minimal example:

use heapless::LinearMap;
use postcard::{from_bytes, to_vec};

fn main() {
    let mut map: LinearMap<&str, &[u8], 4> = LinearMap::new();
    map.insert("a", b"asdf").unwrap();
    map.insert("b", b"as1df").unwrap();
    map.insert("c", b"as2df").unwrap();

    println!("map: {map:?}");

    let m: heapless::Vec<u8, 64> = to_vec(&map).unwrap();
    println!("m: {m:?}");

    let m2: (LinearMap<&str, &[u8], 4>, usize) = from_bytes(&m).unwrap();
    println!("m2: {m2:?}");
}

Output:

> cargo run
   Compiling serde-test v0.1.0 (/tmp/serde-test)
    Finished dev [unoptimized + debuginfo] target(s) in 0.38s
     Running `target/debug/serde-test`
map: {"a": [97, 115, 100, 102], "b": [97, 115, 49, 100, 102], "c": [97, 115, 50, 100, 102]}
m: [3, 1, 97, 4, 97, 115, 100, 102, 1, 98, 5, 97, 115, 49, 100, 102, 1, 99, 5, 97, 115, 50, 100, 102]
thread 'main' panicked at src/main.rs:15:65:
called `Result::unwrap()` on an `Err` value: DeserializeUnexpectedEnd
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Cargo.toml:

[package]
name = "serde-test"
version = "0.1.0"
edition = "2021"

[dependencies]
heapless = { version = "0.7", features = ["serde"] }
postcard = "1.0.8"
serde = { version = "1.0.*", default-features = false }
jounathaen commented 2 months ago

Ok, apparently the error is, that a trailing 0 in the vector m is missing. The above example works if m.push(0).unwrap(); is added before the from_bytes(&m).