Skip to content

Instantly share code, notes, and snippets.

@taylorsmithgg
Created April 23, 2017 12:51
Show Gist options
  • Save taylorsmithgg/ba7b070c0964aa8b86d311ab6f8f5508 to your computer and use it in GitHub Desktop.
Save taylorsmithgg/ba7b070c0964aa8b86d311ab6f8f5508 to your computer and use it in GitHub Desktop.
Save and load from binary in Rust
fn write_binary(vector: Vec<u8>) -> Result<(), std::io::Error> {
let mut f = OpenOptions::new()
.create(true)
.write(true)
.read(true)
.open("foo.bin")
.unwrap();
println!("The file: {:?}", f);
println!("Writing: {:?}", &vector[..]);
let write_result = f.write(&vector[..]).unwrap();
Ok(())
}
fn load_binary() -> Result<(), std::io::Error> {
let mut f = OpenOptions::new()
.read(true)
.open("foo.bin")
.unwrap();
println!("The file: {:?}", f);
let num_bytes = f.metadata().unwrap().len() as usize;
println!("Metadata: {:?}", f.metadata());
let mut buffer = vec![0; num_bytes];
// read up to 10 bytes
let read_result = f.read_to_end(&mut buffer).unwrap();
println!("Read Buffer: {:?}", &buffer[..]);
let decoded: World = deserialize(&buffer[..]).unwrap();
println!("Decoded: {:?}", decoded);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment