我有以下 struct
struct Employee {
id: u64,
name: String,
}
我正在使用以下代码对其进行序列化,然后将序列化的字节数组写入文件:
let emp = Employee {
id: 1546,
name: "abcd".to_string(),
};
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open("hello.txt")
.unwrap();
let initial_buf = &bincode::serialize(&emp).unwrap();
println!("Initial Buf: {:?}", initial_buf);
file.write(&initial_buf);
file.write(&[b'\n']);
file.flush();
file.seek(SeekFrom::Start(0)).unwrap();
let mut final_buf: Vec<u8> = Vec::new();
let mut reader = BufReader::new(file);
reader.read_until(b'\n', &mut final_buf).unwrap();
println!("Final Buf: {:?}", final_buf);
我得到以下输出:
Initial Buf: [10, 6, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 97, 98, 99, 100]
Final Buf: [10]
Bincode的约定是,您给它一个要序列化的值,并且给您返回字节。合同不保证您返回的字节不能包含换行符。
在您的数据中,整数1546为0x60A,表示为字节[10, 6, 0, 0]
。
您应该可以使用Bincode数据而无需任何分隔符。该bincode::deserialize_from
功能将知道在哪里停止阅读。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句