1use crate::error::{Error, Result};
9
10pub 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
23pub 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 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 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 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 assert_eq!(decode(&[0x00]).unwrap(), (0, 1));
124 }
125
126 #[test]
127 fn decode_then_encode_reproduces_every_accepted_input() {
128 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 let overflow = [0x80u8; 11];
160 assert!(matches!(
161 decode(&overflow),
162 Err(Error::InvalidVarint("varint overflows 64 bits"))
163 ));
164 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}