View Source Redix.Protocol (Redix v1.5.1)
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
The return value of parsing functions in this module.
@type redis_value() :: binary() | integer() | nil | Redix.Error.t() | [redis_value()]
Represents a Redis value.
Functions
@spec pack([String.Chars.t()]) :: 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 encoding everything that implements String.Chars
.
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"
@spec parse(binary()) :: on_parse(redis_value())
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", ""}
@spec parse_multi(binary(), non_neg_integer()) :: on_parse([redis_value()])
Parses n
RESP-encoded values from the given data
.
Each element is parsed as described in parse/1
. If an element can't be fully
parsed or there are less than n
elements encoded in data
, then a
continuation in the form of {:continuation, fun}
is returned. Otherwise,
{:ok, values, rest}
is returned. If there's an error in decoding, a
Redix.Protocol.ParseError
exception is raised.
Examples
iex> Redix.Protocol.parse_multi("+OK\r\n+COOL\r\n", 2)
{:ok, ["OK", "COOL"], ""}
iex> {:continuation, fun} = Redix.Protocol.parse_multi("+OK\r\n", 2)
iex> fun.("+OK\r\n")
{:ok, ["OK", "OK"], ""}