#varint #signed-integer #zigzag #io-read #google #io-write #read-write

no-std varint-rs

A small, zero dependency varint implementation in Rust

17 stable releases

2.2.0 Nov 25, 2020
2.1.4 Nov 25, 2020
1.1.5 Nov 23, 2020

#390 in Encoding

Download history 128569/week @ 2024-11-16 77850/week @ 2024-11-23 64971/week @ 2024-11-30 158437/week @ 2024-12-07 117526/week @ 2024-12-14 24032/week @ 2024-12-21 63466/week @ 2024-12-28 129554/week @ 2025-01-04 145037/week @ 2025-01-11 101613/week @ 2025-01-18 126780/week @ 2025-01-25 123971/week @ 2025-02-01 131184/week @ 2025-02-08 131184/week @ 2025-02-15 171877/week @ 2025-02-22 138409/week @ 2025-03-01

594,241 downloads per month
Used in 36 crates (8 directly)

Apache-2.0

20KB
273 lines

crates.io docs.rs crates.io

Varint-rs

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.

Features

  • signed (default): allows for signed integers to be encoded and decoded using zigzag encoding
  • std (default): implements the VarintReader and VarintWriter traits respectively on:
    • all std::io::Read implementors
    • all std::io::Write implementors

Note: Disabling the std feature (which is enabled by default) allows for the crate to be used in a #![no_std] environment.

Example

// to allow the use of the `VarintWriter::write_*_varint` functions
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<Vec<u8>> = Cursor::new(Vec::with_capacity(4));

// 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.write_i32_varint(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.read_i32_varint().unwrap();

Note: This example assumes that the default features are in use.

Credit

Much of this code is ported from the varint crate by Cruz Bishop. A massive thanks to them for the awesome alogrithms!

No runtime deps

Features