I have an issue with deserealizing the struct with field that contains dynamic size (to be exactly, size of this field should be received from another field of same struct):
struct Response {
server_ephemeral: [u8; 32],
g_len: u8,
g: [u8; g_len as usize], // you can't use a variable as the length of an array
n_len: u8,
n: Vec<u8>,
salt: [u8; 32],
}
you should just use a Vec, or if you don't want the complexity of a vec: a Box<[u8]>.
Second, if deriving those traits isn't working, you can implement them yourself.
bincode serializes collections with a length prefix. If you control the data format you can just replace each length / array pair of fields with a single Vec.
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Response {
server_ephemeral: [u8; 32],
g: Vec<u8>,
n: Vec<u8>,
salt: [u8; 32],
}
fn main() {
let value = Response {
server_ephemeral: [100; 32],
g: vec![1, 2, 3, 4],
n: vec![5, 6, 7, 8],
salt: [1; 32],
};
let data = bincode::serialize(&value).unwrap();
let result = bincode::deserialize(&data).unwrap();
assert_eq!(value, result)
}
Rust doesn't have any way to support variable size structs the way you would require with your original struct.
You could create a custom type that wraps an array with a fixed maximum size and serializes / deserializes only the parts that are used. That is almost certainly unnecessary complexity here though.
Serde's data model doesn't allow that. Bincode is not a general-purpose parser for foreign data formats, but a parser for its own format, with lengths specified in bincode's way. The variable-length field in bincode could be Vec<u8>.