Redix v0.3.5 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, or a
continuation in the form {:continuation, fun}
if the data is incomplete.
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> {:continuation, fun} = Redix.Protocol.parse "+OK"
iex> fun.("\r\n")
{:ok, "OK", ""}
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, a
continuation in the form of {:continuation, fun}
is returned. Otherwise,
{:ok, values, rest}
is returned.
Examples
iex> parse_multi("+OK\r\n+COOL\r\n", 2)
{:ok, ["OK", "COOL"], ""}
iex> {:continuation, fun} = parse_multi("+OK\r\n", 2)
iex> fun.("+OK\r\n")
{:ok, ["OK", "OK"], ""}