Skip to content

Instantly share code, notes, and snippets.

@wfvining
Created April 1, 2017 02:08
Show Gist options
  • Save wfvining/0c9bea2eeaa7aadb42fa432b10650d49 to your computer and use it in GitHub Desktop.
Save wfvining/0c9bea2eeaa7aadb42fa432b10650d49 to your computer and use it in GitHub Desktop.
use std::io::Error as IOError;
use std::io::ErrorKind as IOErrorKind;
use std::io::{Seek, SeekFrom, Read, Write};
use std::fs::File;
use bincode::{
serialize,
deserialize,
deserialize_from,
serialized_size,
SizeLimit,
Infinite,
};
// Omitting Storage trait and impl Storage for File
#[derive(Serialize, Deserialize)]
struct Node<D> {
num_children: usize,
children: Vec<u64>,
data: Vec<D>,
}
impl<D> Node<D> {
fn load<S: Storage>(from: &mut S, at: u64) -> Result<Node<D>, IOError> {
// Do two `get`s from the storage. One to get the size, and
// one to read the data.
let header_size = serialized_size(&0u64);
let mut header_buffer = vec![0u8 ; header_size as usize];
try!(from.get(at, &mut header_buffer[..]));
let node_size: u64;
match deserialize(&header_buffer) {
Err(_deserialize_err) => {
// return Err(IOError::new(IOErrorKind::Other,
// deserialize_err.description())),
return Err(IOError::new(IOErrorKind::Other,
"failed to deserialize node header"));
},
Ok(s) => node_size = s,
}
let node_buffer = vec![0u8; node_size as usize];
try!(from.get(at + header_size, &mut node_buffer[..]));
deserialize(&node_buffer[..])
.map_err(|_|
IOError::new(IOErrorKind::Other,
"failed to deserialize node"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment