The ledger reads batches from a stream it does not control. read_line and read_until keep appending until they find a newline, so a single line of 2 GB with no newline means a 2 GB allocation, and checking the length afterward is too late. The limit has to be enforced while reading, not after.
The Read adapter take(n) wraps a reader and reports end of input after n bytes, so read_until can never append more than that. The trick is to allow one byte more than the limit. Reading exactly limit bytes cannot tell a line that is exactly at the limit from one that continues past it; reading limit + 1 can, because the extra byte only arrives if the line is too long. The newline counts toward the limit, since it is part of what was read. limit + 1 is computed with checked_add, so even usize::MAX as a limit gives an error instead of an overflow.
Predict and run
How many bytes are consumed from the oversized line?
use std::io::{self, BufRead, Read};
fn bounded_line(input: &mut impl BufRead, limit: usize) -> io::Result<Option<Vec<u8>>> {
let mut bytes = Vec::new();
let read_limit = limit.checked_add(1)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "limit too large"))?;
let count = input.take(read_limit as u64).read_until(b'\n', &mut bytes)?;
if count == 0 { return Ok(None); }
if count > limit {
return Err(io::Error::new(io::ErrorKind::InvalidData, "line too long"));
}
Ok(Some(bytes))
}
fn main() {
let mut input = io::Cursor::new(b"abcdef");
assert!(bounded_line(&mut input, 4).is_err());
println!("Consumed: {}", input.position());
println!("{:?}", bounded_line(&mut io::Cursor::new(b"abc\n"), 4).unwrap());
}Check your prediction
Consumed: 5
Some([97, 98, 99, 10])take(5) let exactly five bytes through, abcde, and the count of 5 exceeded the limit of 4. The sixth byte was never read, which the Cursor position proves. The second call accepted abc plus its newline, four bytes in all. Notice that take consumes its receiver: here the receiver is the &mut reference, not the reader itself, so the reader survives the call with its position advanced. Before reading on, predict the result for an empty stream and for abcd with no newline.
Probe every boundary
An empty stream and a final line without a newline look similar but mean different things: the first is the end of input, the second is a real line that happens to be last. The function returns None only when zero bytes were read.
use std::io::{self, BufRead, Read};
fn bounded_line(input: &mut impl BufRead, limit: usize) -> io::Result<Option<Vec<u8>>> {
let mut bytes = Vec::new();
let read_limit = limit.checked_add(1)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "limit too large"))?;
let count = input.take(read_limit as u64).read_until(b'\n', &mut bytes)?;
if count == 0 { return Ok(None); }
if count > limit {
return Err(io::Error::new(io::ErrorKind::InvalidData, "line too long"));
}
Ok(Some(bytes))
}
fn main() {
let cases: [&[u8]; 5] = [b"", b"abcd", b"abc\n", b"abcd\n", b"abcde"];
for case in cases {
let outcome = match bounded_line(&mut io::Cursor::new(case), 4) {
Ok(None) => String::from("end of input"),
Ok(Some(line)) => format!("line of {} bytes, newline: {}", line.len(), line.ends_with(b"\n")),
Err(error) => format!("error: {error}"),
};
println!("{:<8} {outcome}", format!("\"{}\"", case.escape_ascii()));
}
let huge = bounded_line(&mut io::Cursor::new(b"x"), usize::MAX);
println!("limit usize::MAX: {}", huge.unwrap_err());
}"" end of input
"abcd" line of 4 bytes, newline: false
"abc\n" line of 4 bytes, newline: true
"abcd\n" error: line too long
"abcde" error: line too long
limit usize::MAX: limit too largeThe fourth case is the one people get wrong: abcd fits in four bytes, but with its newline it is five, and five is over the limit. Whether that is right depends on the format you specify. If the limit is meant to cover only the content, read limit + 2 bytes and strip the newline before comparing; either way, decide once and test both sides of the line. escape_ascii prints \n as two visible characters, which keeps the output on one line per case.
Why stop instead of skipping or truncating
After the error, the stream is positioned in the middle of the rejected line. There are three ways to continue, each with a cost:
- Truncate and accept. Return the first
limitbytes as if they were the line. That silently turnsbolt 1000000intobolt 10, a wrong value that looks valid. Never do this for data. - Skip to the next newline. Discard bytes until a newline, then keep going. That is possible without allocating, by reading into a small fixed buffer, but a hostile stream with no newline still makes you read all of it.
- Stop. Return the error and let the caller abandon the stream. This is the simplest to reason about and bounds both memory and work, so this reader does it.
The ledger reads one batch per line and treats any oversized line as a rejected submission, so stopping is the right trade. A log viewer, which must show as much as it can, would choose skipping.
Measure consumption, not only results
A test that checks only for Err would pass even if the reader had swallowed the whole stream first. Check the reader's position too, as Cursor::position does here. That is the only observable proof that the bound held while reading.
Practice
Your turn
Using bounded_line with a limit of 4, check four cases: empty input returns None, abcd returns a 4-byte line, abc\n returns a 4-byte line, and abcdefghij returns an error. For the error case, prove that only five bytes were consumed even though the stream has ten. Print Line boundaries passed.
use std::io::{self, BufRead, Read};
fn bounded_line(input: &mut impl BufRead, limit: usize) -> io::Result<Option<Vec<u8>>> {
let mut bytes = Vec::new();
let read_limit = limit.checked_add(1)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "limit too large"))?;
let count = input.take(read_limit as u64).read_until(b'\n', &mut bytes)?;
if count == 0 { return Ok(None); }
if count > limit {
return Err(io::Error::new(io::ErrorKind::InvalidData, "line too long"));
}
Ok(Some(bytes))
}
fn main() {
// Add boundary checks using Cursor.
}Hint 1: the idea
The accepted length includes any newline read. For the oversized case, inspect Cursor::position as well as the returned error.
Hint 2: a first step
Create the long input as a named let mut input = io::Cursor::new(b"abcdefghij"); so it still exists after the call, then compare input.position() with 5.
Worked solution
use std::io::{self, BufRead, Read};
fn bounded_line(input: &mut impl BufRead, limit: usize) -> io::Result<Option<Vec<u8>>> {
let mut bytes = Vec::new();
let read_limit = limit.checked_add(1)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "limit too large"))?;
let count = input.take(read_limit as u64).read_until(b'\n', &mut bytes)?;
if count == 0 { return Ok(None); }
if count > limit {
return Err(io::Error::new(io::ErrorKind::InvalidData, "line too long"));
}
Ok(Some(bytes))
}
fn main() {
assert_eq!(bounded_line(&mut io::Cursor::new(b""), 4).unwrap(), None);
assert_eq!(bounded_line(&mut io::Cursor::new(b"abcd"), 4).unwrap().unwrap().len(), 4);
assert_eq!(bounded_line(&mut io::Cursor::new(b"abc\n"), 4).unwrap().unwrap().len(), 4);
let mut input = io::Cursor::new(b"abcdefghij");
let error = bounded_line(&mut input, 4).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
assert_eq!(input.position(), 5);
println!("Line boundaries passed");
}Line boundaries passedChecking error.kind() distinguishes an oversized line, InvalidData, from a bad limit, InvalidInput, without comparing message text. The position check is the real proof: five bytes read from a ten-byte stream shows the reader stopped at limit + 1, so a much longer line would cost no more memory. The checkpoint next feeds this bounded line into UTF-8 decoding and the fallible parser.
Completion is saved in this browser only. It does not measure mastery.