Need to de-/serializer that supports read_exact and read_until when use on Vec<u8>

I have input handlers that parse TCP packets (packet come to handler as Vec<u8>). I want to make this process more consice and handy, so I am looking for de-/serializer for Vec<u8> to deserialize cases like this:

let mut reader = Cursor::new(input.data.as_ref().unwrap()[2..].to_vec());

let code = reader.read_u8()?;

let mut server_ephemeral = vec![0u8; 32];
reader.read_exact(&mut server_ephemeral)?;
let g_len = reader.read_u8()?;
let mut g: Vec<u8> = vec![0u8; g_len as usize];
reader.read_exact(&mut g)?;
let n_len = reader.read_u8()?;
let mut n: Vec<u8> = vec![0u8; n_len as usize];
reader.read_exact(&mut n)?;
let mut salt = vec![0u8; 32];
reader.read_exact(&mut salt)?;

or serialize cases like this into json string:

let mut header = Vec::new();
header.write_u8(Opcode::LOGIN_PROOF)?;

let mut body = Vec::new();
body.write_all(&srp_client.public_ephemeral())?;
body.write_all(&proof)?;
body.write_all(&crc_hash)?;
body.write_u8(0)?; // number of keys
body.write_u8(0)?; // security flags

Do somebody know if there some library to solve cases like this ? I need deserializer that will consider that I use read_until or read_exact.

Have you looked at the bincode crate?

1 Like

Thank you very much ! Seems like this is what I need

do you know btw does bincode allow to handle cases when I need to use one of the parsed field as size for parsing specific field ? Like this:

let size = reader.read_u32::<LittleEndian>()?;
let mut message = vec![0u8; (size - 1) as usize];
reader.read_exact(&mut message)?;

I found the solution like described here: rust - How can I deserialize a bincode field without a given length - Stack Overflow, but probably there another one exists (less verbose) ?

and also this solution not solve cases when need to get field with dynamic field size that located somewhere in the middle of bytes stream:

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Response {
    server_ephemeral: [u8; 32],
    g_len: u8,
    #[serde(skip)]
    g: Vec<u8>,
    n_len: u8,
    #[serde(skip)]
    n: Vec<u8>,
    salt: [u8; 32],
}

in code above I need to parse g_len to know how much bytes I need read next to parse g

Try the Box type