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
ParseErrortype for both functions, so?can pass the ID helper's error straight through. map_errand?: turn the standard library's parse failure intoInvalidNumberand return it early.- A separate zero check:
0parses as au32, so it needs its own rule after parsing. split_once(char::is_whitespace)withunwrap_or: split the verb from its arguments, with an empty remainder when there are none.- Match guards in the right order: the guarded
finishandlistarms come before the general ones.
Plan before you type
- Write
parse_id(text: &str) -> Result<u32, ParseError>: parse, map the error, then reject zero. - Write
parse(line: &str) -> Result<Command, ParseError>: trim, split off the verb, trim the rest. - Match the verb:
finishwith an empty rest isMissingId; otherwiseparse_id(rest)?buildsFinish. - Add the two
listarms, the guarded one first, and a catch-all for unknown verbs. - 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 0returnsOk(Finish(0)): the zero check is missing, or it runs before parsing and compares text instead of the number.finishalone returnsInvalidNumber: the empty remainder reachedparse_id; check for an empty rest first if you wantMissingId.list nowreturnsOk(List): the unguardedlistarm is above the guarded one. Watch for theunreachable patternwarning.?couldn't convert the error:parse_idreturns a different error type fromparse; make both useParseError.finish 7fails: the line or the remainder was not trimmed before splitting or parsing.
Build it
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 7andfinish 7giveOk(Finish(7));listgivesOk(List).finishgivesMissingId;finish xandfinish 4294967296giveInvalidNumber;finish 0givesZeroId.list nowgivesExtraArguments;remove 7givesUnknownCommand.
Use ? to return the ID error from the command parser.
#[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
#[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");
}Finish parser checks passedBoth 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.
Completion is saved in this browser only. It does not measure mastery.