I have a struct containing a byte array that I would like to serialize and deserialize to and from binary, but it only works for arrays up to 32 elements.
Here is my minimal example code
main.rs:
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate bincode;
use bincode::{serialize, deserialize, Infinite};
const BYTECOUNT: usize = 32; // 33 and more does not work, I need 128
type DataArr = [u8; BYTECOUNT];
#[derive(Serialize, Deserialize, Debug)]
struct Entry {
number: i64,
data: DataArr
}
fn main() {
let mut my_entry = Entry { number: 12345, data: [0; BYTECOUNT] };
my_entry.data[4] = 42;
// Convert the Entry to binary.
let serialized: Vec<u8> = serialize(&my_entry, Infinite).unwrap();
println!("serialized = {:?}", serialized);
// Convert the binary representation back to an Entry.
let deserialized: Entry = deserialize(&serialized).unwrap();
println!("deserialized = {:?}", deserialized);
}
Cargo.toml
:
[package]
name = "array_serialization_test"
version = "0.1.0"
[dependencies]
serde = "*"
serde_derive = "*"
bincode = "*"
output:
serialized = [57, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
deserialized = Entry { number: 12345, data: [0, 0, 0, 0, 42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
How can I make it work for 128 elements in the array? Can I somehow manually extend array_impls!
in my user code? Is there an alternative approach?
I think this question is different from How do I map a C struct with padding over 32 bytes using serde and bincode? because I actually need the content of the array, since it is not just used for padding. Also I would like to know if I can extend array_impls!
on my code.
See Question&Answers more detail:
os