Skip to main content

aft_store/content/
codec.rs

1//! The byte encoding content records use: LEB128 varints, and a string table
2//! per record so every string is stored once however often it is used.
3
4use std::collections::HashMap;
5
6use super::DecodeError;
7
8/// Writes one record's fields; strings go to the record's table.
9#[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    /// A string by its index in the table.
50    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    /// An optional string: 0 for none, otherwise its index plus one.
60    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    /// Raw bytes stored inline, not in the table.
85    pub fn blob(&mut self, value: &[u8]) {
86        self.usize(value.len());
87        self.out.extend_from_slice(value);
88    }
89
90    /// The string table followed by the fields.
91    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/// Reads what an [`Encoder`] wrote.
104#[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        // Each table entry takes at least its one-byte length, so the bytes
120        // after the count bound how many there can be.
121        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    /// A count of items still to come, each at least one byte long; see
216    /// [`count_of`](Self::count_of).
217    pub fn count(&mut self) -> Result<usize, DecodeError> {
218        self.count_of(1)
219    }
220
221    /// A count of items still to come, each taking at least `min_len` bytes,
222    /// checked against the bytes left. A count the bytes cannot hold fails
223    /// here, before the caller reserves room for that many items, so a
224    /// damaged or hostile count cannot ask for an allocation larger than a
225    /// real record of the same size would need.
226    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    /// A record with an empty string table, `count` as its first field, and
253    /// `filler` zero bytes after it.
254    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        // Twelve bytes follow the count: four items of three bytes fit, four
267        // items of four bytes do not.
268        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        // A count whose byte total overflows is refused, not wrapped around.
274        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        // A table count followed by 64 KiB of one-byte (empty) strings.
284        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        // A count as large as the whole input, its own bytes included, is
296        // still more strings than the bytes after it can hold.
297        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        // Exactly as many strings as bytes after the count decode.
304        assert!(Decoder::new(&table(64 * 1024)).is_ok());
305    }
306}