Redix v0.3.1 Redix.Protocol
This module provides functions to work with the Redis binary protocol.
Summary
Functions
Packs a list of Elixir terms to a Redis (RESP) array
Parses a RESP-encoded value from the given data
Parses n
RESP-encoded values from the given data
Types
redis_value ::
binary |
integer |
nil |
Redix.Error.t |
[redis_value]
Functions
Specs
pack([binary]) :: iodata
Packs a list of Elixir terms to a Redis (RESP) array.
This function returns an iodata (instead of a binary) because the packed result is usually sent to Redis through :gen_tcp.send/2
or similar. It can be converted to a binary with IO.iodata_to_binary/1
.
All elements of elems
are converted to strings with to_string/1
, hence this function supports integers, atoms, string, char lists and whatnot. Since to_string/1
uses the String.Chars
protocol, running this with consolidated protocols makes it quite faster (even if this is probably not the bottleneck of your application).
Examples
iex> iodata = Redix.Protocol.pack ["SET", "mykey", 1]
iex> IO.iodata_to_binary(iodata)
"*3\r\n$3\r\nSET\r\n$5\r\nmykey\r\n$1\r\n1\r\n"
Specs
parse(binary) ::
{:ok, redis_value, binary} |
{:error, term}
Parses a RESP-encoded value from the given data
.
Returns {:ok, value, rest}
if a value is parsed successfully, {:error, reason}
otherwise.
Examples
iex> Redix.Protocol.parse "+OK\r\ncruft"
{:ok, "OK", "cruft"}
iex> Redix.Protocol.parse "-ERR wrong type\r\n"
{:ok, %Redix.Error{message: "ERR wrong type"}, ""}
iex> Redix.Protocol.parse "+OK"
{:error, :incomplete}
Specs
parse_multi(binary, non_neg_integer) ::
{:ok, [redis_value], binary} |
{:error, term}
Parses n
RESP-encoded values from the given data
.
Each element is parsed as described in parse/1
. If there's an error in parsing any of the elements or there are less than n
elements, {:error, reason}
is returned. Otherwise, {:ok, values, rest}
is returned.
Examples
iex> parse_multi("+OK\r\n+COOL\r\n", 2)
{:ok, ["OK", "COOL"], ""}
iex> parse_multi("+OK\r\n", 2)
{:error, :incomplete}