Crate read_restrict

Source
Expand description

§read-restrict

An adaptor around Rust’s standard io::Take which instead of returning Ok(0) when the read limit is exceeded, instead returns an error of of the kind ErrorKind::InvalidData.

This is intended for enforcing explicit input limits when simply truncating with take could result in incorrect behaviour.

read_restrict also offers restricted variants of std::fs::read and std::fs::read_to_string, to conveniently prevent unbounded reads of overly-large files.

§Examples

use std::io::{self, Read, ErrorKind};

use read_restrict::ReadExt;

fn main() -> io::Result<()> {
    let f = std::fs::File::open("foo.txt")?;
    let mut handle = f.restrict(5);
    let mut buf = [0; 8];
    assert_eq!(5, handle.read(&mut buf)?); // reads at most 5 bytes
    assert_eq!(0, handle.restriction()); // is now exhausted
    assert_eq!(ErrorKind::InvalidData, handle.read(&mut buf).unwrap_err().kind());
    Ok(())
}
fn load_config(path: &std::path::Path) -> std::io::Result<String> {
    // No sensible configuration is going to exceed 640 KiB
    let conf = read_restrict::read_to_string(&path, 640 * 1024)?;
    // probably want to parse it here
    Ok(conf)
}

Structs§

  • Reader adaptor which restricts the bytes read from an underlying reader, returning an IO error of the kind ErrorKind::InvalidData when it is exceeded.

Traits§

Functions§

  • Read the entire contents of a file into a bytes vector, provided it fits within a specified size limit.
  • Read the entire contents of a file into a string, provided it fits within a specified size limit.