Expand description
qread
adds shortcut functionality to anything that implements the std::io::Read
or std::io::BufRead
traits to make certain read operations more ergonomic by handling
allocation of a buffer for you. Specifically, Read
implementors get two new methods:
read_all_to_bytes
, which calls.read_to_end()
on the object and returns the vector of bytes gotten from reading the object.read_all_to_string
, which calls.read_to_string()
on the object and returns the string created.
Likewise, ReadBuf
implementors also get two new methods:
read_until_to_bytes
, which calls.read_until()
on the object and returns the vector of bytes gotten from the object.read_line_to_string
which calls.read_line()
on the object and returns the line as a string (note that it will include the newline).
Examples
Using read_all_to_bytes
and read_all_to_string
to read the full
contents of a file as a vector of bytes or a string, respectively, is very straightforward. Note that these are both members
of the QRead
trait, so that trait must be brought into scope to use these methods.
use std::fs::File;
use qread::QRead;
// This assumes that we have a file `demo.bin` in the current directory
let mut f1 = File::open("demo.bin").unwrap();
let data = f1.read_all_to_bytes().unwrap();
// This assumes that we have a file `demo.txt` in the current directory
let mut f2 = File::open("demo.txt").unwrap();
let text = f2.read_all_to_string().unwrap();
Likewise, the read_until_to_bytes
and read_line_to_string
methods are also straightforward, provided that the QBufRead
trait is in scope.
use std::fs::File;
use std::io::BufReader;
use qread::QBufRead;
// This assumes that we have a file `demo.bin` in the current directory
let mut f1 = BufReader::new(File::open("demo.bin").unwrap());
// Read up to the first instance of byte = 97 (a lowercase ASCII "a")
let data = f1.read_until_to_bytes(97).unwrap();
// This assumes that we have a file `demo.txt` in the current directory
let mut f2 = BufReader::new(File::open("demo.txt").unwrap());
let text = f2.read_line_to_string().unwrap();
Implementing QRead
and QBufRead
You should not need to implement these traits on your own custom objects. Instead, implement Read
and BufRead
, respectively. Because QRead
and QBufRead
have blanket implementations for
any types implementing Read
and BufRead
, respectively, implementing the latter traits automatically grants the former.
Traits
- Trait for implementing ergonomic reads of buffered file content
- Trait for implementing ergonomic reads of full file content