aft_store/content/
codec.rs1use std::collections::HashMap;
5
6use super::DecodeError;
7
8#[derive(Debug, Default)]
10pub struct Encoder {
11 out: Vec<u8>,
12 strings: Vec<Vec<u8>>,
13 index: HashMap<Vec<u8>, u32>,
14}
15
16impl Encoder {
17 #[expect(
18 clippy::cast_possible_truncation,
19 reason = "each byte keeps the low seven bits on purpose"
20 )]
21 pub fn u64(&mut self, mut value: u64) {
22 while value >= 0x80 {
23 self.out.push((value as u8) | 0x80);
24 value >>= 7;
25 }
26 self.out.push(value as u8);
27 }
28
29 pub fn u32(&mut self, value: u32) {
30 self.u64(u64::from(value));
31 }
32
33 pub fn usize(&mut self, value: usize) {
34 self.u64(value as u64);
35 }
36
37 pub fn bool(&mut self, value: bool) {
38 self.out.push(u8::from(value));
39 }
40
41 pub fn byte(&mut self, value: u8) {
42 self.out.push(value);
43 }
44
45 pub fn str(&mut self, value: &str) {
46 self.bytes_ref(value.as_bytes());
47 }
48
49 fn bytes_ref(&mut self, value: &[u8]) {
51 let next = u32::try_from(self.strings.len()).expect("fewer than 2^32 strings");
52 let index = *self.index.entry(value.to_vec()).or_insert_with(|| {
53 self.strings.push(value.to_vec());
54 next
55 });
56 self.u32(index);
57 }
58
59 pub fn opt_str(&mut self, value: Option<&str>) {
61 match value {
62 None => self.u64(0),
63 Some(value) => {
64 let next = u32::try_from(self.strings.len()).expect("fewer than 2^32 strings");
65 let index = *self
66 .index
67 .entry(value.as_bytes().to_vec())
68 .or_insert_with(|| {
69 self.strings.push(value.as_bytes().to_vec());
70 next
71 });
72 self.u64(u64::from(index) + 1);
73 }
74 }
75 }
76
77 pub fn strs(&mut self, values: &[String]) {
78 self.usize(values.len());
79 for value in values {
80 self.str(value);
81 }
82 }
83
84 pub fn blob(&mut self, value: &[u8]) {
86 self.usize(value.len());
87 self.out.extend_from_slice(value);
88 }
89
90 pub fn finish(self) -> Vec<u8> {
92 let mut table = Self::default();
93 table.usize(self.strings.len());
94 for string in &self.strings {
95 table.blob(string);
96 }
97 let mut out = table.out;
98 out.extend_from_slice(&self.out);
99 out
100 }
101}
102
103#[derive(Debug)]
105pub struct Decoder<'a> {
106 input: &'a [u8],
107 position: usize,
108 strings: Vec<&'a str>,
109}
110
111impl<'a> Decoder<'a> {
112 pub fn new(input: &'a [u8]) -> Result<Self, DecodeError> {
113 let mut decoder = Self {
114 input,
115 position: 0,
116 strings: Vec::new(),
117 };
118 let count = decoder.usize()?;
119 if count > input.len() - decoder.position {
122 return Err(DecodeError("string table count"));
123 }
124 let mut strings = Vec::with_capacity(count);
125 for _ in 0..count {
126 let bytes = decoder.blob()?;
127 strings
128 .push(std::str::from_utf8(bytes).map_err(|_| DecodeError("string is not UTF-8"))?);
129 }
130 decoder.strings = strings;
131 Ok(decoder)
132 }
133
134 pub fn u64(&mut self) -> Result<u64, DecodeError> {
135 let mut value = 0u64;
136 for shift in (0..64).step_by(7) {
137 let byte = *self
138 .input
139 .get(self.position)
140 .ok_or(DecodeError("varint runs past the end"))?;
141 self.position += 1;
142 value |= u64::from(byte & 0x7f) << shift;
143 if byte & 0x80 == 0 {
144 return Ok(value);
145 }
146 }
147 Err(DecodeError("varint is too long"))
148 }
149
150 pub fn u32(&mut self) -> Result<u32, DecodeError> {
151 u32::try_from(self.u64()?).map_err(|_| DecodeError("value exceeds 32 bits"))
152 }
153
154 pub fn usize(&mut self) -> Result<usize, DecodeError> {
155 usize::try_from(self.u64()?).map_err(|_| DecodeError("value exceeds usize"))
156 }
157
158 pub fn bool(&mut self) -> Result<bool, DecodeError> {
159 match self.byte()? {
160 0 => Ok(false),
161 1 => Ok(true),
162 _ => Err(DecodeError("bool is neither 0 nor 1")),
163 }
164 }
165
166 pub fn byte(&mut self) -> Result<u8, DecodeError> {
167 let byte = *self
168 .input
169 .get(self.position)
170 .ok_or(DecodeError("record ends early"))?;
171 self.position += 1;
172 Ok(byte)
173 }
174
175 pub fn str(&mut self) -> Result<&'a str, DecodeError> {
176 let index = self.usize()?;
177 self.strings
178 .get(index)
179 .copied()
180 .ok_or(DecodeError("string index out of range"))
181 }
182
183 pub fn string(&mut self) -> Result<String, DecodeError> {
184 self.str().map(str::to_string)
185 }
186
187 pub fn opt_string(&mut self) -> Result<Option<String>, DecodeError> {
188 match self.usize()? {
189 0 => Ok(None),
190 index => self
191 .strings
192 .get(index - 1)
193 .map(|value| Some((*value).to_string()))
194 .ok_or(DecodeError("string index out of range")),
195 }
196 }
197
198 pub fn strings(&mut self) -> Result<Vec<String>, DecodeError> {
199 let count = self.count()?;
200 (0..count).map(|_| self.string()).collect()
201 }
202
203 pub fn blob(&mut self) -> Result<&'a [u8], DecodeError> {
204 let len = self.usize()?;
205 let end = self
206 .position
207 .checked_add(len)
208 .filter(|end| *end <= self.input.len())
209 .ok_or(DecodeError("bytes run past the end"))?;
210 let bytes = &self.input[self.position..end];
211 self.position = end;
212 Ok(bytes)
213 }
214
215 pub fn count(&mut self) -> Result<usize, DecodeError> {
218 self.count_of(1)
219 }
220
221 pub fn count_of(&mut self, min_len: usize) -> Result<usize, DecodeError> {
227 debug_assert!(min_len > 0, "every item takes at least one byte");
228 let count = self.usize()?;
229 let left = self.input.len() - self.position;
230 if count
231 .checked_mul(min_len)
232 .is_none_or(|needed| needed > left)
233 {
234 return Err(DecodeError("count exceeds the bytes left"));
235 }
236 Ok(count)
237 }
238
239 pub fn finish(self) -> Result<(), DecodeError> {
240 if self.position == self.input.len() {
241 Ok(())
242 } else {
243 Err(DecodeError("bytes after the record"))
244 }
245 }
246}
247
248#[cfg(test)]
249mod tests {
250 use super::*;
251
252 fn counted(count: u64, filler: usize) -> Vec<u8> {
255 let mut out = Encoder::default();
256 out.u64(count);
257 for _ in 0..filler {
258 out.byte(0);
259 }
260 out.finish()
261 }
262
263 #[test]
264 fn a_count_is_bounded_by_the_bytes_its_items_need() {
265 let bytes = counted(4, 12);
266 assert_eq!(Decoder::new(&bytes).unwrap().count_of(3), Ok(4));
269 assert_eq!(
270 Decoder::new(&bytes).unwrap().count_of(4),
271 Err(DecodeError("count exceeds the bytes left"))
272 );
273 let bytes = counted(u64::MAX / 2, 12);
275 assert_eq!(
276 Decoder::new(&bytes).unwrap().count_of(4),
277 Err(DecodeError("count exceeds the bytes left"))
278 );
279 }
280
281 #[test]
282 fn a_string_table_longer_than_its_bytes_is_refused() {
283 let table = |count: u64| {
285 let mut out = Encoder::default();
286 out.u64(count);
287 let mut bytes = out.out;
288 bytes.resize(bytes.len() + 64 * 1024, 0);
289 bytes
290 };
291 assert_eq!(
292 Decoder::new(&table(1 << 31)).unwrap_err(),
293 DecodeError("string table count")
294 );
295 let whole = table(64 * 1024 + 3);
298 assert_eq!(whole.len(), 64 * 1024 + 3);
299 assert_eq!(
300 Decoder::new(&whole).unwrap_err(),
301 DecodeError("string table count")
302 );
303 assert!(Decoder::new(&table(64 * 1024)).is_ok());
305 }
306}