Varint is an alternative way of storing integer numbers.
Varints allow for the storage of larger integer types in a smaller amount of
space. It does this by storing an integer using the 7
lower bits and a flag
in the most-significant bit. This flag is set to 1
when more bytes should
be read. The groups of 7
bits are then added from the least-significant
group first.
signed
(default) which allows for signed integers to be encoded, this also enables
the zigzag
featurezigzag
(default) which allows for encoding and decoding of signed integers to and
from unsigned integersio
(default) which implements VarintReader
and VarintWriter
on std::io
``rust
// to allow the use of the
VarintWriter::write*varintfunctions
use varint_rs::VarintWriter;
// to allow the use of the
VarintReader::read*varint` functions
use varint_rs::VarintReader;
// an example to use for the buffer use std::io::Cursor;
// create an i32 set to 300
let number: i32 = 300;
// create a buffer for the varint to be writen to
// an i32 can be 4
bytes maximum, so we pre-allocate the capacity
let mut buffer: Cursor
// now we can write the varint into the buffer
// 300
should only use 2
bytes instead of all 4
// the write_*_varint
functions may return an std::io::Error
buffer.writei32varint(number).unwrap();
// we reset the cursor pos back to 0
, this isn't varint stuff
buffer.set_position(0);
// now we can read the varint from the buffer
// we should read 300
which was the number we stored
// the read_*_varint
functions may return an std::io::Error
let number: i32 = buffer.readi32varint().unwrap();
```
Much of this code is ported from the varint crate by Cruz Bishop. A massive thanks to them for the awesome alogrithms!