A reading queue should answer the question a reader actually has: what do I read next? In this lesson you add that answer to the list report, then download the project and run it with Cargo on your own machine.
The rule is simple: the next book is the pending book with the smallest ID. You do not need a new data structure for it. queue.books() already yields (&BookId, &Book) pairs in ascending ID order, because the map is a BTreeMap. So the first pending book the iterator reaches is the answer, and the Day 4 consumer that stops at the first match is find. It returns an Option, which also covers the case where nothing is pending.
The change touches only report in app.rs. The parser and the queue stay as they are, which is the payoff of keeping the layers separate: a new view of the data does not need new rules for changing it.
Extend the report
Extend the report
In app.rs, add a line immediately before the pending and finished counts. For the sample input, print Next: #7 Rust Patterns. If no book is pending, print Next: none. The next book is the pending book with the smallest ID. Test the sample, an input that finishes every book before listing, and a plain list on an empty queue.
Hint 1: the idea
The iterator is already in key order. Look for its first pending record instead of sorting or collecting.
Hint 2: a first step
Use queue.books().find(...). Its result is an Option, so handle the found and missing cases in a match. app.rs does not import Status, so name it by its full path, crate::queue::Status::Pending.
Worked solution
Insert this in report before the let (pending, finished) line. find stops at the first matching entry and returns the original pair.
match queue.books().find(|(_, book)| book.status() == &crate::queue::Status::Pending) {
Some((id, book)) => writeln!(output, "Next: #{} {}", id.get(), book.title())?,
None => writeln!(output, "Next: none")?,
}With the sample, book 3 is finished, so the search moves on to book 7 and prints Next: #7 Rust Patterns. book.status() returns &Status, so the comparison is between two references; that works because Status derives PartialEq. Each arm ends with ? because a write can fail, just like the other lines of the report.
If you keep the extension, the queue checks will now fail: the transcripts in check.rs do not expect a Next: line. That failure is correct, because the output really changed. Update the expected transcripts in check_io for both the empty queue and the nonempty one, then run the checks again.
Why find fits the question
Several consumers could answer "lowest pending ID", but they do different amounts of work. The example below runs the same question two ways over a small map and counts how many entries find had to look at.
use std::collections::BTreeMap;
fn main() {
let books = BTreeMap::from([
(3, ("Borrowing", true)),
(7, ("Rust Patterns", false)),
(9, ("Traits", false)),
]);
let mut visited = 0;
let next = books.iter().find(|(_, book)| {
visited += 1;
!book.1
});
println!("find: {next:?} after {visited} visits");
let lowest = books.iter().filter(|(_, book)| !book.1).map(|(id, _)| id).min();
println!("filter and min: {lowest:?}");
}find: Some((7, ("Rust Patterns", false))) after 2 visits
filter and min: Some(7)Both give ID 7, but find stopped after two entries, while filter and min had to see every entry before knowing the minimum. min is the right tool when the data is not sorted. Here the map already did the sorting, so find both reads as the question and does the least work. It also hands back the whole pair, so the title is right there for the report.
Run with Cargo
Download the original reading queue and extract it. The download contains the same five Rust files you have been reading, plus sample.txt, a README.md, and a Cargo.toml that defines two binaries: reading-queue from main.rs, the default, and check-queue from check.rs. The download is the original, so your extension is not included; copy your report change into app.rs if you want to keep it.
In a terminal in the folder containing Cargo.toml, run these commands with a local Rust toolchain that supports edition 2024 (Rust 1.85 or newer).
cargo run --quiet < sample.txt
cargo run --quiet --bin check-queueThe first command sends the fixture to stdin with <, so the program reads it exactly as the browser did. Run cargo run --quiet without the redirect to type commands yourself; end the input with Ctrl-D on macOS and Linux, or Ctrl-Z then Enter on Windows. The check binary needs no input at all: it replays its fixtures from memory, which works because app::run accepts any buffered reader and any writer.
Going further: the same checks as cargo test
check-queue is a second main because the browser has no test runner: it can only run a program. Locally, Rust has one built in, and a typical crate keeps its checks in a tests module rather than a check binary. Each check becomes a function marked #[test], and #[cfg(test)] compiles the module only when testing. Add this to the end of the downloaded main.rs:
#[cfg(test)]
mod tests {
use crate::app;
use crate::queue::{BookId, Queue, QueueError};
#[test]
fn duplicate_add_keeps_the_first_title() {
let id = BookId::new(7).expect("positive ID");
let mut queue = Queue::default();
assert_eq!(queue.add(id, "Rust"), Ok(()));
assert_eq!(queue.add(id, "Replacement"), Err(QueueError::DuplicateId));
let titles: Vec<&str> = queue.books().map(|(_, book)| book.title()).collect();
assert_eq!(titles, ["Rust"]);
}
#[test]
fn list_on_an_empty_queue_reports_zero_books() {
let mut output = Vec::new();
app::run("list".as_bytes(), &mut output).expect("in-memory I/O");
assert_eq!(String::from_utf8(output).unwrap(), "Reading queue\nPending: 0 | Finished: 0\n");
}
}Then run cargo test. Among Cargo's lines you will see:
running 2 tests
test tests::duplicate_add_keeps_the_first_title ... ok
test tests::list_on_an_empty_queue_reports_zero_books ... okThe assertions are the ones check.rs already makes; only the packaging differs. crate::queue names the module from the top of the program, because tests is a module of its own. Each #[test] function runs separately, so one failure is reported by name and the rest still run, where check-queue stops at its first panic. A &[u8] such as "list".as_bytes() is itself a BufRead, the same injection that makes the check binary possible. Cargo also prints running 0 tests for check-queue, which has no #[test] functions. The advanced course's download uses this layout from the start.
Run the checks after every change
Make cargo run --quiet --bin check-queue a habit after each edit. It takes a second, and it tells you whether a change kept every promise the queue already made, or changed output you will have to update on purpose.
Completion is saved in this browser only. It does not measure mastery.