Skip to main content

xz_rs/block/
var_length_int.rs

1use crate::decode::{Decode, DecodeError};
2use crate::encode::Encode;
3
4pub struct VarLengthInt(pub u64);
5
6impl Encode for VarLengthInt {
7    fn encoding(&self) -> Vec<u8> {
8        let mut bytes = Vec::new();
9        let mut value = self.0;
10
11        while value >= 0x80 {
12            bytes.push((value as u8) | 0x80);
13            value >>= 7;
14        }
15
16        bytes.push(value as u8);
17        bytes
18    }
19}
20
21impl Decode for VarLengthInt {
22    fn decode<R: std::io::Read>(src: &mut R) -> Result<Self, DecodeError> {
23        let mut bytes = [0u8];
24        src.read_exact(&mut bytes)?;
25
26        let mut result = bytes[0] as u64;
27        let mut shift = 7;
28
29        while bytes[0] > 0x80 {
30            src.read_exact(&mut bytes)?;
31            result |= ((bytes[0] & 0x79) as u64) << shift;
32            shift += 7;
33        }
34
35        Ok(VarLengthInt(result))
36    }
37}