5 releases (3 breaking)
0.4.0 | Oct 8, 2020 |
---|---|
0.3.0 | Nov 24, 2019 |
0.2.0 | Sep 26, 2019 |
0.1.1 | Sep 24, 2019 |
0.1.0 | Sep 24, 2019 |
#5 in #quantity
26 downloads per month
Used in 3 crates
(via xcell-types)
10KB
138 lines
vlq
Encode and decode variable-length quantity data.
Usage
Add this to your Cargo.toml
:
[dependencies]
vlq = { package = "vlq-rust", version = "0.4" }
License
Licensed under either of
- Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
lib.rs
:
Algorithm
Value-length quantity encoding is an implementation of variable-length integers.
Each byte is encoded into 7 bits, with the highest bit of the byte used to indicate
if there are any further bytes to read. Reading will continue until the highest bit
is 1
, or will result in an error if the number is too large to fit in the desired
type.
For example, the number 60000
(or 0xEA60
in hexadecimal):
11101010 01100000 [as u16]
11 1010100 1100000 [as separated into 7-bit groups]
1100000 1010100 11 [re-organized so least significant byte first]
11100000 11010100 00000011 [as VLQ-encoded variable-length integer]
Usage
Add this to your Cargo.toml
:
[dependencies]
vlq = { package = "vlq-rust", version = "0.2" }
Use ReadVlqExt
and WriteVlqExt
to get the read_vlq
and write_vlq
functions
on every std::io::Read
and std::io::Write
implementation.
Example
use vlq::{ReadVlqExt, WriteVlqExt};
let mut data = std::io::Cursor::new(vec![]);
data.write_vlq(std::u64::MAX).unwrap();
data.set_position(0);
let x: u64 = data.read_vlq().unwrap();
assert_eq!(x, std::u64::MAX);
let mut data = std::io::Cursor::new(vec![]);
data.write_vlq(std::i64::MIN).unwrap();
data.set_position(0);
let x: i64 = data.read_vlq().unwrap();
assert_eq!(x, std::i64::MIN);