Reuse One Buffer With BufReader::read_until
Stream byte records via BufReader::read_until into a single cleared Vec<u8> buffer, validating UTF-8 and checking capacity without per-line allocations.
Code
use std::io::{self, BufRead, BufReader, Cursor};
fn parse_lines<R: BufRead>(reader: &mut R) -> io::Result<(Vec<String>, usize)> {
let mut buf = Vec::with_capacity(64);
let mut records = Vec::new();
loop {
buf.clear();
let bytes = reader.read_until(b'\n', &mut buf)?;
if bytes == 0 {
break;
}
while matches!(buf.last(), Some(&b'\n') | Some(&b'\r')) {
buf.pop();
}
let line = std::str::from_utf8(&buf)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
if !line.is_empty() {
records.push(line.to_owned());
}
}
Ok((records, buf.capacity()))
}
fn main() -> io::Result<()> {
let raw = b"event:login\r\nevent:purchase\n\nevent:logout";
let mut reader = BufReader::with_capacity(16, Cursor::new(raw));
let (records, cap) = parse_lines(&mut reader)?;
println!("parsed {} records: {records:?}", records.len());
println!("reused buffer capacity stayed at {cap} bytes");
Ok(())
}Annotated execution — Reuse One Buffer With BufReader::read_until
Under the hood: the functions parse_lines and main.
The file repeats itself only inside while matches!(buf.last(), Some(&b'\n') | Some(&b'\r')). Fallible operations return Result, and the ? operator short-circuits errors up to the caller.
Caveats
- Zero setup installs required; every referenced symbol arrives with the platform.
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Using it
The run prints parsed, reused buffer capacity stayed at — each prefix names the step that produced it.
Running the file executes main, which drives parse_lines in order.
Key statements
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
while matches!(buf.last(), Some(&b'\n') | Some(&b'\r')) {
buf.pop();
}
let bytes = reader.read_until(b'\n', &mut buf)?;
Interactive Tools for This Topic
FAQ
- How are errors reported?
- Through `Result` values propagated with the `?` operator. Nothing panics inside the snippet; the caller decides how to handle each failure.
- What does Reuse One Buffer With BufReader::read_until print when run?
- Run it as a complete program — the output lines carry labels such as `parsed`, `reused buffer capacity stayed at`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.