Skip to content
Journey to Code

Part 3 of 3

One World, Many Players

A String Is Not a Command

Parse Player Input With Option and let else

· By · 2 min read

View as Markdown

Cover reading "A String Is Not a Command" beside a parser machine turning loose input tiles into distinct command shapes.

The server can read say hello.

Right now it is one string with a space in it. Every place that uses it has to remember where the verb ends, whether a message follows and what an empty message means. That arrangement gets worse with every command we add. Rust is not responsible for that part. We did it ourselves.

We are going to turn incoming text into a Command enum before the game sees it.

The article_2 branch has the exact starting checkpoint.

Give commands names#

Add src/lib.rs:

src/lib.rs
pub mod protocol;

Then add src/protocol.rs:

src/protocol.rs
#[derive(Debug, PartialEq)]
pub enum Command {
    Look,
    Say(String),
    Who,
    Quit,
}

#[derive(Debug, PartialEq)]
pub enum ParseError {
    Empty,
    MissingMessage,
    Unknown(String),
}

pub fn parse_command(input: &str) -> Result<Command, ParseError> {
    let input = input.trim();
    if input.is_empty() {
        return Err(ParseError::Empty);
    }

    let mut words = input.splitn(2, char::is_whitespace);
    let verb = words.next().expect("non-empty input has a first word");
    let rest = words.next().map(str::trim).filter(|text| !text.is_empty());

    match verb {
        "look" => Ok(Command::Look),
        "who" => Ok(Command::Who),
        "quit" => Ok(Command::Quit),
        "say" => {
            let Some(message) = rest else {
                return Err(ParseError::MissingMessage);
            };
            Ok(Command::Say(message.to_owned()))
        }
        other => Err(ParseError::Unknown(other.to_owned())),
    }
}

rest is an Option<&str>. It is Some(message) when a second piece exists and None when the player only typed say.

let ... else handles the shape we require:

Rust
let Some(message) = rest else {
    return Err(ParseError::MissingMessage);
};

If rest is Some, Rust gives us the inner message and continues. If it is None, the else block must leave this path by returning, breaking, continuing or panicking. Here it returns a parsing error.

That leaves message as an ordinary &str below the statement. No extra nesting required.

Test the border#

Parsing is a border between untrusted text and our game. That makes it a good place for small tests:

src/protocol.rs
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_a_message_with_spaces() {
        assert_eq!(
            parse_command("say hello from the gate"),
            Ok(Command::Say("hello from the gate".to_owned()))
        );
    }

    #[test]
    fn say_needs_a_message() {
        assert_eq!(parse_command("say"), Err(ParseError::MissingMessage));
    }
}

Run them with cargo test.

Live example · parse three commands
#[derive(Debug)]
enum Command { Look, Say(String), Quit }

fn parse(input: &str) -> Result<Command, &'static str> {
    let mut words = input.trim().splitn(2, char::is_whitespace);
    let verb = words.next().ok_or("empty command")?;
    match verb {
        "look" => Ok(Command::Look),
        "quit" => Ok(Command::Quit),
        "say" => {
            let Some(message) = words.next().map(str::trim).filter(|s| !s.is_empty()) else {
                return Err("say needs a message");
            };
            Ok(Command::Say(message.to_owned()))
        }
        _ => Err("unknown command"),
    }
}

fn main() {
    for input in ["look", "say hello there", "say"] {
        println!("{input:?} -> {:?}", parse(input));
    }
}

Use the parsed command#

The connection handler now has one string operation:

Rust
match parse_command(&line) {
    Ok(Command::Look) => writeln!(stream, "You see an empty room.")?,
    Ok(Command::Say(message)) => writeln!(stream, "You say: {message}")?,
    Ok(Command::Who) => writeln!(stream, "You are the only player.")?,
    Ok(Command::Quit) => {
        writeln!(stream, "Goodbye")?;
        break;
    }
    Err(error) => writeln!(stream, "Invalid command: {error:?}")?,
}

The network side owns text. The game side receives meaning.

What we learned#

  • Option represents a value that may be absent
  • Some carries the value and None does not
  • let ... else keeps the successful value in the current scope
  • parsing belongs at the edge of the program
  • a command enum keeps string rules out of the world model

One player can now hold a real conversation with the server.

The second player still has to wait outside.

One connection. Shared world.

Comments require JavaScript.