Enforce a strict limit on the number of bytes read from a Read
with an error
when exceeded.
```rust
pub trait ReadExt {
fn restrict(self, restriction: u64) -> Restrict
impl
impl
impl
This is a modified version of Rust's stdlib Read::take
implementation which
returns an error when its limit is exceeded. Reads operate as normal, bound
strictly to the read limit, following which io::ErrorKind::InvalidData
will
be returned.
```rust use std::io::{self, ErrorKind, Result}; use std::io::prelude::*; use std::fs::File; use read_restrict::ReadExt;
fn main() -> io::Result<()> { let f = File::open("foo.txt")?.restrict(5); let mut handle = f.restrict(5); let mut buf = [0; 8]; asserteq!(5, handle.read(&mut buf)?); // reads at most 5 bytes asserteq!(0, handle.restriction()); // is now exhausted asserteq!(ErrorKind::InvalidData, handle.read(&mut buf).unwraperr().kind()); Ok(()) } ```