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
A thin wrapper around [io::Take
] - instead of returning Ok(0)
when exhausted,
a Restrict
returns an error of the kind [ErrorKind::InvalidData
].
This is intended for enforcing explicit input limits when simply truncating with
take
could result in incorrect behaviour.
```rust use std::io::{Read, Result, ErrorKind}; use read_restrict::ReadExt;
fn main() -> Result<()> { let f = std::fs::File::open("foo.txt")?; 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(()) } ```
Or more realistically:
```rust use read_restrict::ReadExt;
fn main() -> std::io::Result<()> { let input = std::fs::File::open("foo.json")?; let input = std::io::BufReader::new(input); // buffer for performance let input = input.restrict(640 * 1024); // 640k should be enough JSON for anyone let data = serdejson::from_reader(input)?; Ok(()) } ```