dermesser / integer-encoding-rs

Integer encoding for primitive integer types: Supports varint/varint+zigzag and fixed-length integer encoding and decoding, and provides synchronous and asynchronous Write/Read types for easily writing/reading integers.
Other
66 stars 16 forks source link

Integer encoding to buffer fails #20

Closed rkfox closed 3 years ago

rkfox commented 3 years ago

The code below fails. I'm not sure why.

let num = 1654648798768;
let required_space = num.required_space();
let mut dst = Vec::with_capacity(required_space);
num.encode_var(&mut dst);
dermesser commented 3 years ago

You need to declare the type of num correctly (as i64) and also import the VarInt trait so that you can use its methods. This works:

use integer_encoding;

use integer_encoding::VarInt;

fn main() {
    let num: i64 = 1654648798768;
    let required_space = num.required_space();
    let mut dst = Vec::with_capacity(required_space);
    num.encode_var(&mut dst);
}
rkfox commented 3 years ago

This code (explicitly typed) still panics.

thread 'test::test' panicked at 'assertion failed: dst.len() >= self.required_space()', /home/user/.cargo/registry/src/github.com-1ecc6299db9ec823/integer-encoding-3.0.2/src/varint.rs:177:9

Although this code works fine.

dermesser commented 3 years ago

yes, so about encode_var: the documentation states this size requirement (https://docs.rs/integer-encoding/3.0.2/integer_encoding/trait.VarInt.html#required-methods). The reason is avoiding unexpected allocations.

If you want to extend a vector, the writer trait may be used instead:

use integer_encoding;

use std::io::Write;
use integer_encoding::VarIntWriter;

fn main() {
    let num: i64 = 1654648798768;
    let mut dst = vec![];
    dst.write_varint(num);
}