Crate varuint[−][src]
Variable length signed and unsigned integer types. Types support up to 128-bit integers, both are encoded to 1-17 bytes.
Encoding rules are based on SQLite 4 Varuint type
with modifications for support of 128-bit long integers.
Varint is encoded using the Protobuf ZigZag approach
and reuses Varuint
as a storage.
Unlike the Protobuf encoding rules Varuint
needs the first byte only to find out the length of the
whole value. Microbenchmarks say that it is a lot faster.
How to use
Add dependency to your Cargo.toml:
[dependencies]
varuint = "0.5"
Add imports to your code:
use varuint::{Varint, Varuint, Serializable, Deserializable};
Use it:
use std::mem; use varuint::*; fn test_varint(v: i128, size: usize) { let v = Varint(v); assert_eq!(size, v.size_hint()); let mut arr: [u8; 17] = unsafe { mem::uninitialized() }; assert_eq!(size, v.serialize(&mut (&mut arr as &mut [u8])).unwrap()); assert_eq!(v, Varint::deserialize(&mut (&arr as &[u8])).unwrap()); } fn main() { test_varint(0, 1); test_varint(1, 1); test_varint(-1, 1); }
Encoding rules
Encoding rules for Varuint
are (assuming value is V
):
- If
V<=240
then output a single byteA0
equal toV
. - If
V<=2031
then outputA0
as(V-240)/256 + 241
andA1
as(V-240)%256
. - If
V<=67567
then outputA0
as248
,A1
as(V-2032)/256
, andA2
as(V-2032)%256
. - If
V<=16777215
then outputA0
as249
andA1
throughA3
as a little-endian 3-byte integer. - If
V<=4294967295
then outputA0
as250
andA1..A4
as a little-endian 4-byte integer. - If
V<=1099511627775
then outputA0
as251
andA1..A5
as a little-endian 5-byte integer. - If
V<=281474976710655
then outputA0
as252
andA1..A6
as a little-endian 6-byte integer. - If
V<=72057594037927935
then outputA0
as253
andA1..A7
as a little-endian 7-byte integer. - If
V<=9223372036854775807
then outputA0
as254
andA1..A8
as a little-endian 8-byte integer. - Otherwise output
A0
as255
andA1..A16
as a little-endian 16-byte integer.
Varint
converted to the Varuint
in the first place and then encoded as an unsigned integer.
Conversion method makes values closer to 0 take less space.
See Protobuf docs
for details.
Structs
Varint |
Variable length signed integer. |
Varuint |
Variable length unsigned integer. |
Traits
Deserializable |
Trait for deserializable types |
Serializable |
Trait for serializable types |