expression

Bound each input record before parsing

A streaming reader can still allocate too much for a single record. Limit each read to one byte more than the maximum, including its line terminator. On oversize stop processing rather than interpreting the rest as a new record. Fixture: Expected stdout (not executed): ok record too large Expected stderr: (empty) Expected exit: 0 Common mistake: Using lines() alone as a memory bound, or resuming after rejecting only the prefix of a long record.

Formal Syntax & Structure

rust syntaxrust
reader.by_ref().take(MAX + 1).read_until(b'\n', &mut record)

Working Example

Example Snippetrust
fn main() {    use std::io::{BufRead, Read, Cursor};    let mut reader = Cursor::new(b"ok\n123456789\n");    const MAX: u64 = 8;    let mut record = Vec::new();    loop {        record.clear();        let n = reader.by_ref().take(MAX + 1).read_until(b'\n', &mut record).unwrap();        if n == 0 { break; }        if n as u64 > MAX { println!("record too large"); break; }        print!("{}", std::str::from_utf8(&record).unwrap());    }}
Rust Reference