Skip to content

Instantly share code, notes, and snippets.

@vortec
Created February 25, 2017 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vortec/9e3b77f0902d1904b18a74768afe4a1a to your computer and use it in GitHub Desktop.
Save vortec/9e3b77f0902d1904b18a74768afe4a1a to your computer and use it in GitHub Desktop.
defmodule KVServer.Command do
@doc ~S"""
Parses a line into a command.
## Examples
iex> KVServer.Command.parse "CREATE shopping\r\n"
{:ok, {:create, "shopping"}}
iex> KVServer.Command.parse "CREATE shopping \r\n"
{:ok, {:create, "shopping"}}
iex> KVServer.Command.parse "PUT shopping milk 1\r\n"
{:ok, {:put, "shopping", "milk", "1"}}
iex> KVServer.Command.parse "GET shopping milk\r\n"
{:ok, {:get, "shopping", "milk"}}
iex> KVServer.Command.parse "DELETE shopping eggs\r\n"
{:ok, {:delete, "shopping", "eggs"}}
Unknown commands or commands with the wrong number of
arguments return an error:
iex> KVServer.Command.parse "UNKNOWN shopping eggs\r\n"
{:error, :unknown_command}
iex> KVServer.Command.parse "GET shopping\r\n"
{:error, :unknown_command}
"""
def parse(line) do
case String.split(line) do
["CREATE", bucket] ->
{:ok, {:create, bucket}}
["PUT", bucket, name, value] ->
{:ok, {:put, bucket, name, value}}
["GET", bucket, name] ->
{:ok, {:get, bucket, name}}
["DELETE", bucket, name] ->
{:ok, {:delete, bucket, name}}
_ ->
{:error, :unknown_command}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment