Skip to content

Instantly share code, notes, and snippets.

@bddap
Created August 27, 2019 20:33
Show Gist options
  • Save bddap/7a65f7c276c65662aa7d8b37d1cf944a to your computer and use it in GitHub Desktop.
Save bddap/7a65f7c276c65662aa7d8b37d1cf944a to your computer and use it in GitHub Desktop.
// bincode is a backend for serde. bincode can serialize and deserialize type that implement
// serde::Serialize and serde::Deserialize
use bincode;
// Bincode serializes into a binary format, but other backends exist to serialize into other
// formats, like json.
// make sure to add the following to your Cargo.toml
//
// [dependencies]
// bincode = "1"
// serde = { version = "1", features = ["derive"] }
fn main() {
using_vec();
custom_struct();
}
fn using_vec() {
let blocks: Vec<Vec<u8>> = vec![
vec![1, 2, 3],
vec![1, 2, 3, 4, 5],
vec![1, 2, b'c', 4],
vec![1, 2, 3, b'a'],
];
// write
let mut file = std::fs::File::create("blocks").unwrap();
bincode::serialize_into(&mut file, &blocks).unwrap();
drop(file); // close the file
// read
let file = std::fs::File::open("blocks").unwrap();
let read_blocks: Vec<Vec<u8>> = bincode::deserialize_from(&file).unwrap();
assert_eq!(blocks, read_blocks);
}
fn custom_struct() {
#[derive(PartialEq, Debug, serde::Serialize, serde::Deserialize)] // automatically implements serde for the type
struct Blocks {
blocks: Vec<Vec<u8>>,
metadata: String,
}
let blocks = Blocks {
blocks: vec![
vec![1, 2, 3],
vec![1, 2, 3, 4, 5],
vec![1, 2, b'c', 4],
vec![1, 2, 3, b'a'],
],
metadata: "you can use any type for metadata as long as it implements serde".to_string(),
};
// write
let mut file = std::fs::File::create("blocks").unwrap();
bincode::serialize_into(&mut file, &blocks).unwrap();
drop(file); // close the file
// read
let file = std::fs::File::open("blocks").unwrap();
let read_blocks: Blocks = bincode::deserialize_from(&file).unwrap();
assert_eq!(blocks, read_blocks);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment