我有一个包含字节数组的结构,我想对二进制进行序列化和反序列化,但它仅适用于最多 32 个元素的数组。
这是我的最小示例代码
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 = "*"
输出:
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]
如何使它适用于数组中的 128 个元素?我可以以某种方式手动扩展array_impls!
我的用户代码吗?有替代方法吗?
我认为这个问题不同于How do I map a C struct with padding over 32 bytes using serde and bincode? 因为我实际上需要数组的内容,因为它不仅仅用于填充。另外我想知道我是否可以扩展array_impls!
我的代码。