Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deserialize a bincode field without a given length

So I'm trying to deserialize a message consisting of binary data (bincode), this binary isn't serialized by serde but I'm trying to use serde to deserialize it. However, the data send optionally has a raw data section at the end of which the length isn't prefixed but is guaranteed to be the rest of the message. Serde always expects a length. I can't add the length due to backwards compatability concerns with a system not made/designed by me, this compat is important. Is this possible to achieve with Serde and how would I go about doing that?

I've already looked at the docs for serde and bincode and couldn't find anything in there to help me.

like image 923
0x76 Avatar asked May 17 '19 14:05

0x76


1 Answers

bincode::deserialize_from lets you retain any trailing data in the input stream.


use serde::Deserialize;

#[derive(Deserialize, Debug)]
struct Data {
    q: String,
    r: i32,

    #[serde(skip)]
    trailing: Vec<u8>,
}

fn main() -> bincode::Result<()> {
    let bytes = [7, 0, 0, 0, 0, 0, 0, 0, 115, 117, 99, 99, 101, 115, 115, 227, 7, 0, 0, 3, 2, 1];

    let mut cursor = &bytes[..];
    let mut data: Data = bincode::deserialize_from(&mut cursor)?;
    data.trailing = cursor.to_owned();

    println!("{:#?}", data);
    Ok(())
}
like image 58
dtolnay Avatar answered Oct 05 '22 12:10

dtolnay