63 lines
1.5 KiB
Rust
Raw Normal View History

2017-03-29 18:16:58 +03:00
use std::io;
mod module;
mod section;
2017-03-29 23:13:54 +03:00
mod primitives;
mod types;
2017-03-29 18:16:58 +03:00
pub use self::module::Module;
pub use self::section::Section;
2017-03-29 23:13:54 +03:00
pub use self::primitives::{VarUint32, VarUint7, VarUint1, VarInt7, Uint32, CountedList};
2017-03-29 18:16:58 +03:00
pub trait Deserialize : Sized {
type Error;
fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error>;
}
#[derive(Debug)]
pub enum Error {
UnexpectedEof,
InconsistentLength { expected: usize, actual: usize },
Other(&'static str),
HeapOther(String),
2017-03-29 23:13:54 +03:00
UnknownValueType(i8),
2017-03-29 18:16:58 +03:00
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::HeapOther(format!("I/O Error: {}", err))
}
}
struct Unparsed(pub Vec<u8>);
impl Deserialize for Unparsed {
type Error = Error;
fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
let len = VarUint32::deserialize(reader)?.into();
2017-03-29 19:40:51 +03:00
let mut vec = vec![0u8; len];
reader.read_exact(&mut vec[..])?;
2017-03-29 18:16:58 +03:00
Ok(Unparsed(vec))
}
}
2017-03-29 23:13:54 +03:00
impl From<Unparsed> for Vec<u8> {
fn from(u: Unparsed) -> Vec<u8> {
u.0
2017-03-29 18:16:58 +03:00
}
}
2017-03-29 23:13:54 +03:00
fn deserialize_file<P: AsRef<::std::path::Path>>(p: P) -> Result<Module, Error> {
use std::io::Read;
2017-03-29 18:16:58 +03:00
2017-03-29 23:13:54 +03:00
let mut contents = Vec::new();
::std::fs::File::open(p)?.read_to_end(&mut contents)?;
2017-03-29 18:16:58 +03:00
2017-03-29 23:13:54 +03:00
deserialize_buffer(contents)
2017-03-29 18:16:58 +03:00
}
2017-03-29 23:13:54 +03:00
fn deserialize_buffer<T: Deserialize>(contents: Vec<u8>) -> Result<T, T::Error> {
let mut reader = io::Cursor::new(contents);
T::deserialize(&mut reader)
}