Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: How to deserialize distinct objects from the same file
I would like to serialize and then deserialize distinct objects in distinct parts of the same file, in RON format. So, I wrote this sample code:
use std::error::Error;
use std::fs::File;
use std::io::{BufReader, BufWriter, Read, Seek, Write};
const PATH: &str = "data.ron";
const SEPARATOR: &[u8] = b" something ";
fn serialize() -> Result<(), Box<dyn Error>> {
let file = File::create(PATH)?;
let mut writer = BufWriter::new(file);
ron::ser::to_writer(&mut writer, &"Hi")?;
writer.write(SEPARATOR)?;
ron::ser::to_writer(&mut writer, &12.30)?;
println!("Wrote file: {}", PATH);
Ok(())
}
fn deserialize() -> Result<(), Box<dyn Error>> {
let file = File::open(PATH)?;
let mut reader = BufReader::new(file);
let word: String = ron::de::from_reader(&mut reader)?;
reader.seek(std::io::SeekFrom::Current(SEPARATOR.len() as i64))?;
let number: f64 = ron::de::from_reader(&mut reader)?;
println!("Read back: {}, {}", word, number);
Ok(())
}
fn main() -> Result<(), Box<dyn Error>> {
serialize()?;
deserialize()?;
Ok(())
}
It can be compiled and run with these dependencies:
ron = "0.8"
serde = "1.0.219"
It prints this to the console:
Wrote file: data.ron
Error: SpannedError { code: TrailingCharacters, position: Position { line: 1, col: 6 } }
The generated file contains this:
"Hi" something 12.3
A first problem is that, if I set the dependency ron = "0.9"
or ron = "0.10.1"
, the program cannot be compiled anymore, because the trait bound `BufWriter<File>: std::fmt::Write` is not satisfied.
.
However, the biggest problem is that SpannedError
that I get after having deserialized the string "Hi"
.
2 posts - 2 participants
🏷️ Rust_feed