Skip to content

On Your Own: A Library Loan Log

The Course
•
60 min study

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 a Borrow variant that holds the borrower as a &'a str, so parsing allocates nothing.
  • A parse error enum and ?: one ParseError for the ID helper and the command parser, with a message method that chooses the words a person sees, as on Day 5.
  • split_once(char::is_whitespace) plus trim: split off the verb and the ID while keeping spaces inside a name such as Ada Lovelace.
  • BTreeMap and the entry API: reject a second loan for an occupied ID, and store an owned String only for a vacant one.
  • remove: its Option result tells you whether there was a loan to end.
  • impl BufRead and impl Write: one run function for stdin and for a fixture replayed into a Vec<u8>.

Plan before you type

  1. Define Command<'a> with Borrow(u32, &'a str), Return(u32) and List, and a ParseError with a variant for each malformed input and a message method.
  2. Write an id helper that rejects text that is not a u32 and, with a different variant, the value zero.
  3. Write parse(line): split off the verb, then for borrow split off the ID and treat the trimmed remainder as the borrower.
  4. Write run(input, output): number lines with enumerate, skip blank ones, and apply each parsed command to a BTreeMap<u32, String>.
  5. For list, write a heading, one line per loan in ID order, and a total.
  6. In main, assert the parser's error cases, replay a short fixture into a Vec<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

  • Grace instead of Grace Hopper: the borrower was taken with split_whitespace or as one word; split once and keep the trimmed remainder.
  • The second borrow 7 replaces Ada: the code uses insert; the duplicate rule needs entry and an Occupied arm that changes nothing.
  • borrow 7 Grace Hopper is 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 &str from the command; store String::from(borrower) instead.

Build it

Exercise

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 BORROWER adds 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 ID removes a loan if it exists. A returned ID can be borrowed again.
  • list takes 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:

ProblemExampleMessage
ID already on loansecond borrow 7 Linusalready on loan
return of an ID with no loanreturn 99no such loan
ID that is not a whole numberreturn sevenID must be a whole number
ID of zeroborrow 0 FerrisID must be 1 or more
borrow with an ID but no nameborrow 7 enter a borrower
list followed by anythinglist nowlist takes no arguments
any other first wordrenew 7unknown 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:

Text
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: 2

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

Your working space Rust
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(())
}
borrow 7 Ada Lovelace borrow 7 Linus return 99 return 7 borrow 7 Grace Hopper borrow 0 Ferris borrow 3 Ferris list
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
Run the solution Rust
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())
}
borrow 7 Ada Lovelace borrow 7 Linus return 99 return 7 borrow 7 Grace Hopper borrow 0 Ferris borrow 3 Ferris list
Text
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: 2

Removing 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 Ferris and return seven give different messages, and the difference is two variants of your error type.
  • borrow 7 Grace Hopper keeps the space in the name, and borrow 7 is rejected with enter a borrower.
  • A second borrow for an occupied ID leaves the first borrower in place, and your replay check fails if you switch to insert.
  • A returned ID can be borrowed again, and your replay check fails if return stops calling remove.
  • 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.

Was this article helpful?

Your response is saved on this device.