[−][src]Crate vint64
vint64
: simple and efficient variable-length integer encoding
About
This crate implements a variable-length encoding for 64-bit little endian integers with a number of properties which make it superior in every way to other variable-length integer encodings like LEB128, SQLite "Varuints" or CBOR:
- Capable of expressing the full 64-bit integer range with a maximum of 9-bytes
- No loops involved in decoding: just (unaligned) loads, masks, and shifts
- No complex branch-heavy logic - decoding is CTZ + shifts and sanity checks
- Total length of a
vint64
can be determined via the first byte alone
Some precedent for this sort of encoding can be found in the Extensible Binary Meta Language (used by e.g. the Matroska media container format), however note that the specific type of "vint" used by this format still requires a loop to decode.
Usage
// Encode a 64-bit integer as a vint64 let encoded = vint64::encode(42); assert_eq!(encoded.as_ref(), &[0x55]); // Decode an encoded vint64 with trailing data let mut slice: &[u8] = &[0x55, 0xde, 0xad, 0xbe, 0xef]; let decoded = vint64::decode(&mut slice).unwrap(); assert_eq!(decoded, 42); assert_eq!(slice, &[0xde, 0xad, 0xbe, 0xef]); // Zigzag encoding can be used to encode signed vint64s. // Decode with `vint64::decode_signed`. let signed = vint64::encode_signed(-42); assert_eq!(signed.as_ref(), &[0xa7]);
Structs
Error | Error type: indicates decoding failure |
Vint64 |
|
Constants
MAX_BYTES | Maximum length of a |
Functions
decode | Decode a |
decode_signed | Decode a zigzag-encoded |
encode | Encode an unsigned 64-bit integer as |
encode_signed | Encode a signed integer as a zigzag-encoded |
length_hint | Get the length of a |