Skip to main content

ostrya_core/
varint.rs

1//! Protobuf-style LEB128 varints.
2//!
3//! Little-endian base-128: each byte carries seven value bits, and the high
4//! bit is the continuation flag. This is the encoding used for the sizes in
5//! `ostree.sizes` packed entries and for static-delta operation operands.
6
7use crate::error::{Error, Result};
8
9/// Append the LEB128 encoding of `value` to `out`.
10pub fn encode(mut value: u64, out: &mut Vec<u8>) {
11    loop {
12        let byte = (value & 0x7f) as u8;
13        value >>= 7;
14        if value == 0 {
15            out.push(byte);
16            return;
17        }
18        out.push(byte | 0x80);
19    }
20}
21
22/// Decode a LEB128 varint from the front of `input`, returning the value and
23/// the number of bytes consumed.
24///
25/// Rejects a truncated sequence (a continuation bit with no following byte),
26/// any encoding whose value does not fit in 64 bits, and any non-minimal
27/// encoding (a multi-byte sequence whose terminating byte is `0x00`, which
28/// contributes no value bits and so has a shorter canonical form). Rejecting
29/// non-minimal forms keeps unpack-then-pack of an `ostree.sizes` entry
30/// byte-identical.
31pub fn decode(input: &[u8]) -> Result<(u64, usize)> {
32    let mut value: u64 = 0;
33    let mut shift: u32 = 0;
34    for (i, &byte) in input.iter().enumerate() {
35        let payload = u64::from(byte & 0x7f);
36        if shift >= 64 || (shift == 63 && payload > 1) {
37            return Err(Error::InvalidVarint("varint overflows 64 bits"));
38        }
39        value |= payload << shift;
40        if byte & 0x80 == 0 {
41            if i > 0 && byte == 0 {
42                return Err(Error::InvalidVarint("varint is not minimally encoded"));
43            }
44            return Ok((value, i + 1));
45        }
46        shift += 7;
47    }
48    Err(Error::InvalidVarint("varint is truncated"))
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    // Reference vectors for protobuf-style LEB128 (little-endian base-128).
56    const VECTORS: &[(u64, &[u8])] = &[
57        (0, &[0x00]),
58        (1, &[0x01]),
59        (127, &[0x7f]),
60        (128, &[0x80, 0x01]),
61        (255, &[0xff, 0x01]),
62        (300, &[0xac, 0x02]),
63        (16384, &[0x80, 0x80, 0x01]),
64        (2097151, &[0xff, 0xff, 0x7f]),
65        (
66            u64::MAX,
67            &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01],
68        ),
69    ];
70
71    #[test]
72    fn encodes_reference_vectors() {
73        for &(value, bytes) in VECTORS {
74            let mut out = Vec::new();
75            encode(value, &mut out);
76            assert_eq!(out, bytes, "encoding {value}");
77        }
78    }
79
80    #[test]
81    fn decodes_reference_vectors_with_length() {
82        for &(value, bytes) in VECTORS {
83            assert_eq!(
84                decode(bytes).unwrap(),
85                (value, bytes.len()),
86                "decoding {value}"
87            );
88        }
89    }
90
91    #[test]
92    fn decode_stops_at_the_varint_and_reports_consumed() {
93        // 300 followed by trailing bytes: consume only the two varint bytes.
94        let buf = [0xac, 0x02, 0xde, 0xad];
95        assert_eq!(decode(&buf).unwrap(), (300, 2));
96    }
97
98    #[test]
99    fn rejects_non_minimal_encodings() {
100        // A trailing 0x00 payload byte adds no value bits: the value has a
101        // shorter encoding, so the long form is not canonical.
102        assert!(matches!(
103            decode(&[0x80, 0x00]),
104            Err(Error::InvalidVarint("varint is not minimally encoded"))
105        ));
106        assert!(matches!(
107            decode(&[0xff, 0x80, 0x00]),
108            Err(Error::InvalidVarint("varint is not minimally encoded"))
109        ));
110        // A lone 0x00 is the minimal encoding of zero and stays valid.
111        assert_eq!(decode(&[0x00]).unwrap(), (0, 1));
112    }
113
114    #[test]
115    fn decode_then_encode_reproduces_every_accepted_input() {
116        // Every accepted encoding is minimal, so re-encoding the decoded value
117        // reproduces the original bytes exactly. Sweep a dense low range and
118        // the powers of two up to u64::MAX to cover each byte-length boundary.
119        let mut values: Vec<u64> = (0u64..2048).collect();
120        for shift in 0..64 {
121            let p = 1u64 << shift;
122            values.push(p.wrapping_sub(1));
123            values.push(p);
124            values.push(p.wrapping_add(1));
125        }
126        values.push(u64::MAX);
127        for value in values {
128            let mut encoded = Vec::new();
129            encode(value, &mut encoded);
130            let (decoded, consumed) = decode(&encoded).unwrap();
131            assert_eq!(decoded, value, "value {value}");
132            assert_eq!(consumed, encoded.len(), "consumed for {value}");
133            let mut reencoded = Vec::new();
134            encode(decoded, &mut reencoded);
135            assert_eq!(reencoded, encoded, "re-encode for {value}");
136        }
137    }
138
139    #[test]
140    fn rejects_truncated_and_overflowing_input() {
141        assert!(matches!(
142            decode(&[0x80]),
143            Err(Error::InvalidVarint("varint is truncated"))
144        ));
145        assert!(matches!(decode(&[]), Err(Error::InvalidVarint(_))));
146        // Eleven bytes: a 71-bit value cannot fit in u64.
147        let overflow = [0x80u8; 11];
148        assert!(matches!(
149            decode(&overflow),
150            Err(Error::InvalidVarint("varint overflows 64 bits"))
151        ));
152        // Tenth byte carrying more than one payload bit also overflows.
153        let overflow = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02];
154        assert!(matches!(
155            decode(&overflow),
156            Err(Error::InvalidVarint("varint overflows 64 bits"))
157        ));
158    }
159}