peekable-reader-rs

Build Status

A utility struct for Rust: a wrapper around any Reader, which allows for performing peek operations, along with the usual Reader methods.

Usage

For now, the PeekableReader exposes a single additional method: fn peek_byte(&mut self) -> IoResult<u8> which is analogous to the read_byte method exposed by the Reader trait, returning the result that the next read_byte will return. This allows the clients to check the result of the next read operation, without actually consuming the byte from the input.

The error semantics are such that any errors raised by the underlying wrapped Reader while performing a peek operation are always returned on a subsequent read method call, so as to perserve the invariant that the result of peek_byte is always the same as the result of the following read_byte operation.

Since the PeekableReader also implements the Reader trait, it is possible to seamlessly plug it in anywhere any other Reader implementation would fit.

``rust // Wrap anyReaderinstance into a PeekableReader. let mut peekable_reader = PeekableReader::new(MemReader::new(vec![1, 2, 3])); // Now we can peek at the next byte, without consuming it... let b = peekable_reader.peek_byte(); // Multiple calls ofpeekbytebefore a read always return the same result assert!(peekable_reader.peek_byte() == b); // ...the result of thepeekbyteis always exactly what the next //readbyte` call returns. assert!(peekablereader.read_byte() == b); assert!(b.unwrap() == 1);

// A peeked byte is always correctly included in a read, regardless of which // flavor of read is used from the Reader trait. let _ = peekablereader.peekbyte(); // (e.g. read into a buffer) let mut buffer: Vec = vec![0, 0]; peekablereader.read(buffer.asmutslice()); asserteq!(vec![2, 3], buffer);

// Peeking at the end returns an EOF assert!(match peekablereader.peekbyte() { Err(IoError { kind: IoErrorKind::EndOfFile, .. }) => true, _ => false, }); ```

License

MIT