1use crate::error::{Error, Result};
8
9pub 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
22pub 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 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 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 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 assert_eq!(decode(&[0x00]).unwrap(), (0, 1));
112 }
113
114 #[test]
115 fn decode_then_encode_reproduces_every_accepted_input() {
116 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 let overflow = [0x80u8; 11];
148 assert!(matches!(
149 decode(&overflow),
150 Err(Error::InvalidVarint("varint overflows 64 bits"))
151 ));
152 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}