[−][src]Trait read_from::ReadFrom
Used to deserialize types from an input stream (i.e. a Read
implementation).
Example
This implements ReadFrom
for a simple TinyRational
struct.
use read_from::ReadFrom; use std::io::{self, Cursor, Read}; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TinyRational { numer: i8, denom: u8 } #[derive(Debug)] pub enum TinyRationalReadError { DenomIsZero, Io(io::Error) } impl ReadFrom for TinyRational { type Error = TinyRationalReadError; fn read_from<R: Read>(mut inp: R) -> Result<Self, Self::Error> { let mut buf = [0; 2]; inp.read_exact(&mut buf).map_err(TinyRationalReadError::Io)?; let numer = buf[0] as i8; let denom = buf[1] as u8; if denom == 0 { Err(TinyRationalReadError::DenomIsZero) } else { Ok(Self { numer, denom }) } } } assert_eq!( TinyRational::read_from(Cursor::new(&[3, 4])).unwrap(), TinyRational { numer: 3, denom: 4 }); assert!(matches!( TinyRational::read_from(Cursor::new(&[3, 0])).unwrap_err(), TinyRationalReadError::DenomIsZero ));
Associated Types
type Error
What error can happen when trying to read?
Required methods
fn read_from<R: Read>(input: R) -> Result<Self, Self::Error>
Attempts to construct Self
from the given input stream.