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 BufReadandimpl Writeparameters: the caller chooses stdin and stdout, or aCursorand aVec<u8>.lines().enumerate(): each line arrives with its zero-based index, assigned before any line is skipped.line?andwriteln!(...)?: I/O errors leaverunimmediately as anio::Result.- A
matchon 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
writereturnsBrokenPipe.
Plan before you type
- Start
countat zero insiderun, so every run begins fresh. - Loop over
input.lines().enumerate()and match online?.trim(). - Ignore
"", increment onadd, writeCount: Noncount, and writeLine N: unknown commandfor anything else. - In
main, replay the fixture into aVec<u8>, convert it to aString, and assert the exact transcript. - Add a
ClosedPipewriter, runcountinto it, and assert that the error kind isBrokenPipe. - 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 beforeenumerate, 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 valueon the output vector: you passedoutputinstead of&mut output, soruntook ownership of it.- The broken-pipe check reports
Ok: a write result was discarded instead of propagated with?.
Build it
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:
Line 3: unknown command
Count: 1
Count: 2use 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
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(())
}Line 3: unknown command
Count: 1
Count: 2Count: 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.
Completion is saved in this browser only. It does not measure mastery.