Skip to content

Checkpoint: Parse a Finish Request

The Course
•
30 min study

The reading queue needs to understand finish 7. That one short line can go wrong in five different ways, and each deserves its own answer: the ID is missing, it is not a number, it is zero, a list has extra words, or the verb is unknown. In this checkpoint you write the parser for finish ID and list, built from two functions: one that knows the rules for an ID, and one that knows the shape of a command. The ID parser's errors flow out through the command parser with ?.

No queue is involved. Parsing only describes the request, so every check is a plain comparison between an input string and an expected Result.

What you will use

  • A shared error enum: one ParseError type for both functions, so ? can pass the ID helper's error straight through.
  • map_err and ?: turn the standard library's parse failure into InvalidNumber and return it early.
  • A separate zero check: 0 parses as a u32, so it needs its own rule after parsing.
  • split_once(char::is_whitespace) with unwrap_or: split the verb from its arguments, with an empty remainder when there are none.
  • Match guards in the right order: the guarded finish and list arms come before the general ones.

Plan before you type

  1. Write parse_id(text: &str) -> Result<u32, ParseError>: parse, map the error, then reject zero.
  2. Write parse(line: &str) -> Result<Command, ParseError>: trim, split off the verb, trim the rest.
  3. Match the verb: finish with an empty rest is MissingId; otherwise parse_id(rest)? builds Finish.
  4. Add the two list arms, the guarded one first, and a catch-all for unknown verbs.
  5. Assert every case from the task, valid and invalid, then print one success line.
Prove it can fail

Your assertions are only useful if they can fail. Try three deliberate bugs, one at a time, and confirm that a different assertion stops the program each time: delete the zero check in parse_id; swap the two list arms; remove the MissingId arm so finish alone falls through to parse_id. If a bug does not trip any assertion, you are missing a case.

Mistakes worth checking for

  • finish 0 returns Ok(Finish(0)): the zero check is missing, or it runs before parsing and compares text instead of the number.
  • finish alone returns InvalidNumber: the empty remainder reached parse_id; check for an empty rest first if you want MissingId.
  • list now returns Ok(List): the unguarded list arm is above the guarded one. Watch for the unreachable pattern warning.
  • ? couldn't convert the error: parse_id returns a different error type from parse; make both use ParseError.
  • finish 7 fails: the line or the remainder was not trimmed before splitting or parsing.

Build it

Exercise

Your turn

Accept finish ID, where ID is a positive u32, and list with no arguments. Assert these results, then print Finish parser checks passed:

  • finish 7 and finish 7 give Ok(Finish(7)); list gives Ok(List).
  • finish gives MissingId; finish x and finish 4294967296 give InvalidNumber; finish 0 gives ZeroId.
  • list now gives ExtraArguments; remove 7 gives UnknownCommand.

Use ? to return the ID error from the command parser.

Your working space Rust
#[derive(Debug, PartialEq, Eq)]
enum Command { Finish(u32), List }

#[derive(Debug, PartialEq, Eq)]
enum ParseError { MissingId, InvalidNumber, ZeroId, ExtraArguments, UnknownCommand }

fn main() {
    // Check every valid and invalid case from the task.
}
Hint 1: the idea

Let a helper own the rules for a positive ID. The command parser only decides which command it is looking at, then calls the helper and propagates its result.

Hint 2: a first step

Write parse_id(text: &str) -> Result<u32, ParseError> first and test it on 7, 0 and x before writing parse.

Worked solution
Run the solution Rust
#[derive(Debug, PartialEq, Eq)]
enum Command { Finish(u32), List }

#[derive(Debug, PartialEq, Eq)]
enum ParseError { MissingId, InvalidNumber, ZeroId, ExtraArguments, UnknownCommand }

fn parse_id(text: &str) -> Result<u32, ParseError> {
    let id = text.parse::<u32>().map_err(|_| ParseError::InvalidNumber)?;
    if id == 0 { Err(ParseError::ZeroId) } else { Ok(id) }
}

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 {
        "finish" if rest.is_empty() => Err(ParseError::MissingId),
        "finish" => Ok(Command::Finish(parse_id(rest)?)),
        "list" if !rest.is_empty() => Err(ParseError::ExtraArguments),
        "list" => Ok(Command::List),
        _ => Err(ParseError::UnknownCommand),
    }
}

fn main() {
    assert_eq!(parse("finish 7"), Ok(Command::Finish(7)));
    assert_eq!(parse(" finish   7 "), Ok(Command::Finish(7)));
    assert_eq!(parse("list"), Ok(Command::List));
    assert_eq!(parse("finish"), Err(ParseError::MissingId));
    assert_eq!(parse("finish x"), Err(ParseError::InvalidNumber));
    assert_eq!(parse("finish 4294967296"), Err(ParseError::InvalidNumber));
    assert_eq!(parse("finish 0"), Err(ParseError::ZeroId));
    assert_eq!(parse("list now"), Err(ParseError::ExtraArguments));
    assert_eq!(parse("remove 7"), Err(ParseError::UnknownCommand));
    println!("Finish parser checks passed");
}
Text
Finish parser checks passed

Both functions return ParseError, so parse_id(rest)? needs no conversion: an ID error leaves parse unchanged. finish 4294967296 checks the upper boundary, one past u32::MAX, and finish 7 checks that trimming happens at both levels. The queue's real parser in command.rs has this same structure. On Day 6 you will feed parsers like this one from a reader instead of string literals.

Was this article helpful?

Your response is saved on this device.