diff --git a/src/elements/mod.rs b/src/elements/mod.rs index 4dd2f87..7e1bd9f 100644 --- a/src/elements/mod.rs +++ b/src/elements/mod.rs @@ -255,33 +255,23 @@ pub fn serialize(val: T) -> Result, T::Error> { Ok(buf) } -/// Deserialize module from file. +/// Deserialize module from the file. #[cfg(feature = "std")] pub fn deserialize_file>(p: P) -> Result { - use std::io::Read; - - let mut contents = Vec::new(); - - ::std::fs::File::open(p) - .and_then(|mut f| f.read_to_end(&mut contents)) + let mut f = ::std::fs::File::open(p) .map_err(|e| Error::HeapOther(format!("Can't read from the file: {:?}", e)))?; - deserialize_buffer(&contents) + Module::deserialize(&mut f) } /// Serialize module to the file #[cfg(feature = "std")] pub fn serialize_to_file>(p: P, module: Module) -> Result<(), Error> { - use std::io::Write; - let mut io = ::std::fs::File::create(p) - .map_err(|e| Error::HeapOther(format!("Can't create the file: {:?}", e)))?; - let mut buf = Vec::new(); - - module.serialize(&mut buf)?; - - io.write_all(&buf) - .map_err(|e| Error::HeapOther(format!("Can't write to the file: {:?}", e)))?; + .map_err(|e| + Error::HeapOther(format!("Can't create the file: {:?}", e)) + )?; + module.serialize(&mut io)?; Ok(()) } diff --git a/src/io.rs b/src/io.rs index c6730bb..45db600 100644 --- a/src/io.rs +++ b/src/io.rs @@ -3,10 +3,8 @@ //! Basically it just a replacement for the std::io that is usable from //! the `no_std` environment. -use std::vec::Vec; - /// IO specific error. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug)] pub enum Error { /// Some unexpected data left in the buffer after reading all data. TrailingData, @@ -16,6 +14,9 @@ pub enum Error { /// Invalid data is encountered. InvalidData, + + #[cfg(feature = "std")] + IoError(::std::io::Error), } /// IO specific Result. @@ -35,13 +36,6 @@ pub trait Read { fn read(&mut self, buf: &mut [u8]) -> Result<()>; } -impl Write for Vec { - fn write(&mut self, buf: &[u8]) -> Result<()> { - self.extend(buf); - Ok(()) - } -} - /// Reader that saves the last position. pub struct Cursor { inner: T, @@ -75,6 +69,29 @@ impl> Read for Cursor { } } +#[cfg(not(feature = "std"))] +impl Write for ::std::vec::Vec { + fn write(&mut self, buf: &[u8]) -> Result<()> { + self.extend(buf); + Ok(()) + } +} + +#[cfg(feature = "std")] +impl Read for T { + fn read(&mut self, buf: &mut [u8]) -> Result<()> { + self.read_exact(buf) + .map_err(Error::IoError) + } +} + +#[cfg(feature = "std")] +impl Write for T { + fn write(&mut self, buf: &[u8]) -> Result<()> { + self.write_all(buf).map_err(Error::IoError) + } +} + #[cfg(test)] mod tests { use super::*;