use std::error::Error; use std::fmt; use std::fs::File; use std::io::{self, BufRead}; use std::num; use std::path::Path; use std::str; pub struct Binary { pub words: Vec, } #[derive(Debug)] pub enum BinaryError { Io(io::Error), Utf8(str::Utf8Error), ParseInt(num::ParseIntError), } impl fmt::Display for BinaryError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { BinaryError::Io(ref err) => err.fmt(f), BinaryError::Utf8(ref err) => err.fmt(f), BinaryError::ParseInt(ref err) => err.fmt(f), } } } impl Error for BinaryError { fn description(&self) -> &str { match *self { BinaryError::Io(ref err) => err.description(), BinaryError::Utf8(ref err) => err.description(), BinaryError::ParseInt(ref err) => err.description(), } } } impl From for BinaryError { fn from(err: io::Error) -> BinaryError { BinaryError::Io(err) } } impl From for BinaryError { fn from(err: str::Utf8Error) -> BinaryError { BinaryError::Utf8(err) } } impl From for BinaryError { fn from(err: num::ParseIntError) -> BinaryError { BinaryError::ParseInt(err) } } impl Binary { pub fn new_from_hex_file(path: &Path) -> Result { let file = try!(File::open(path)); let file = io::BufReader::new(file); let mut words: Vec = Vec::new(); for line in file.lines() { let line = try!(line); for bytes in line.as_bytes().chunks(8).rev() { let word = try!(str::from_utf8(bytes)); words.push(try!(u32::from_str_radix(word, 16))); } } Ok(Binary { words: words, }) } }