Created
February 25, 2017 22:21
-
-
Save vortec/9e3b77f0902d1904b18a74768afe4a1a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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