# `MqttX.Packet.Varint`
[🔗](https://github.com/cignosystems/mqttx/blob/v0.10.0/lib/mqttx/packet/varint.ex#L1)

MQTT Variable Byte Integer encoding and decoding.

Variable byte integers use 1-4 bytes to encode values from 0 to 268,435,455.
Each byte uses 7 bits for data and 1 continuation bit.

## Encoding

    iex> MqttX.Packet.Varint.encode(127)
    <<127>>

    iex> MqttX.Packet.Varint.encode(128)
    <<128, 1>>

    iex> MqttX.Packet.Varint.encode(16383)
    <<255, 127>>

## Decoding

    iex> MqttX.Packet.Varint.decode(<<128, 1, "rest">>)
    {:ok, 128, "rest"}

# `byte_length`

```elixir
@spec byte_length(non_neg_integer()) :: 1 | 2 | 3 | 4
```

Calculate the byte length needed to encode a value.

# `decode`

```elixir
@spec decode(binary()) ::
  {:ok, non_neg_integer(), binary()} | :incomplete | {:error, atom()}
```

Decode a variable byte integer from binary data.

Returns `{:ok, value, rest}` on success, `:incomplete` if more data needed,
or `{:error, reason}` on failure.

# `encode`

```elixir
@spec encode(non_neg_integer()) :: binary()
```

Encode an integer as a variable byte integer.

Returns a binary of 1-4 bytes.

# `encode_iodata`

```elixir
@spec encode_iodata(non_neg_integer()) :: iodata()
```

Encode an integer as iodata (more efficient for building packets).

# `max_value`

```elixir
@spec max_value() :: non_neg_integer()
```

Maximum value that can be encoded.

---

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