sqlite_fsr/utils/
varint.rs

1pub fn parse_varint(bytes: &[u8]) -> (i64, usize) {
2    let mut value: u64 = 0;  // Use u64 to avoid premature sign extension
3    let mut len = 0;
4    
5    for &byte in bytes.iter().take(9) {
6        len += 1;
7        
8        if len == 9 {
9            // 9th byte uses all 8 bits
10            value = (value << 8) | (byte as u64);
11            return (value as i64, len);
12        } else {
13            // First 8 bytes use lower 7 bits
14            value = (value << 7) | ((byte & 0x7F) as u64);
15            
16            if byte & 0x80 == 0 {
17                // High bit is 0, we're done
18                return (value as i64, len);
19            }
20        }
21    }
22    
23    // Should not reach here if bytes.len() >= 9
24    (value as i64, len)
25}
26
27pub fn encode_varint(mut value: i64) -> Vec<u8> {
28    let mut varint_bytes = Vec::new();
29
30    loop {
31        let byte = (value & 0x7F) as u8; // take 7 bits
32        value >>= 7;
33        if value != 0 {
34            varint_bytes.push(byte | 0x80); // set MSB = 1 (more bytes follow)
35        } else {
36            varint_bytes.push(byte); // last byte, MSB = 0
37            break;
38        }
39    }
40
41    return varint_bytes
42}