Skip to main content

vlqencoding/
lib.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8//! VLQ (Variable-length quantity) encoding.
9
10use std::io;
11use std::io::Read;
12use std::io::Write;
13
14pub trait VLQEncode<T> {
15    /// Encode an integer to a VLQ byte array and write it directly to a stream.
16    ///
17    /// # Examples
18    ///
19    /// ```
20    /// use vlqencoding::VLQEncode;
21    /// let mut v = vec![];
22    ///
23    /// let x = 120u8;
24    /// v.write_vlq(x)
25    ///     .expect("writing an encoded u8 to a vec should work");
26    /// assert_eq!(v, vec![120]);
27    ///
28    /// let x = 22742734291u64;
29    /// v.write_vlq(x)
30    ///     .expect("writing an encoded u64 to a vec should work");
31    ///
32    /// assert_eq!(v, vec![120, 211, 171, 202, 220, 84]);
33    /// ```
34    ///
35    /// Signed integers are encoded via zig-zag:
36    ///
37    /// ```
38    /// use vlqencoding::VLQEncode;
39    /// let mut v = vec![];
40    ///
41    /// let x = -3i8;
42    /// v.write_vlq(x)
43    ///     .expect("writing an encoded i8 to a vec should work");
44    /// assert_eq!(v, vec![5]);
45    ///
46    /// let x = 1000i16;
47    /// v.write_vlq(x)
48    ///     .expect("writing an encoded i16 to a vec should work");
49    /// assert_eq!(v, vec![5, 208, 15]);
50    /// ```
51    fn write_vlq(&mut self, value: T) -> io::Result<()>;
52}
53
54pub trait VLQLen {
55    /// Report byte len of encoded value.
56    ///
57    /// # Examples
58    ///
59    /// ```
60    /// use vlqencoding::VLQLen;
61    /// assert_eq!(0u8.vlq_len(), 1);
62    /// assert_eq!(128u8.vlq_len(), 2);
63    /// ```
64    fn vlq_len(self) -> usize;
65}
66
67pub trait VLQDecode<T> {
68    /// Read a VLQ byte array from stream and decode it to an integer.
69    ///
70    /// # Examples
71    ///
72    /// ```
73    /// use std::io::Cursor;
74    /// use std::io::ErrorKind;
75    /// use std::io::Seek;
76    /// use std::io::SeekFrom;
77    ///
78    /// use vlqencoding::VLQDecode;
79    ///
80    /// let mut c = Cursor::new(vec![120u8, 211, 171, 202, 220, 84]);
81    ///
82    /// let x: Result<u8, _> = c.read_vlq();
83    /// assert_eq!(x.unwrap(), 120u8);
84    ///
85    /// let x: Result<u16, _> = c.read_vlq();
86    /// assert_eq!(x.unwrap_err().kind(), ErrorKind::InvalidData);
87    ///
88    /// c.seek(SeekFrom::Start(1)).expect("seek should work");
89    /// let x: Result<u64, _> = c.read_vlq();
90    /// assert_eq!(x.unwrap(), 22742734291u64);
91    /// ```
92    ///
93    /// Signed integers are decoded via zig-zag:
94    ///
95    /// ```
96    /// use std::io::Cursor;
97    /// use std::io::ErrorKind;
98    /// use std::io::Seek;
99    /// use std::io::SeekFrom;
100    ///
101    /// use vlqencoding::VLQDecode;
102    ///
103    /// let mut c = Cursor::new(vec![5u8, 208, 15]);
104    ///
105    /// let x: Result<i8, _> = c.read_vlq();
106    /// assert_eq!(x.unwrap(), -3i8);
107    ///
108    /// let x: Result<i8, _> = c.read_vlq();
109    /// assert_eq!(x.unwrap_err().kind(), ErrorKind::InvalidData);
110    ///
111    /// c.seek(SeekFrom::Start(1)).expect("seek should work");
112    /// let x: Result<i32, _> = c.read_vlq();
113    /// assert_eq!(x.unwrap(), 1000i32);
114    /// ```
115    fn read_vlq(&mut self) -> io::Result<T>;
116}
117
118pub trait VLQDecodeAt<T> {
119    /// Read a VLQ byte array from the given offset and decode it to an integer.
120    ///
121    /// Returns `Ok((decoded_integer, bytes_read))` on success.
122    ///
123    /// This is similar to `VLQDecode::read_vlq`. It's for immutable `AsRef<[u8]>` instead of
124    /// a mutable `io::Read` object.
125    ///
126    /// # Examples
127    ///
128    /// ```
129    /// use std::io::ErrorKind;
130    ///
131    /// use vlqencoding::VLQDecodeAt;
132    ///
133    /// let c = &[120u8, 211, 171, 202, 220, 84, 255];
134    ///
135    /// let x: Result<(u8, _), _> = c.read_vlq_at(0);
136    /// assert_eq!(x.unwrap(), (120u8, 1));
137    ///
138    /// let x: Result<(u64, _), _> = c.read_vlq_at(1);
139    /// assert_eq!(x.unwrap(), (22742734291u64, 5));
140    ///
141    /// let x: Result<(u64, _), _> = c.read_vlq_at(6);
142    /// assert_eq!(x.unwrap_err().kind(), ::std::io::ErrorKind::InvalidData);
143    ///
144    /// let x: Result<(u64, _), _> = c.read_vlq_at(7);
145    /// assert_eq!(x.unwrap_err().kind(), ::std::io::ErrorKind::InvalidData);
146    /// ```
147    fn read_vlq_at(&self, offset: usize) -> io::Result<(T, usize)>;
148}
149
150macro_rules! impl_unsigned_primitive {
151    ($T: ident) => {
152        impl<W: Write + ?Sized> VLQEncode<$T> for W {
153            fn write_vlq(&mut self, value: $T) -> io::Result<()> {
154                let mut buf = [0u8];
155                let mut value = value;
156                loop {
157                    let mut byte = (value & 127) as u8;
158                    let next = value >> 7;
159                    if next != 0 {
160                        byte |= 128;
161                    }
162                    buf[0] = byte;
163                    self.write_all(&buf)?;
164                    value = next;
165                    if value == 0 {
166                        break;
167                    }
168                }
169                Ok(())
170            }
171        }
172
173        impl<R: Read + ?Sized> VLQDecode<$T> for R {
174            fn read_vlq(&mut self) -> io::Result<$T> {
175                let mut buf = [0u8];
176                let mut value = 0 as $T;
177                let mut base = 1 as $T;
178                let base_multiplier = (1 << 7) as $T;
179                loop {
180                    self.read_exact(&mut buf)?;
181                    let byte = buf[0];
182                    value = ($T::from(byte & 127))
183                        .checked_mul(base)
184                        .and_then(|v| v.checked_add(value))
185                        .ok_or(io::ErrorKind::InvalidData)?;
186                    if byte & 128 == 0 {
187                        break;
188                    }
189                    base = base
190                        .checked_mul(base_multiplier)
191                        .ok_or(io::ErrorKind::InvalidData)?;
192                }
193                Ok(value)
194            }
195        }
196
197        impl<R: AsRef<[u8]>> VLQDecodeAt<$T> for R {
198            fn read_vlq_at(&self, offset: usize) -> io::Result<($T, usize)> {
199                let buf = self.as_ref();
200                let mut size = 0;
201                let mut value = 0 as $T;
202                let mut base = 1 as $T;
203                let base_multiplier = (1 << 7) as $T;
204                loop {
205                    if let Some(byte) = buf.get(offset + size) {
206                        size += 1;
207                        value = ($T::from(byte & 127))
208                            .checked_mul(base)
209                            .and_then(|v| v.checked_add(value))
210                            .ok_or(io::ErrorKind::InvalidData)?;
211                        if byte & 128 == 0 {
212                            break;
213                        }
214                        base = base
215                            .checked_mul(base_multiplier)
216                            .ok_or(io::ErrorKind::InvalidData)?;
217                    } else {
218                        return Err(io::ErrorKind::InvalidData.into());
219                    }
220                }
221                Ok((value, size))
222            }
223        }
224
225        impl VLQLen for $T {
226            fn vlq_len(mut self) -> usize {
227                let mut byte_count = 0;
228                loop {
229                    byte_count += 1;
230                    self >>= 7;
231                    if self == 0 {
232                        return byte_count;
233                    }
234                }
235            }
236        }
237    };
238}
239
240impl_unsigned_primitive!(usize);
241impl_unsigned_primitive!(u64);
242impl_unsigned_primitive!(u32);
243impl_unsigned_primitive!(u16);
244impl_unsigned_primitive!(u8);
245
246macro_rules! impl_signed_primitive {
247    ($T: ty, $U: ty) => {
248        impl<W: Write + ?Sized> VLQEncode<$T> for W {
249            fn write_vlq(&mut self, v: $T) -> io::Result<()> {
250                self.write_vlq(((v << 1) ^ (v >> (<$U>::BITS - 1))) as $U)
251            }
252        }
253
254        impl<R: Read + ?Sized> VLQDecode<$T> for R {
255            fn read_vlq(&mut self) -> io::Result<$T> {
256                (self.read_vlq() as Result<$U, _>).map(|n| ((n >> 1) as $T) ^ -((n & 1) as $T))
257            }
258        }
259
260        impl<R: AsRef<[u8]>> VLQDecodeAt<$T> for R {
261            fn read_vlq_at(&self, offset: usize) -> io::Result<($T, usize)> {
262                (self.read_vlq_at(offset) as Result<($U, _), _>)
263                    .map(|(n, s)| (((n >> 1) as $T) ^ -((n & 1) as $T), s))
264            }
265        }
266
267        impl VLQLen for $T {
268            fn vlq_len(self) -> usize {
269                (((self << 1) ^ (self >> (<$U>::BITS - 1))) as $U).vlq_len()
270            }
271        }
272    };
273}
274
275impl_signed_primitive!(isize, usize);
276impl_signed_primitive!(i64, u64);
277impl_signed_primitive!(i32, u32);
278impl_signed_primitive!(i16, u16);
279impl_signed_primitive!(i8, u8);
280
281#[cfg(test)]
282mod tests {
283    use std::io;
284    use std::io::Cursor;
285    use std::io::Seek;
286    use std::io::SeekFrom;
287
288    use quickcheck::quickcheck;
289
290    use super::*;
291
292    macro_rules! check_round_trip {
293        ($N: expr) => {{
294            let mut v = vec![];
295            let mut x = $N;
296            v.write_vlq(x).expect("write");
297
298            let byte_len = v.len();
299
300            // `z` and `y` below are helpful for the compiler to figure out the return type of
301            // `read_vlq_at`, and `read_vlq`.
302            #[allow(unused_assignments)]
303            let mut z = x;
304            let t = v.read_vlq_at(0).unwrap();
305            z = t.0;
306
307            let mut c = Cursor::new(v);
308            let y = x;
309            x = c.read_vlq().unwrap();
310            x == y && y == z && t.1 == c.position() as usize && x.vlq_len() == byte_len
311        }};
312    }
313
314    #[test]
315    fn test_round_trip_manual() {
316        for i in (0..64)
317            .flat_map(|b| vec![1u64 << b, (1 << b) + 1, (1 << b) - 1].into_iter())
318            .chain(vec![0xb3a73ce2ff2, 0xab54a98ceb1f0ad2])
319            .flat_map(|i| vec![i, !i].into_iter())
320        {
321            assert!(check_round_trip!(i as i8));
322            assert!(check_round_trip!(i as i16));
323            assert!(check_round_trip!(i as i32));
324            assert!(check_round_trip!(i as i64));
325            assert!(check_round_trip!(i as isize));
326            assert!(check_round_trip!(i as u8));
327            assert!(check_round_trip!(i as u16));
328            assert!(check_round_trip!(i as u32));
329            assert!(check_round_trip!(i));
330            assert!(check_round_trip!(i as usize));
331        }
332    }
333
334    #[test]
335    fn test_read_errors() {
336        let mut c = Cursor::new(vec![]);
337        assert_eq!(
338            (c.read_vlq() as io::Result<u64>).unwrap_err().kind(),
339            io::ErrorKind::UnexpectedEof
340        );
341
342        let mut c = Cursor::new(vec![255, 129]);
343        assert_eq!(
344            (c.read_vlq() as io::Result<u64>).unwrap_err().kind(),
345            io::ErrorKind::UnexpectedEof
346        );
347
348        c.seek(SeekFrom::Start(0)).unwrap();
349        assert_eq!(
350            (c.read_vlq() as io::Result<u8>).unwrap_err().kind(),
351            io::ErrorKind::InvalidData
352        );
353    }
354
355    #[test]
356    fn test_zig_zag() {
357        let mut c = Cursor::new(vec![]);
358        for (i, u) in [
359            (0, 0),
360            (-1, 1),
361            (1, 2),
362            (-2, 3),
363            (-127, 253),
364            (127, 254),
365            (-128i8, 255u8),
366        ] {
367            c.seek(SeekFrom::Start(0)).expect("seek");
368            c.write_vlq(i).expect("write");
369            c.seek(SeekFrom::Start(0)).expect("seek");
370            let x: u8 = c.read_vlq().unwrap();
371            assert_eq!(x, u);
372        }
373    }
374
375    quickcheck! {
376        fn test_round_trip_u64_quickcheck(x: u64) -> bool {
377            check_round_trip!(x)
378        }
379
380        fn test_round_trip_i64_quickcheck(x: i64) -> bool {
381            check_round_trip!(x)
382        }
383
384        fn test_round_trip_u8_quickcheck(x: u8) -> bool {
385            check_round_trip!(x)
386        }
387
388        fn test_round_trip_i8_quickcheck(x: i8) -> bool {
389            check_round_trip!(x)
390        }
391    }
392}