Trait handy_async::io::ReadFrom
[−]
[src]
pub trait ReadFrom<R: Read>: AsyncMatch<PatternReader<R>> { fn read_from(self, reader: R) -> ReadPattern<Self, R> { ... } fn sync_read_from(self, reader: R) -> Result<Self::Value> { ... } fn into_stream(self, reader: R) -> ReadStream<R, Self>
where
Self: Clone, { ... } }
The ReadFrom
trait allows for reading a value of the pattern from a source asynchronously.
Notice
For executing asynchronously, we assume the writer R
returns
the std::io::ErrorKind::WouldBlock
error if a read operation would be about to block.
Examples
Defines your own reading pattern:
use std::io::{Read, Error, ErrorKind}; use futures::{Future, BoxFuture}; use handy_async::io::{ReadFrom, PatternReader, AsyncIoError}; use handy_async::pattern::Pattern; use handy_async::matcher::AsyncMatch; // Defines pattern. struct HelloWorld; impl Pattern for HelloWorld { type Value = Vec<u8>; } // Implements pattern maching between `PatternReader<R>` and `HelloWorld`. impl<R: Read + Send + 'static> AsyncMatch<PatternReader<R>> for HelloWorld { type Future = BoxFuture<(PatternReader<R>, Vec<u8>), AsyncIoError<PatternReader<R>>>; fn async_match(self, matcher: PatternReader<R>) -> Self::Future { let buf = vec![0; b"Hello World!".len()]; buf.and_then(|b| if b == b"Hello World!" { Ok(b) } else { Err(Error::new(ErrorKind::InvalidData, format!("Unexpected bytes {:?}", b)) ) }).async_match(matcher).boxed() } } // Executes pattern matchings. // matched let pattern = (vec![0; 5], HelloWorld); let (rest, value) = pattern.read_from(&b"Hey! Hello World!!!"[..]).wait().unwrap(); assert_eq!(value.0, b"Hey! "); assert_eq!(value.1, b"Hello World!"); assert_eq!(rest, b"!!"); // unmatched let pattern = (vec![0; 5], HelloWorld); let e = pattern.read_from(&b"Hey! Hello Rust!!!"[..]).wait().err().unwrap(); assert_eq!(e.error_ref().kind(), ErrorKind::InvalidData);
Provided Methods
fn read_from(self, reader: R) -> ReadPattern<Self, R>
Creates a future instance to read a value of the pattern from reader
.
Examples
use handy_async::io::ReadFrom; use handy_async::pattern::{Pattern, Endian}; use handy_async::pattern::read::{U8, U16}; use futures::Future; let mut input = &[1, 0, 2][..]; let pattern = (U8, U16.be()); let future = pattern.read_from(&mut input); assert_eq!(future.wait().unwrap().1, (1, 2));
fn sync_read_from(self, reader: R) -> Result<Self::Value>
Synchronous version of the ReadFrom::read_from
method.
fn into_stream(self, reader: R) -> ReadStream<R, Self> where
Self: Clone,
Self: Clone,
Consumes this pattern and the reader
,
returning a stream which will produce a sequence of read values.
Examples
use futures::{Future, Stream}; use handy_async::pattern::read::U8; use handy_async::io::ReadFrom; let values = U8.into_stream(&b"hello"[..]).take(3).collect().wait().unwrap(); assert_eq!(values, b"hel");
Implementors
impl<R: Read, T> ReadFrom<R> for T where
T: AsyncMatch<PatternReader<R>>,