The beginner planner called io::stdin() inside the function that processed input. That works when a person is typing, but it means the only way to test the function is to type at it. By the end of Day 5 the queue had a parser you could check with string literals. Today you make the input loop just as testable, by letting the caller decide where the bytes come from.
The tool is the Day 3 idea of a trait bound, applied to the standard library's BufRead trait. A function that accepts input: impl BufRead works with any buffered reader. io::stdin().lock() gives one that reads the console. Cursor::new(b"one\ntwo") gives one that reads bytes already in memory, which is perfect for a test. The function body is the same for both; it never learns which one it got.
lines() turns a reader into an iterator of lines, without their line endings. Each item is an io::Result<String>, because reading can fail, so line? either gives you the text or returns the error to your caller. A blank line is still a line, and it arrives as an empty String. Use trim().is_empty() to decide whether it should count.
Predict and run
The stdin box below contains one, an empty line, two and three. How many lines count in each source? Does nonblank need to know which source it is reading?
use std::io::{self, BufRead, Cursor};
fn nonblank(input: impl BufRead) -> io::Result<usize> {
let mut count = 0;
for line in input.lines() {
if !line?.trim().is_empty() {
count += 1;
}
}
Ok(count)
}
fn main() -> io::Result<()> {
println!("Fixture: {}", nonblank(Cursor::new(b"one\n\ntwo"))?);
println!("Stdin: {}", nonblank(io::stdin().lock())?);
Ok(())
}Check your prediction
Fixture: 2
Stdin: 3The fixture has three lines, one of them blank, so two count. Stdin has four lines and the same rule gives three. The fixture's last line, two, has no newline after it and still counts: lines() yields a final line without a terminator. Remove the last newline from the stdin box and predict the count, then clear the box completely. An empty input has no lines at all, so the count is 0.
A read can fail
Why is each line a Result? Reading from a terminal or a pipe can fail, and so can decoding: lines() produces Strings, which must be valid UTF-8. A fixture can provoke that failure on purpose. Byte 255 never appears in valid UTF-8.
use std::io::{self, BufRead, Cursor};
fn nonblank(input: impl BufRead) -> io::Result<usize> {
let mut count = 0;
for line in input.lines() {
if !line?.trim().is_empty() {
count += 1;
}
}
Ok(count)
}
fn main() {
let bytes = vec![b'o', b'k', b'\n', 255, b'\n'];
match nonblank(Cursor::new(bytes)) {
Ok(count) => println!("Counted {count}"),
Err(error) => println!("Read failed: {:?}", error.kind()),
}
}Read failed: InvalidDataThe first line, ok, was read and counted, then the second line failed, and line? returned the error instead of a partial count. That is usually what you want: a count based on half the input would be a wrong answer that looks right. The Day 7 checks use this exact trick to prove the queue reports read errors to its caller.
Why the bound, and why lock
You could write the parameter as a concrete type, such as input: io::StdinLock<'_>. Then only the console can call it, and a test that passes a Cursor is rejected with error[E0308]: mismatched types. The trait bound is what opens the door to fixtures.
The .lock() matters too. Passing io::stdin() itself fails with error[E0277]: the trait bound Stdin: BufRead is not satisfied. A Stdin handle is shared by the whole program; locking it gives you a StdinLock that owns the buffer for as long as you read, and that type implements BufRead.
Choose the source in main
Let main be the only function that knows about the console. It locks stdin and passes the reader to everything else. Every function below main takes impl BufRead, so each one can be driven by a Cursor in a check.
Practice
Your turn
Write commands(input: impl BufRead) -> io::Result<usize> that counts the lines whose trimmed text is exactly list. Call it on an in-memory fixture b"list\nlist", which should print Fixture: 2, and on the supplied stdin, which should print Stdin: 1 because list counts once trimmed.
use std::io::{self, BufRead, Cursor};
fn main() -> io::Result<()> {
// Count list commands in both sources.
Ok(())
}Hint 1: the idea
Read each line through the same interface and compare the trimmed text with "list". Lines that are blank or say something else simply do not count.
Hint 2: a first step
Give the function the return type io::Result<usize> and write if line?.trim() == "list" inside the loop.
Worked solution
use std::io::{self, BufRead, Cursor};
fn commands(input: impl BufRead) -> io::Result<usize> {
let mut count = 0;
for line in input.lines() {
if line?.trim() == "list" {
count += 1;
}
}
Ok(count)
}
fn main() -> io::Result<()> {
println!("Fixture: {}", commands(Cursor::new(b"list\nlist"))?);
println!("Stdin: {}", commands(io::stdin().lock())?);
Ok(())
}Fixture: 2
Stdin: 1The same loop runs for both sources; only the argument in main changes. Comparing the trimmed line means list counts but list now would not, which matches the Day 5 parser's rule. The next lesson does the same for output, so a test can capture what the program writes.
Completion is saved in this browser only. It does not measure mastery.