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"}
Summary
Functions
Calculate the byte length needed to encode a value.
Decode a variable byte integer from binary data.
Encode an integer as a variable byte integer.
Encode an integer as iodata (more efficient for building packets).
Maximum value that can be encoded.
Functions
@spec byte_length(non_neg_integer()) :: 1 | 2 | 3 | 4
Calculate the byte length needed to encode a value.
@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.
@spec encode(non_neg_integer()) :: binary()
Encode an integer as a variable byte integer.
Returns a binary of 1-4 bytes.
@spec encode_iodata(non_neg_integer()) :: iodata()
Encode an integer as iodata (more efficient for building packets).
@spec max_value() :: non_neg_integer()
Maximum value that can be encoded.