This is the reading queue's shape applied to a new problem, with no files to start from. A library lends items by ID. Each line of input is a command, and the log keeps the set of active loans. The twist is that loans end: a returned item's ID becomes free and can be borrowed again. Unlike the queue, removing an entry is part of the design.
Build it in the same layers as the queue: a parser that borrows the line and returns a typed command, a loop that applies commands to a sorted map and writes results, and checks that replay input from memory.
What you will use
- A borrowed command enum:
Command<'a>with aBorrowvariant that holds the borrower as a&'a str, so parsing allocates nothing. - A parse error enum and
?: oneParseErrorfor the ID helper and the command parser, with amessagemethod that chooses the words a person sees, as on Day 5. split_once(char::is_whitespace)plustrim: split off the verb and the ID while keeping spaces inside a name such asAda Lovelace.BTreeMapand the entry API: reject a second loan for an occupied ID, and store an ownedStringonly for a vacant one.remove: itsOptionresult tells you whether there was a loan to end.impl BufReadandimpl Write: onerunfunction for stdin and for a fixture replayed into aVec<u8>.
Plan before you type
- Define
Command<'a>withBorrow(u32, &'a str),Return(u32)andList, and aParseErrorwith a variant for each malformed input and amessagemethod. - Write an
idhelper that rejects text that is not au32and, with a different variant, the value zero. - Write
parse(line): split off the verb, then forborrowsplit off the ID and treat the trimmed remainder as the borrower. - Write
run(input, output): number lines withenumerate, skip blank ones, and apply each parsed command to aBTreeMap<u32, String>. - For
list, write a heading, one line per loan in ID order, and a total. - In
main, assert the parser's error cases, replay a short fixture into aVec<u8>and compare the transcript, then run on stdin.
Prove it can fail
Check that your checks can catch the two bugs this problem invites. Replace the vacant-entry match with loans.insert(key, String::from(borrower)): the duplicate on line 2 should no longer produce an error, and your transcript comparison should fail. Then make return print Returned without calling remove: the second borrow 7 should now be rejected as already on loan. If either bug slips past your checks, add a fixture line that would expose it.
Mistakes worth checking for
Graceinstead ofGrace Hopper: the borrower was taken withsplit_whitespaceor as one word; split once and keep the trimmed remainder.- The second
borrow 7replaces Ada: the code usesinsert; the duplicate rule needsentryand anOccupiedarm that changes nothing. borrow 7 Grace Hopperis rejected after the return: the return branch did not remove the key, or it removed from a copy of the map.line does not live long enough: the map stores the&strfrom the command; storeString::from(borrower)instead.
Build it
Your turn
Build a loan log with a borrowed command parser and a sorted map of active loans. Keep the parser separate from the function that applies commands. Use one command per line.
borrow ID BORROWERadds a loan if the positive ID is free. Preserve a borrower’s internal spaces and store an owned name. Reject a second loan for the same ID.return IDremoves a loan if it exists. A returned ID can be borrowed again.listtakes no arguments. Print active loans in ascending ID order and include a count.
Skip blank lines, but count them, so line numbers match the input. Report each problem as Line N: message and continue. Use these messages:
| Problem | Example | Message |
|---|---|---|
| ID already on loan | second borrow 7 Linus | already on loan |
| return of an ID with no loan | return 99 | no such loan |
| ID that is not a whole number | return seven | ID must be a whole number |
| ID of zero | borrow 0 Ferris | ID must be 1 or more |
borrow with an ID but no name | borrow 7 | enter a borrower |
list followed by anything | list now | list takes no arguments |
| any other first word | renew 7 | unknown command |
Successful commands print Borrowed #ID and Returned #ID. list prints Active loans, then #ID Borrower for each loan in ascending ID order, then Total: N. For the supplied input the program should print exactly:
Borrowed #7
Line 2: already on loan
Line 3: no such loan
Returned #7
Borrowed #7
Line 6: ID must be 1 or more
Borrowed #3
Active loans
#3 Ferris
#7 Grace Hopper
Total: 2Zero and non-numbers get different messages because the advice differs: one should pick another number, the other should type a number at all. Keep that difference in the error type, not only in the printed text. Then add your own checks in main: assert the parser's result for a zero ID, an empty borrower and list now, and replay a short fixture into a Vec<u8> and compare its transcript with the exact text you expect.
use std::collections::{BTreeMap, btree_map::Entry};
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
let mut loans: BTreeMap<u32, String> = BTreeMap::new();
for (index, line) in io::stdin().lock().lines().enumerate() {
let line = line?;
if line.trim().is_empty() {
continue;
}
// Parse the command and apply it to loans.
println!("Line {}: {}", index + 1, line.trim());
}
Ok(())
}Hint 1: the idea
Model the instructions as an enum, then let the map enforce whether a key is occupied or vacant.
Hint 2: a first step
Start with the types, before any parsing: the three command variants, with the borrowed name on Borrow, and one ParseError variant per row of the message table that the parser can detect. The two map rules, already on loan and no such loan, are not parse errors.
Worked solution
use std::collections::{BTreeMap, btree_map::Entry};
use std::io::{self, BufRead, Write};
enum Command<'a> {
Borrow(u32, &'a str),
Return(u32),
List,
}
#[derive(Debug, PartialEq, Eq)]
enum ParseError {
InvalidId,
ZeroId,
MissingBorrower,
ExtraArguments,
UnknownCommand,
}
impl ParseError {
fn message(&self) -> &'static str {
match self {
ParseError::InvalidId => "ID must be a whole number",
ParseError::ZeroId => "ID must be 1 or more",
ParseError::MissingBorrower => "enter a borrower",
ParseError::ExtraArguments => "list takes no arguments",
ParseError::UnknownCommand => "unknown command",
}
}
}
fn id(text: &str) -> Result<u32, ParseError> {
let value = text.parse::<u32>().map_err(|_| ParseError::InvalidId)?;
if value == 0 { Err(ParseError::ZeroId) } else { Ok(value) }
}
fn split(line: &str) -> (&str, &str) {
let (head, rest) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
(head, rest.trim())
}
fn parse(line: &str) -> Result<Command<'_>, ParseError> {
let (verb, rest) = split(line.trim());
match verb {
"borrow" => {
let (key, borrower) = split(rest);
let key = id(key)?;
if borrower.is_empty() {
return Err(ParseError::MissingBorrower);
}
Ok(Command::Borrow(key, borrower))
}
"return" => Ok(Command::Return(id(rest)?)),
"list" if !rest.is_empty() => Err(ParseError::ExtraArguments),
"list" => Ok(Command::List),
_ => Err(ParseError::UnknownCommand),
}
}
fn run(input: impl BufRead, mut output: impl Write) -> io::Result<()> {
let mut loans = BTreeMap::new();
for (index, line) in input.lines().enumerate() {
let line = line?;
if line.trim().is_empty() {
continue;
}
let number = index + 1;
match parse(&line) {
Ok(Command::Borrow(key, borrower)) => match loans.entry(key) {
Entry::Vacant(slot) => {
slot.insert(String::from(borrower));
writeln!(output, "Borrowed #{key}")?;
}
Entry::Occupied(_) => writeln!(output, "Line {number}: already on loan")?,
},
Ok(Command::Return(key)) => {
if loans.remove(&key).is_some() {
writeln!(output, "Returned #{key}")?;
} else {
writeln!(output, "Line {number}: no such loan")?;
}
}
Ok(Command::List) => {
writeln!(output, "Active loans")?;
for (key, borrower) in &loans {
writeln!(output, "#{key} {borrower}")?;
}
writeln!(output, "Total: {}", loans.len())?;
}
Err(error) => writeln!(output, "Line {number}: {}", error.message())?,
}
}
output.flush()
}
fn replay(input: &str) -> String {
let mut output = Vec::new();
run(input.as_bytes(), &mut output).expect("in-memory I/O");
String::from_utf8(output).expect("UTF-8 output")
}
fn main() -> io::Result<()> {
assert_eq!(parse("borrow 0 Ada").err(), Some(ParseError::ZeroId));
assert_eq!(parse("return seven").err(), Some(ParseError::InvalidId));
assert_eq!(parse("borrow 7 ").err(), Some(ParseError::MissingBorrower));
assert_eq!(parse("list now").err(), Some(ParseError::ExtraArguments));
assert_eq!(replay("borrow 2 Ada Lovelace\nborrow 2 Linus\nlist\n\nreturn 2\nreturn 2\nrenew 2\nborrow 2 Grace\nlist"), concat!(
"Borrowed #2\n",
"Line 2: already on loan\n",
"Active loans\n",
"#2 Ada Lovelace\n",
"Total: 1\n",
"Returned #2\n",
"Line 6: no such loan\n",
"Line 7: unknown command\n",
"Borrowed #2\n",
"Active loans\n",
"#2 Grace\n",
"Total: 1\n",
));
run(io::stdin().lock(), io::stdout().lock())
}Borrowed #7
Line 2: already on loan
Line 3: no such loan
Returned #7
Borrowed #7
Line 6: ID must be 1 or more
Borrowed #3
Active loans
#3 Ferris
#7 Grace Hopper
Total: 2Removing a loan frees the key, so the later borrow 7 Grace Hopper finds a vacant entry and succeeds. The map owns each saved name, while the parser only borrows the line it is given. The checks in main run before the stdin session and print nothing when they pass: .err() turns each Result into an Option of its error, so the commands do not need PartialEq, and the replay is built to fail for both bugs in the Prove it can fail callout: the duplicate borrow 2 Linus must be refused while list still shows Ada, so switching to insert breaks it, and the second return 2 must find no loan, so a return that skips remove breaks it. The blank line checks that line numbers still count it. A &[u8] such as input.as_bytes() is itself a BufRead, so the replay needs no Cursor. The words a person reads live in one place, message, and the run loop only decides where they go. Printing {error:?} instead would show ZeroId to the user: a Rust name, not advice.
Check your own work
- The supplied input prints exactly the eleven lines in the brief.
borrow 0 Ferrisandreturn sevengive different messages, and the difference is two variants of your error type.borrow 7 Grace Hopperkeeps the space in the name, andborrow 7is rejected withenter a borrower.- A second
borrowfor an occupied ID leaves the first borrower in place, and your replay check fails if you switch toinsert. - A returned ID can be borrowed again, and your replay check fails if
returnstops callingremove. - The parser stores no
String; only the vacant-entry branch makes one.
If one of these fails, the Mistakes worth checking for list above names the usual cause.
Completion is saved in this browser only. It does not measure mastery.