Crate varuint[−][src]
Variable length signed and unsigned integer types. Types support up to 128-bit integers and 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.4"
Add imports to your code:
use varuint::{Varint, Varuint, Serializable, Deserializable};
Use it:
use std::mem; use std::io::Read; 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() }; { let mut buf = &mut arr as &mut [u8]; assert_eq!(size, v.serialize(&mut buf).unwrap()); } let mut buf: &[u8] = &arr; let mut read: &mut Read = &mut buf; assert_eq!(v, Varint::deserialize(read).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<=240then output a single byteA0equal toV. - If
V<=2031then outputA0as(V-240)/256 + 241andA1as(V-240)%256. - If
V<=67567then outputA0as248,A1as(V-2032)/256, andA2as(V-2032)%256. - If
V<=16777215then outputA0as249andA1throughA3as a little-endian 3-byte integer. - If
V<=4294967295then outputA0as250andA1..A4as a little-ending 4-byte integer. - If
V<=1099511627775then outputA0as251andA1..A5as a little-ending 5-byte integer. - If
V<=281474976710655then outputA0as252andA1..A6as a little-ending 6-byte integer. - If
V<=72057594037927935then outputA0as253andA1..A7as a little-ending 7-byte integer. - If
V<=9223372036854775807then outputA0as254andA1..A8as a little-ending 8-byte integer. - Otherwise output
A0as255andA1..A16as 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 |