Skip to main content

ostrya_core/
varint.rs

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