Varint
A library to compress integers using LEB128.
Installation
Add :varint to your list of dependencies in mix.exs:
def deps do
[{:varint, "~> 1.6"}]
end
Usage
LEB128
Use this module to compress and decompress unsigned integers:
iex> Varint.LEB128.encode(300)
<<172, 2>>
iex> Varint.LEB128.decode(<<172, 2>>)
{300, <<>>}
SLEB128
Use this module to compress and decompress signed integers using signed LEB128:
iex> Varint.SLEB128.encode(-624485)
<<155, 241, 89>>
iex> Varint.SLEB128.decode(<<155, 241, 89>>)
{-624485, <<>>}
Batch decoding
Use decode_batch/1 to decode a binary of consecutive varints into a list in wire order. Both codecs return [] for an empty binary and raise ArgumentError for non-binary input or an incomplete trailing value.
It's faster than repeatedly calling decode/1.
iex> Varint.LEB128.decode_batch(<<1, 172, 2, 0>>)
[1, 300, 0]
iex> Varint.SLEB128.decode_batch(<<127, 191, 127, 1>>)
[-1, -65, 1]
Zigzag
As LEB128 works with unsigned integers, you can use the Zigzag module to process signed integers.
iex> Varint.Zigzag.encode(-2)
3
iex> Varint.Zigzag.decode(3)
-2
iex> Varint.Zigzag.encode(2)
4
iex> Varint.Zigzag.decode(4)
2
You'll find detailed instructions at hexdocs.pm.
Benchmarks
Run the Benchee suite from the repository root with MIX_ENV=bench.
MIX_ENV=bench mix deps.get
MIX_ENV=bench mix run bench/varint.exs 076af45
Pass a Git revision to compare against it in the same VM, or omit the revision to benchmark the current code alone. Each measurement covers a batch of 256 deterministic inputs. The suite covers signed and unsigned values of several encoded widths, with a trailing binary on decode inputs.
Batch decoding comparison
Run the batch benchmark with MIX_ENV=bench mix run bench/batch.exs.
Each iteration compares decode_batch/1 with a loop over decode/1 on the same 16 prebuilt buffers. Both codecs are measured on 16, 64, 256, and 1,024 values per buffer. The benchmark uses one-byte values and a mix that samples one-, two-, and three-byte values with an 80/15/5 probability split.
License
Copyright (c) 2016 Alexandre Hamez
This work is free. You can redistribute it and/or modify it under the terms of the MIT License. See the LICENSE file for more details.