Skip to main content

nativeview_codec/
reader.rs

1//! Strictly bounds-checked little-endian binary reader.
2
3use crate::{canonical_f32_bits, canonical_f64_bits, CodecError, NvDecode};
4
5/// Default maximum container nesting depth (`read_vec` / `read_opt`) guarding against
6/// stack-overflow DoS on recursive `#[derive(NvCodec)]` types.
7pub const DEFAULT_MAX_DEPTH: usize = 64;
8
9/// Strictly bounds-checked little-endian binary reader.
10#[derive(Debug, Clone)]
11pub struct ByteReader<'a> {
12    data: &'a [u8],
13    pos: usize,
14    zero_byte_budget: usize,
15    depth: usize,
16    max_depth: usize,
17}
18
19impl<'a> ByteReader<'a> {
20    #[inline]
21    pub const fn new(data: &'a [u8]) -> Self {
22        Self {
23            data,
24            pos: 0,
25            zero_byte_budget: data.len().saturating_add(64),
26            depth: 0,
27            max_depth: DEFAULT_MAX_DEPTH,
28        }
29    }
30
31    /// Overrides the maximum nested container depth (default [`DEFAULT_MAX_DEPTH`] = 64).
32    #[inline]
33    pub const fn with_max_depth(mut self, max_depth: usize) -> Self {
34        self.max_depth = max_depth;
35        self
36    }
37
38    #[inline]
39    fn enter_depth(&mut self) -> Result<(), CodecError> {
40        if self.depth >= self.max_depth {
41            return Err(CodecError::DepthExceeded {
42                max: self.max_depth,
43            });
44        }
45        self.depth += 1;
46        Ok(())
47    }
48
49    #[inline]
50    pub const fn pos(&self) -> usize {
51        self.pos
52    }
53
54    #[inline]
55    pub const fn remaining(&self) -> usize {
56        self.data.len() - self.pos
57    }
58
59    #[inline]
60    pub fn remaining_slice(&self) -> &'a [u8] {
61        &self.data[self.pos..]
62    }
63
64    #[inline]
65    pub fn ensure_remaining(&self, needed: usize) -> Result<(), CodecError> {
66        let remaining = self.remaining();
67        if needed > remaining {
68            Err(CodecError::Truncated { needed, remaining })
69        } else {
70            Ok(())
71        }
72    }
73
74    #[inline]
75    pub fn read_exact(&mut self, len: usize) -> Result<&'a [u8], CodecError> {
76        self.ensure_remaining(len)?;
77        let start = self.pos;
78        self.pos = start + len;
79        Ok(&self.data[start..self.pos])
80    }
81
82    #[inline]
83    pub fn read_array<const N: usize>(&mut self) -> Result<[u8; N], CodecError> {
84        let slice = self.read_exact(N)?;
85        let mut out = [0u8; N];
86        out.copy_from_slice(slice);
87        Ok(out)
88    }
89
90    /// Advances past `len` bytes without inspecting them (`Truncated` if fewer remain).
91    #[inline]
92    pub fn skip(&mut self, len: usize) -> Result<(), CodecError> {
93        self.read_exact(len).map(|_| ())
94    }
95
96    #[inline]
97    pub fn expect_magic<const N: usize>(&mut self, magic: &[u8; N]) -> Result<(), CodecError> {
98        let got = self.read_exact(N)?;
99        if got == magic {
100            Ok(())
101        } else {
102            Err(CodecError::BadMagic)
103        }
104    }
105
106    #[inline]
107    pub fn expect_zero(&mut self, len: usize) -> Result<(), CodecError> {
108        let slice = self.read_exact(len)?;
109        for &b in slice {
110            if b != 0 {
111                return Err(CodecError::NonZeroReserved(u64::from(b)));
112            }
113        }
114        Ok(())
115    }
116
117    #[inline]
118    pub fn read_u8(&mut self) -> Result<u8, CodecError> {
119        Ok(self.read_exact(1)?[0])
120    }
121
122    #[inline]
123    pub fn read_i8(&mut self) -> Result<i8, CodecError> {
124        Ok(self.read_u8()? as i8)
125    }
126
127    /// Reads a strict boolean (`0 => false`, `1 => true`; any other byte returns `BadBool`).
128    #[inline]
129    pub fn read_bool(&mut self) -> Result<bool, CodecError> {
130        match self.read_u8()? {
131            0 => Ok(false),
132            1 => Ok(true),
133            other => Err(CodecError::BadBool(other)),
134        }
135    }
136
137    #[inline]
138    pub fn read_u16(&mut self) -> Result<u16, CodecError> {
139        Ok(u16::from_le_bytes(self.read_array::<2>()?))
140    }
141
142    #[inline]
143    pub fn read_i16(&mut self) -> Result<i16, CodecError> {
144        Ok(i16::from_le_bytes(self.read_array::<2>()?))
145    }
146
147    /// Reads a little-endian 24-bit unsigned integer (e.g. WebP `VP8X` canvas dimensions).
148    #[inline]
149    pub fn read_u24(&mut self) -> Result<u32, CodecError> {
150        let [b0, b1, b2] = self.read_array::<3>()?;
151        Ok(u32::from_le_bytes([b0, b1, b2, 0]))
152    }
153
154    #[inline]
155    pub fn read_u32(&mut self) -> Result<u32, CodecError> {
156        Ok(u32::from_le_bytes(self.read_array::<4>()?))
157    }
158
159    #[inline]
160    pub fn read_i32(&mut self) -> Result<i32, CodecError> {
161        Ok(i32::from_le_bytes(self.read_array::<4>()?))
162    }
163
164    #[inline]
165    pub fn read_u64(&mut self) -> Result<u64, CodecError> {
166        Ok(u64::from_le_bytes(self.read_array::<8>()?))
167    }
168
169    #[inline]
170    pub fn read_i64(&mut self) -> Result<i64, CodecError> {
171        Ok(i64::from_le_bytes(self.read_array::<8>()?))
172    }
173
174    /// Reads a canonical little-endian `f32` (`-0.0` -> `+0.0`, NaN -> canonical quiet NaN).
175    #[inline]
176    pub fn read_f32(&mut self) -> Result<f32, CodecError> {
177        let v = f32::from_le_bytes(self.read_array::<4>()?);
178        Ok(f32::from_bits(canonical_f32_bits(v)))
179    }
180
181    /// Reads a raw little-endian `f32` preserving exact IEEE-754 bit patterns.
182    #[inline]
183    pub fn read_f32_raw(&mut self) -> Result<f32, CodecError> {
184        Ok(f32::from_le_bytes(self.read_array::<4>()?))
185    }
186
187    /// Reads a canonical little-endian `f64` (`-0.0` -> `+0.0`, NaN -> canonical quiet NaN).
188    #[inline]
189    pub fn read_f64(&mut self) -> Result<f64, CodecError> {
190        let v = f64::from_le_bytes(self.read_array::<8>()?);
191        Ok(f64::from_bits(canonical_f64_bits(v)))
192    }
193
194    /// Reads a raw little-endian `f64` preserving exact IEEE-754 bit patterns.
195    #[inline]
196    pub fn read_f64_raw(&mut self) -> Result<f64, CodecError> {
197        Ok(f64::from_le_bytes(self.read_array::<8>()?))
198    }
199
200    /// Appends `count` raw little-endian `u32` words to `out` with one bounds check and one
201    /// reservation (`Truncated` before any allocation if fewer than `count * 4` bytes remain).
202    pub fn read_u32_words_into(&mut self, count: usize, out: &mut Vec<u32>) -> Result<(), CodecError> {
203        let byte_len = count.checked_mul(4).ok_or(CodecError::LenOverflow {
204            len: count,
205            max: usize::MAX / 4,
206        })?;
207        let bytes = self.read_exact(byte_len)?;
208        out.reserve(count);
209        out.extend(bytes.as_chunks::<4>().0.iter().map(|&w| u32::from_le_bytes(w)));
210        Ok(())
211    }
212
213    /// Reads a `u32` sequence length bounded by `max` AND guaranteed to fit `min_elem_bytes`
214    /// within the remaining slice (prevents OOM pre-allocation on malicious buffers).
215    #[inline]
216    pub fn read_len(&mut self, max: usize, min_elem_bytes: usize) -> Result<usize, CodecError> {
217        let len = self.read_u32()? as usize;
218        if len > max {
219            return Err(CodecError::LenOverflow { len, max });
220        }
221        if let Some(max_possible) = self.remaining().checked_div(min_elem_bytes)
222            && len > max_possible
223        {
224            return Err(CodecError::Truncated {
225                needed: len.saturating_mul(min_elem_bytes),
226                remaining: self.remaining(),
227            });
228        }
229        Ok(len)
230    }
231
232    /// Reads a `u32`-length-prefixed byte slice bounded by `max`.
233    #[inline]
234    pub fn read_bytes(&mut self, max: usize) -> Result<&'a [u8], CodecError> {
235        let len = self.read_u32()? as usize;
236        if len > max {
237            return Err(CodecError::LenOverflow { len, max });
238        }
239        self.read_exact(len)
240    }
241
242    /// Reads a `u16`-length-prefixed byte slice bounded by `max`.
243    #[inline]
244    pub fn read_bytes_u16(&mut self, max: usize) -> Result<&'a [u8], CodecError> {
245        let len = usize::from(self.read_u16()?);
246        if len > max {
247            return Err(CodecError::LenOverflow { len, max });
248        }
249        self.read_exact(len)
250    }
251
252    /// Reads a `u8`-length-prefixed byte slice bounded by `max`.
253    #[inline]
254    pub fn read_bytes_u8(&mut self, max: usize) -> Result<&'a [u8], CodecError> {
255        let len = usize::from(self.read_u8()?);
256        if len > max {
257            return Err(CodecError::LenOverflow { len, max });
258        }
259        self.read_exact(len)
260    }
261
262    /// Reads a `u32`-length-prefixed UTF-8 string slice bounded by `max`.
263    #[inline]
264    pub fn read_str(&mut self, max: usize) -> Result<&'a str, CodecError> {
265        let bytes = self.read_bytes(max)?;
266        core::str::from_utf8(bytes).map_err(|_| CodecError::InvalidUtf8)
267    }
268
269    /// Reads a `u16`-length-prefixed UTF-8 string slice bounded by `max`.
270    #[inline]
271    pub fn read_str_u16(&mut self, max: usize) -> Result<&'a str, CodecError> {
272        let bytes = self.read_bytes_u16(max)?;
273        core::str::from_utf8(bytes).map_err(|_| CodecError::InvalidUtf8)
274    }
275
276    /// Reads a `u8`-length-prefixed UTF-8 string slice bounded by `max`.
277    #[inline]
278    pub fn read_str_u8(&mut self, max: usize) -> Result<&'a str, CodecError> {
279        let bytes = self.read_bytes_u8(max)?;
280        core::str::from_utf8(bytes).map_err(|_| CodecError::InvalidUtf8)
281    }
282
283    /// Reads a `u32`-length-prefixed owned `String` bounded by `max`.
284    #[inline]
285    pub fn read_string(&mut self, max: usize) -> Result<String, CodecError> {
286        Ok(self.read_str(max)?.to_owned())
287    }
288
289    /// Reads a `u32`-length-prefixed vector bounded by `max` elements and `min_elem_bytes` per item.
290    ///
291    /// When `min_elem_bytes == 0`, no upfront capacity is allocated (so lying lengths fail with 0
292    /// heap allocations) and zero-byte-progress items are bounded to `O(input_len)` across the
293    /// reader's lifetime to prevent `Vec<Vec<()>>` CPU-amplification DoS attacks.
294    pub fn read_vec<T>(
295        &mut self,
296        max: usize,
297        min_elem_bytes: usize,
298        mut decode_item: impl FnMut(&mut Self) -> Result<T, CodecError>,
299    ) -> Result<Vec<T>, CodecError> {
300        self.enter_depth()?;
301        let res = (|| {
302            let count = self.read_len(max, min_elem_bytes)?;
303            if min_elem_bytes > 0 {
304                let mut out = Vec::with_capacity(count);
305                for _ in 0..count {
306                    out.push(decode_item(self)?);
307                }
308                return Ok(out);
309            }
310            let mut out = Vec::new();
311            for i in 0..count {
312                let before = self.pos;
313                let item = decode_item(self)?;
314                if self.pos == before {
315                    let remaining_items = count - i;
316                    if remaining_items > self.zero_byte_budget {
317                        return Err(CodecError::LenOverflow {
318                            len: count,
319                            max: self.zero_byte_budget,
320                        });
321                    }
322                    self.zero_byte_budget -= 1;
323                }
324                out.push(item);
325            }
326            Ok(out)
327        })();
328        self.depth -= 1;
329        res
330    }
331
332    /// Reads an optional value tagged by a strict boolean byte (`0 = None`, `1 = Some(T)`).
333    #[inline]
334    pub fn read_opt<T>(
335        &mut self,
336        decode_some: impl FnOnce(&mut Self) -> Result<T, CodecError>,
337    ) -> Result<Option<T>, CodecError> {
338        if self.read_bool()? {
339            self.enter_depth()?;
340            let res = decode_some(self);
341            self.depth -= 1;
342            Ok(Some(res?))
343        } else {
344            Ok(None)
345        }
346    }
347
348    /// Decodes a value implementing [`NvDecode`].
349    #[inline]
350    pub fn read_value<T: NvDecode>(&mut self) -> Result<T, CodecError> {
351        T::decode(self)
352    }
353
354    /// Asserts that no trailing unread bytes remain.
355    #[inline]
356    pub fn finish(self) -> Result<(), CodecError> {
357        let rem = self.remaining();
358        if rem != 0 {
359            Err(CodecError::TrailingBytes(rem))
360        } else {
361            Ok(())
362        }
363    }
364}