Skip to content

Checkpoint: Test the Whole Input Loop

The Course
•
30 min study

This checkpoint builds the skeleton of the reading queue's input loop, with a counter standing in for the queue. The loop reads commands from any BufRead, writes results to any Write, and treats two kinds of trouble differently. A bad command is the user's mistake: report it with its line number and keep going, without touching the state. A failed read or write is the environment's problem: stop and return the error to the caller.

You will prove both halves with checks that need no console. A fixture replayed into a vector shows that the bad line was reported and the count survived. A writer that always fails shows that an I/O error escapes run.

What you will use

  • impl BufRead and impl Write parameters: the caller chooses stdin and stdout, or a Cursor and a Vec<u8>.
  • lines().enumerate(): each line arrives with its zero-based index, assigned before any line is skipped.
  • line? and writeln!(...)?: I/O errors leave run immediately as an io::Result.
  • A match on the trimmed line: blank, add, count, and everything else, each with its own effect.
  • A full transcript comparison: assert_eq! on the whole captured string, final newline included.
  • A writer that refuses: a small type whose write returns BrokenPipe.

Plan before you type

  1. Start count at zero inside run, so every run begins fresh.
  2. Loop over input.lines().enumerate() and match on line?.trim().
  3. Ignore "", increment on add, write Count: N on count, and write Line N: unknown command for anything else.
  4. In main, replay the fixture into a Vec<u8>, convert it to a String, and assert the exact transcript.
  5. Add a ClosedPipe writer, run count into it, and assert that the error kind is BrokenPipe.
  6. Print the transcript so you can read it.
Prove it can fail

Make two deliberate changes and confirm a check stops each one. First, set count = 0 in the unknown-command branch: the transcript assertion should fail, showing Count: 0 where Count: 1 belongs. Second, ignore the write result in the count branch by writing let _ = writeln!(...): the BrokenPipe assertion should fail, because run now returns Ok. Restore both.

Mistakes worth checking for

  • The rejection says Line 2: blank lines were removed before enumerate, so the number counts surviving lines instead of input lines.
  • Only one Count: line appears: the error branch returns or breaks instead of continuing.
  • The assertion fails only at the very end: the expected string is missing its final \n; writeln! ends every line with one.
  • use of moved value on the output vector: you passed output instead of &mut output, so run took ownership of it.
  • The broken-pipe check reports Ok: a write result was discarded instead of propagated with ?.

Build it

Exercise

Your turn

Write run for the commands add and count. Start the count at zero, skip blank lines, and report anything else as Line N: unknown command using its original line number, then continue. Replay add\n\noops\ncount\nadd\ncount from memory and assert the exact transcript below. Then run count into a writer that always fails and assert the error kind is BrokenPipe. Print the transcript at the end:

Text
Line 3: unknown command
Count: 1
Count: 2
Your working space Rust
use std::io::{self, BufRead, Cursor, Write};

fn run(input: impl BufRead, mut output: impl Write) -> io::Result<()> {
    // Process add and count.
    Ok(())
}

fn main() -> io::Result<()> {
    let fixture = Cursor::new(b"add\n\noops\ncount\nadd\ncount");
    let mut output = Vec::new();
    run(fixture, &mut output)?;
    // Assert the transcript, check a failing writer, and print the transcript.
    Ok(())
}
Hint 1: the idea

Change the count only in the add branch. The unknown-command branch writes a message and lets the loop move to the next line.

Hint 2: a first step

Use for (index, line) in input.lines().enumerate() and match line?.trim(). For the failing writer, copy the ClosedPipe type from the previous write lesson.

Worked solution
Run the solution Rust
use std::io::{self, BufRead, Cursor, Write};

fn run(input: impl BufRead, mut output: impl Write) -> io::Result<()> {
    let mut count = 0;
    for (index, line) in input.lines().enumerate() {
        match line?.trim() {
            "" => {}
            "add" => count += 1,
            "count" => writeln!(output, "Count: {count}")?,
            _ => writeln!(output, "Line {}: unknown command", index + 1)?,
        }
    }
    Ok(())
}

struct ClosedPipe;

impl Write for ClosedPipe {
    fn write(&mut self, _bytes: &[u8]) -> io::Result<usize> {
        Err(io::Error::new(io::ErrorKind::BrokenPipe, "reader went away"))
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

fn main() -> io::Result<()> {
    let fixture = Cursor::new(b"add\n\noops\ncount\nadd\ncount");
    let mut output = Vec::new();
    run(fixture, &mut output)?;
    let text = String::from_utf8(output).expect("report writes UTF-8");
    assert_eq!(text, "Line 3: unknown command\nCount: 1\nCount: 2\n");

    let error = run(Cursor::new(b"count"), ClosedPipe).expect_err("write should fail");
    assert_eq!(error.kind(), io::ErrorKind::BrokenPipe);

    print!("{text}");
    Ok(())
}
Text
Line 3: unknown command
Count: 1
Count: 2

Count: 1 after the rejection proves the earlier add still counts, and Count: 2 proves processing continued past the bad line. The ClosedPipe check covers the other contract: an I/O failure is not reported as a line error but returned to the caller. On Day 7 the real queue's check.rs uses both kinds of check, with a Queue where this counter is.

Was this article helpful?

Your response is saved on this device.