Current section
Files
Jump to
Current section
Files
README.md
# Varint
[](https://github.com/ahamez/varint/actions/workflows/elixir.yml) [](https://coveralls.io/github/ahamez/varint?branch=master) [](https://hex.pm/packages/varint) [](https://hexdocs.pm/varint/) [](https://github.com/ahamez/varint/blob/master/LICENSE)
A library to compress integers using [LEB128](https://en.wikipedia.org/wiki/LEB128).
## Installation
Add `:varint` to your list of dependencies in `mix.exs`:
```elixir
def deps do
[{:varint, "~> 1.6"}]
end
```
## Usage
### LEB128
Use this module to compress and decompress unsigned integers:
```elixir
iex> Varint.LEB128.encode(300)
<<172, 2>>
```
```elixir
iex> Varint.LEB128.decode(<<172, 2>>)
{300, <<>>}
```
### SLEB128
Use this module to compress and decompress signed integers using signed LEB128:
```elixir
iex> Varint.SLEB128.encode(-624485)
<<155, 241, 89>>
```
```elixir
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`.
```elixir
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.
```elixir
iex> Varint.Zigzag.encode(-2)
3
```
```elixir
iex> Varint.Zigzag.decode(3)
-2
```
```elixir
iex> Varint.Zigzag.encode(2)
4
```
```elixir
iex> Varint.Zigzag.decode(4)
2
```
You'll find detailed instructions at [hexdocs.pm](https://hexdocs.pm/varint/api-reference.html).
## Benchmarks
Run the Benchee suite from the repository root with `MIX_ENV=bench`.
```sh
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.