# `Redix.Protocol`
[🔗](https://github.com/whatyouhide/redix/blob/v1.8.0/lib/redix/protocol.ex#L1)

This module provides functions to work with the [Redis binary
protocol](http://redis.io/topics/protocol).

# `on_parse`

```elixir
@type on_parse(value) ::
  {:ok, value, binary()} | {:continuation, (binary() -&gt; on_parse(value))}
```

The return value of parsing functions in this module.

# `redis_value`

```elixir
@type redis_value() :: binary() | integer() | nil | Redix.Error.t() | [redis_value()]
```

Represents a Redis value.

# `pack`

```elixir
@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"

# `parse`

```elixir
@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", ""}

# `parse_multi`

```elixir
@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"], ""}

---

*Consult [api-reference.md](api-reference.md) for complete listing*
