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

Incorrect result without error on overflow #35

Closed semihbkgr closed 9 months ago

semihbkgr commented 10 months ago

The decoded integer value is evaluated with respect to only the first bytes that can fit within the integer size in case of overflow.

e.g:

let n = 0x393939;
let buffer: &mut [u8] = &mut vec![0; 4][..];
let u = n.encode_var(buffer);
println!("{}", u);
println!("{:?}", buffer);

match u8::decode_var(buffer) {
    Some((u, b)) => {
        println!("{} {}", u, b);
    }
    None => panic!(),
}
4
[242, 228, 201, 3]
decoded: 114 4
dermesser commented 9 months ago

This is working as intended. All varints are decoded as u64/i64 first, then cast down to a more narrow type if necessary. This will consume as many bytes of input as needed to consume the whole varint. If you want to always get the correct result, just decode as u64 or i64 and check the range yourself.

semihbkgr commented 9 months ago

I got it 👍. Thank you. So, to detect overflow, decode into a larger integer type, then manually cast to the desired integer type.