Skip to content

Checkpoint: Parse One Bounded Batch

The Course
•
35 min study

This checkpoint builds the front door of the ledger: the function that turns raw bytes from a stream into a batch of quantities. It is a pipeline of three stages, and each one rejects a different kind of bad input. The bounded reader limits how much memory a hostile line can cost. UTF-8 decoding rejects bytes that are not text. The fallible collection rejects any entry that is not a number, and returns nothing at all unless every entry is good. Each stage's error should say which stage failed, so a person can fix the input.

What you will use

  • bounded_line. Read at most the limit plus one byte, so an oversized line is detected without reading the rest of the stream.
  • ok_or on an Option. Turn "no line at all" into an error, because an empty submission is not a valid batch.
  • String::from_utf8. Take ownership of the bytes and give them back as a String only if they are valid UTF-8.
  • Collecting into a Result. Parse each comma-separated entry and stop at the first bad one, with its position in the message.
  • map_err for context. Turn each stage's error into a String that names the stage or entry.

Plan before you type

  1. Write batch(input: &mut impl BufRead) -> Result<Vec<u32>, String> with a limit of 16 bytes including the newline.
  2. Call bounded_line, map its error to a String, and turn None into "missing batch".
  3. Decode with String::from_utf8, prefixing its error with not UTF-8: .
  4. Trim the text, split on commas, enumerate the parts, and parse each trimmed part as u32, prefixing errors with entry N: counting from 1.
  5. In main, print the outcome for each case in the exercise.
Prove each stage rejects its own input

Give every bad case exactly one defect and check that the message names the right stage. If the oversized line reports entry 1: ..., the length check is not running before parsing. If the exactly-16-byte line is rejected, the limit is off by one, probably because the newline was not counted or limit + 1 became limit.

Mistakes worth checking for

  • An empty input returns Ok([]) or a parse error: None from the reader was not turned into an error, or empty text reached split, which yields one empty part.
  • 2,,4 is accepted as [2, 4]: empty parts are being filtered out. An empty entry is a mistake in the batch, so let it fail.
  • Entry positions start at 0: people count from 1, so add 1 to the enumerate index.
  • A line with a trailing \r\n fails on its last entry: trimming the whole text first removes both characters. Trimming only \n would not.
Exercise

Your turn

Write batch as planned and print the outcome, one line each, for these inputs: 2, 4\n, 100,200,300,400\n (exactly 16 bytes), the single byte 255, 2,bad, 2,,4, the 17-byte line 12345678901234567, and empty input. Print a successful batch with {:?} and an error with Error: followed by the message.

Your working space Rust
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() {
    // Use the bounded reader, then validate the complete line.
}
Hint 1: the idea

Each stage turns its own error into a String with map_err, and ? passes it straight out. Change no external state during parsing; the whole function is pure apart from reading.

Hint 2: a first step

bounded_line(input, 16).map_err(|error| error.to_string())?.ok_or("missing batch")? gives you the bytes. ? converts the &str from ok_or into a String because String implements From for &str.

Worked solution
Run the solution Rust
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 batch(input: &mut impl BufRead) -> Result<Vec<u32>, String> {
    let bytes = bounded_line(input, 16).map_err(|error| error.to_string())?
        .ok_or("missing batch")?;
    let text = String::from_utf8(bytes).map_err(|error| format!("not UTF-8: {error}"))?;
    text.trim().split(',').enumerate().map(|(index, part)| {
        part.trim().parse::<u32>().map_err(|error| format!("entry {}: {error}", index + 1))
    }).collect()
}

fn main() {
    let cases: [&[u8]; 7] = [
        b"2, 4\n",
        b"100,200,300,400\n",
        &[255],
        b"2,bad",
        b"2,,4",
        b"12345678901234567",
        b"",
    ];
    for case in cases {
        match batch(&mut io::Cursor::new(case)) {
            Ok(values) => println!("{values:?}"),
            Err(message) => println!("Error: {message}"),
        }
    }
}
Text
[2, 4]
[100, 200, 300, 400]
Error: not UTF-8: invalid utf-8 sequence of 1 bytes from index 0
Error: entry 2: invalid digit found in string
Error: entry 2: cannot parse integer from empty string
Error: line too long
Error: missing batch

Every bad case fails in a different stage, and the message says which. The 16-byte line passes and the 17-byte line fails, which pins the limit to exactly where the plan put it; the oversized line never reached decoding, so no part of it was parsed. Returning String errors keeps this checkpoint short, but it throws away structure: a caller cannot ask which entry failed without parsing the message. On Day 5 you will replace these strings with an error type that keeps the stage and position as fields.

Was this article helpful?

Your response is saved on this device.