Skip to content

Show the Next Pending Book

The Course
•
26 min study

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

Exercise

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.

Your working space Rust
mod app; mod command; mod queue; use std::io; fn main() -> io::Result<()> { app::run(io::stdin().lock(), io::stdout().lock()) } use crate::command::{Command, parse}; use crate::queue::Queue; use std::io::{self, BufRead, Write}; fn report(queue: &Queue, output: &mut impl Write) -> io::Result<()> { writeln!(output, "Reading queue")?; for (id, book) in queue.books() { writeln!(output, "#{} [{}] {}", id.get(), book.status().label(), book.title())?; } let (pending, finished) = queue.counts(); writeln!(output, "Pending: {pending} | Finished: {finished}") } pub fn run(input: impl BufRead, mut output: impl Write) -> io::Result<()> { let mut queue = Queue::default(); for (index, line) in input.lines().enumerate() { let line = line?; if line.trim().is_empty() { continue; } let number = index + 1; let command = match parse(&line) { Ok(command) => command, Err(error) => { writeln!(output, "Line {number}: {}", error.message())?; continue; } }; match command { Command::Add { id, title } => match queue.add(id, title) { Ok(()) => writeln!(output, "Added #{}", id.get())?, Err(error) => writeln!(output, "Line {number}: {}", error.message())?, }, Command::Finish(id) => match queue.finish(id) { Ok(()) => writeln!(output, "Finished #{}", id.get())?, Err(error) => writeln!(output, "Line {number}: {}", error.message())?, }, Command::List => report(&queue, &mut output)?, } } output.flush() } use crate::queue::BookId; #[derive(Debug, PartialEq, Eq)] pub enum Command<'a> { Add { id: BookId, title: &'a str }, Finish(BookId), List, } #[derive(Debug, PartialEq, Eq)] pub enum ParseError { UnknownCommand, InvalidId, ZeroId, MissingTitle, ExtraArguments, } impl ParseError { pub fn message(&self) -> &'static str { match self { Self::UnknownCommand => "use add, finish or list", Self::InvalidId => "use a whole-number ID", Self::ZeroId => "ID must be positive", Self::MissingTitle => "enter a title", Self::ExtraArguments => "list takes no arguments", } } } fn parse_id(text: &str) -> Result<BookId, ParseError> { let value = text.parse::<u32>().map_err(|_| ParseError::InvalidId)?; BookId::new(value).ok_or(ParseError::ZeroId) } pub fn parse(line: &str) -> Result<Command<'_>, ParseError> { let line = line.trim(); let (verb, rest) = line.split_once(char::is_whitespace).unwrap_or((line, "")); let rest = rest.trim(); match verb { "add" => { let (id, title) = rest.split_once(char::is_whitespace).unwrap_or((rest, "")); let id = parse_id(id)?; let title = title.trim(); if title.is_empty() { return Err(ParseError::MissingTitle); } Ok(Command::Add { id, title }) } "finish" => Ok(Command::Finish(parse_id(rest)?)), "list" if !rest.is_empty() => Err(ParseError::ExtraArguments), "list" => Ok(Command::List), _ => Err(ParseError::UnknownCommand), } } use std::collections::{BTreeMap, btree_map::Entry}; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct BookId(u32); impl BookId { pub fn new(value: u32) -> Option<Self> { if value == 0 { None } else { Some(Self(value)) } } pub fn get(self) -> u32 { self.0 } } #[derive(Debug, PartialEq, Eq)] pub enum QueueError { EmptyTitle, DuplicateId, UnknownId, AlreadyFinished, } impl QueueError { pub fn message(&self) -> &'static str { match self { Self::EmptyTitle => "enter a title", Self::DuplicateId => "ID is already in use", Self::UnknownId => "book was not found", Self::AlreadyFinished => "book is already finished", } } } #[derive(Debug, PartialEq, Eq)] pub enum Status { Pending, Finished, } impl Status { pub fn label(&self) -> &'static str { match self { Self::Pending => "pending", Self::Finished => "finished", } } } pub struct Book { title: String, status: Status, } impl Book { pub fn title(&self) -> &str { &self.title } pub fn status(&self) -> &Status { &self.status } } #[derive(Default)] pub struct Queue { books: BTreeMap<BookId, Book>, } impl Queue { pub fn add(&mut self, id: BookId, title: &str) -> Result<(), QueueError> { let title = title.trim(); if title.is_empty() { return Err(QueueError::EmptyTitle); } match self.books.entry(id) { Entry::Vacant(slot) => { slot.insert(Book { title: String::from(title), status: Status::Pending }); Ok(()) } Entry::Occupied(_) => Err(QueueError::DuplicateId), } } pub fn finish(&mut self, id: BookId) -> Result<(), QueueError> { let book = self.books.get_mut(&id).ok_or(QueueError::UnknownId)?; if book.status == Status::Finished { return Err(QueueError::AlreadyFinished); } book.status = Status::Finished; Ok(()) } pub fn books(&self) -> impl Iterator<Item = (&BookId, &Book)> { self.books.iter() } pub fn counts(&self) -> (usize, usize) { let finished = self.books.values().filter(|book| book.status == Status::Finished).count(); (self.books.len() - finished, finished) } } add 7 Rust Patterns add 3 Borrowing finish 3 add 7 Replacement list
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.

Rust
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.

Stop at the first pending book Rust
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:?}");
}
Text
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).

Shell
cargo run --quiet < sample.txt
cargo run --quiet --bin check-queue

The 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:

Rust
#[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:

Text
running 2 tests
test tests::duplicate_add_keeps_the_first_title ... ok
test tests::list_on_an_empty_queue_reports_zero_books ... ok

The 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.

Was this article helpful?

Your response is saved on this device.