Skip to content

Run the Reading Queue

The Course
•
24 min study

The beginner tracker accepted independent reading rows: each line meant the same thing whatever came before it. This queue responds to commands whose meaning depends on earlier lines. finish 3 is only valid if book 3 was added and is not finished yet. That is the difference between parsing data and running a small program with state, and it is what the last six days prepared you for. Use one command per line.

  • add ID TITLE stores an owned title in the pending state. The ID is a positive u32 and can be used only once per run.
  • finish ID changes a pending book to finished. Unknown and already finished IDs produce distinct errors.
  • list prints every book in ascending ID order, then the pending and finished counts. Blank lines are skipped, and bad commands report their input line number.

How the files fit together

Each file has one job, and each job is a day of this course.

  • main.rs is the only code that touches the console. It locks stdin and stdout and passes them to app::run, as on Day 6.
  • app.rs owns the loop: read a line, skip it if blank, parse it, apply it, and write one line of result. It turns every error into a message with a line number.
  • command.rs is the Day 5 parser. It returns a Command<'_> that borrows its title from the line, or a ParseError.
  • queue.rs holds the state: a BTreeMap<BookId, Book> from Day 4, with the entry API enforcing unique IDs. BookId is the Day 1 validated type, with a private field, so a zero ID cannot exist outside this module.
  • check.rs is a second entry point that replays fixtures and checks the results, which you will run in the third lesson.

The browser reads the text in the input box through to its end, as if it were typed and then closed. Every run starts with a fresh, empty queue.

Predict and run

The fixture adds book 7 first, then book 3. Which book will the report list first? What will happen to the title when the duplicate add 7 arrives?

Predict, then run 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
Check your prediction
Text
Added #7
Added #3
Finished #3
Line 4: ID is already in use
Reading queue
#3 [finished] Borrowing
#7 [pending] Rust Patterns
Pending: 1 | Finished: 1

Book 3 is listed first because the map iterates in key order; arrival order is gone. The duplicate on line 4 reached the occupied entry and was rejected before anything was stored, so Rust Patterns keeps its title and its pending status. Add another finish 3 before list, then try finish 99. Predict the two messages, and explain which rule each command breaks and why neither should change the report.

Every rule, one input

The sample shows one rejection. The run below sends one line for each kind of mistake, then a valid add and finish. Before running it, write down the message you expect for each line. The messages come from the message methods in command.rs and queue.rs.

Run every error path 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 0 Zero add 4 finish 99 remove 3 add 4 Traits finish 4 finish 4 list now list
Text
Line 1: ID must be positive
Line 2: enter a title
Line 3: book was not found
Line 4: use add, finish or list
Added #4
Finished #4
Line 7: book is already finished
Line 8: list takes no arguments
Reading queue
#4 [finished] Traits
Pending: 0 | Finished: 1

Lines 1, 2, 4 and 8 fail in the parser: the text itself is wrong, so no queue method is called. Lines 3 and 7 parse correctly but break a rule that depends on state, so the queue rejects them. The two kinds of error are separate enums for that reason. Each rejected line produces exactly one message, and the loop continues, which is why the final report still appears.

Two kinds of failure

A bad command never stops the run; it becomes a Line N: message. A failed read or write does stop it: app::run returns the io::Error, and main returns it too. That split is the Day 6 checkpoint at full size.

Practice

Exercise

Predict a transcript

Without running it first, write the complete output for this input. Then paste it into the input box of the first playground and compare.

Text
add 2 Traits
add 1 Slices
finish 2

add 2 Again
list
Hint 1: the idea

Work out the map's contents after each line, then sort by ID only when you reach list. Remember that the blank line still has a line number.

Hint 2: a first step

The first three lines all succeed. The fifth line reuses ID 2.

Worked solution
Text
Added #2
Added #1
Finished #2
Line 5: ID is already in use
Reading queue
#1 [pending] Slices
#2 [finished] Traits
Pending: 1 | Finished: 1

The rejection reports line 5, not 4, because enumerate numbered the blank line before the loop skipped it. Book 2 keeps both its first title and its finished status, and book 1 is listed first even though it arrived second. The next lesson follows the title of an add command from the input line into the map.

Was this article helpful?

Your response is saved on this device.