Skip to main content

vlq_bij/
be128.rs

1//! Read and write base 128, big-endian, bijective variable-length quantities.
2//!
3//! This is the same [bijective VLQ](https://en.wikipedia.org/wiki/Variable-length_quantity#Removing_redundancy)
4//! used by [git](https://github.com/git/git/commit/d2c1898571a6a2324593e92163e8754880e0c1fb).
5//!
6//! The high bit of each byte indicates whether there is another byte to follow,
7//! and the lower seven bits hold the base 128 digit.
8//! These digits are orders with the most significant digits first.
9//!
10//! The base 128 digits are adjusted so that there is a unique encoding for each non-negative integer.
11//! The value represented by `n` `0x7f` digits is one less than the values represented by `n+1` `0x00` digits.
12//!
13//! The numeric sort order of the values matches the lexiographic sort order of encoded values.
14
15use std::io::{self, Read, Write};
16
17/// Possible errors when encoding and decoding.
18#[derive(Debug)]
19pub enum Error {
20    Overflow,
21    IO(io::Error),
22}
23
24impl PartialEq for Error {
25    fn eq(&self, other: &Self) -> bool {
26        match (self, other) {
27            (Error::Overflow, Error::Overflow) => true,
28            (Error::IO(a), Error::IO(b)) => a.kind() == b.kind(),
29            _ => false,
30        }
31    }
32}
33
34impl From<io::Error> for Error {
35    fn from(value: io::Error) -> Error {
36        Error::IO(value)
37    }
38}
39
40impl From<io::ErrorKind> for Error {
41    fn from(value: io::ErrorKind) -> Error {
42        Error::IO(value.into())
43    }
44}
45
46/// Types that can be encoded and decode from a VLQ.
47pub trait Vlq128: Sized {
48    /// Intermediate stat required for decoding a VLQ.
49    type DecState;
50    /// Initialize the decoding state given some initial bits.
51    ///
52    /// `input` is the bits, of which the lowest `bits` are valid, any higher bits will be zeroed.
53    fn dec_vlq_init(input: u8, bits: u8) -> Result<Self::DecState, Error>;
54    /// Accept some input bits, progress the state.
55    ///
56    /// `input` is the bits, of which the lowest `bits` are valid, any higher bits will be zeroed.
57    fn dec_vlq_step(state: Self::DecState, input: u8, bits: u8) -> Result<Self::DecState, Error>;
58    /// Finalize the output from the state.
59    fn dec_vlq_final(state: Self::DecState) -> Result<Self, Error>;
60
61    /// Intermediate state required for encoding a VLQ.
62    type EncState;
63    /// Encode the last bits of the value, this is called first.
64    ///
65    /// `bits` specifies how many of the low bits will be used.
66    fn enc_vlq_final(&self, bits: u8) -> Result<(Option<Self::EncState>, u8), Error>;
67    /// Encode ongoing bits of the value, in reverse order.
68    ///
69    /// `bits` specifies how many of the low bits will be used.
70    fn enc_vlq_step(state: Self::EncState, bits: u8)
71        -> Result<(Option<Self::EncState>, u8), Error>;
72}
73
74macro_rules! uvlq {
75    ($t:ty) => {
76        impl Vlq128 for $t {
77            type DecState = Self;
78
79            fn dec_vlq_init(input: u8, _: u8) -> Result<Self::DecState, Error> {
80                Ok(input.into())
81            }
82
83            fn dec_vlq_step(
84                state: Self::DecState,
85                input: u8,
86                bits: u8,
87            ) -> Result<Self::DecState, Error> {
88                state
89                    .checked_add(1)
90                    .and_then(|x| x.checked_mul(1 << bits))
91                    .and_then(|x| x.checked_add(input.into()))
92                    .ok_or(Error::Overflow)
93            }
94
95            fn dec_vlq_final(state: Self::DecState) -> Result<Self::DecState, Error> {
96                Ok(state)
97            }
98
99            type EncState = Self;
100
101            fn enc_vlq_final(&self, bits: u8) -> Result<(Option<Self::EncState>, u8), Error> {
102                let val = *self as u8;
103                let next = self >> bits;
104                Ok((if next == 0 { None } else { Some(next) }, val))
105            }
106            fn enc_vlq_step(
107                state: Self::EncState,
108                bits: u8,
109            ) -> Result<(Option<Self::EncState>, u8), Error> {
110                let val = state - 1;
111                let next = val >> bits;
112                Ok((if next == 0 { None } else { Some(next) }, val as u8))
113            }
114        }
115    };
116}
117
118uvlq!(u8);
119uvlq!(u16);
120uvlq!(u32);
121uvlq!(u64);
122uvlq!(u128);
123uvlq!(usize);
124
125/// Read a base-128 big-endian bijective variable length quantity from `reader`.
126///
127/// - Read errors are returned.
128/// - Wraparound overflows are caught and return `Error::Overflow`.
129pub fn decode<A: Vlq128>(mut reader: impl Read) -> Result<A, Error> {
130    let mut buf = [0];
131    reader.read_exact(&mut buf)?;
132    let mut state = <A>::dec_vlq_init(buf[0] & 0x7f, 7)?;
133    loop {
134        if buf[0] & 0x80 == 0 {
135            return A::dec_vlq_final(state);
136        }
137        reader.read_exact(&mut buf)?;
138        state = A::dec_vlq_step(state, buf[0] & 0x7f, 7)?;
139    }
140}
141
142/// Write a base-128 big-endian bijective variable length quantity to `writer`.
143///
144/// - Write errors are returned.
145pub fn encode<A: Vlq128>(mut writer: impl Write, value: &A) -> Result<usize, Error> {
146    let mut buf = Vec::new();
147    let (mut opt_state, mut val) = value.enc_vlq_final(7)?;
148    buf.push(val & 0x7f);
149    while let Some(state) = opt_state {
150        (opt_state, val) = A::enc_vlq_step(state, 7)?;
151        buf.push(val | 0x80);
152    }
153    buf.reverse();
154    writer.write_all(&buf)?;
155    return Ok(buf.len());
156}
157
158#[cfg(test)]
159static TESTS: [([u8; 4], usize, u64); 13] = [
160    ([0x00, 0x00, 0x00, 0x00], 1, 0x0),
161    ([0x7f, 0x00, 0x00, 0x00], 1, 0x7f),
162    ([0x80, 0x00, 0x00, 0x00], 2, 0x80),
163    ([0x80, 0x7f, 0x00, 0x00], 2, 0xff),
164    ([0x81, 0x00, 0x00, 0x00], 2, 0x100),
165    ([0xff, 0x7f, 0x00, 0x00], 2, 0x407f),
166    ([0x80, 0x80, 0x00, 0x00], 3, 0x4080),
167    ([0x82, 0xfe, 0x7f, 0x00], 3, 0xffff),
168    ([0x82, 0xff, 0x00, 0x00], 3, 0x10000),
169    ([0xbe, 0xfe, 0x7f, 0x00], 3, 0xfffff),
170    ([0xff, 0xff, 0x7f, 0x00], 3, 0x20407f),
171    ([0x80, 0x80, 0x80, 0x00], 4, 0x204080),
172    ([0xff, 0xff, 0xff, 0x7f], 4, 0x1020407f),
173];
174
175#[test]
176fn test_read_overflows() {
177    assert_eq!(
178        Err(Error::Overflow),
179        decode::<u8>(&mut &[0x80, 0xff, 0x00][..])
180    );
181    assert_eq!(Err(Error::Overflow), decode::<u8>(&mut &[0x81, 0x00][..]));
182    assert_eq!(
183        Err(Error::Overflow),
184        decode::<u16>(&mut &[0x82, 0xfe, 0xff, 0x00][..])
185    );
186    assert_eq!(
187        Err(Error::Overflow),
188        decode::<u16>(&mut &[0x82, 0xff, 0x00][..])
189    );
190}
191
192#[test]
193fn test_read_eof() {
194    assert_eq!(
195        Err(io::ErrorKind::UnexpectedEof.into()),
196        decode::<u64>(&mut &[0x80][..])
197    );
198    assert_eq!(
199        Err(io::ErrorKind::UnexpectedEof.into()),
200        decode::<u64>(&mut &[0xff][..])
201    );
202}
203
204#[test]
205fn test_read_cases() {
206    for tc in TESTS {
207        assert_eq!(Ok(tc.2), decode(tc.0.as_slice()));
208    }
209}
210
211#[test]
212fn test_write_cases() {
213    for tc in TESTS {
214        let mut buf = [0; 4];
215        println!("Input {:#x}:", tc.2);
216        assert_eq!(tc.1, encode(&mut buf[..], &tc.2).unwrap());
217        assert_eq!(tc.0, buf);
218    }
219}
220
221#[test]
222fn test_write_read_random() {
223    for _i in 0..1000 {
224        let n: u128 = rand::random();
225        let mut buf = [0; 19];
226        encode(&mut buf[..], &n).unwrap();
227        let x = decode(&buf[..]).unwrap();
228        assert_eq!(n, x);
229    }
230}