qubit_io_binary/stream/leb128_reader.rs
1// =============================================================================
2// Copyright (c) 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9//! Reader for LEB128-encoded values.
10
11use core::marker::PhantomData;
12use std::io::Result;
13use std::io::SeekFrom;
14
15use qubit_codec_binary::Leb128Codec;
16use qubit_codec_binary::Leb128DecodePolicy;
17use qubit_codec_binary::NonStrict;
18use qubit_codec_binary::Strict;
19use qubit_io::ByteInput;
20use qubit_io::Input;
21use qubit_io::Seekable;
22use qubit_io::SeekableByteInput;
23
24use crate::util::MIN_CODEC_BUFFER_CAPACITY;
25use crate::util::read_leb128_from_reader;
26use crate::util::read_utf8_payload;
27#[cfg(not(target_pointer_width = "64"))]
28use crate::util::usize_from_u64_len;
29
30/// Reader wrapper for LEB128 integers.
31///
32/// The decoding policy is selected by the `P` type parameter. Use
33/// `Leb128Reader<R, NonStrict>` for permissive decoding and
34/// `Leb128Reader<R, Strict>` for canonical-only decoding.
35///
36/// A synchronous read error may occur after part of a value has been consumed.
37/// A later call starts at the current input position; it does not resume the
38/// failed value. Recover only at a framing boundary or trusted seek checkpoint.
39///
40/// # Target-width integers
41///
42/// `usize` and `isize` methods use the current Rust target's pointer width.
43/// Prefer fixed-width integer methods such as `read_u64` or `read_i64` for
44/// persistent files and cross-platform protocols.
45///
46/// # Type Parameters
47///
48/// - `R`: Underlying byte input.
49/// - `P`: LEB128 canonicality policy.
50///
51/// # Examples
52///
53/// ```
54/// use qubit_codec_binary::NonStrict;
55/// use qubit_io_binary::Leb128Reader;
56///
57/// let mut reader = Leb128Reader::<_, NonStrict>::new(
58/// std::io::Cursor::new([0xAC, 0x02]),
59/// );
60/// assert_eq!(reader.read_u32_non_strict()?, 300);
61/// # Ok::<(), std::io::Error>(())
62/// ```
63pub struct Leb128Reader<R, P> {
64 /// Wrapped byte input.
65 inner: R,
66 /// Scratch storage for the largest LEB128 payload.
67 buffer: [u8; MIN_CODEC_BUFFER_CAPACITY],
68 /// Associates the selected decoding policy without storing a value.
69 marker: PhantomData<fn() -> P>,
70}
71
72impl_input_methods!(Leb128Reader<R, P> where R: ByteInput);
73impl_seekable_methods!(Leb128Reader<R, P> where R: SeekableByteInput);
74
75impl<R, P> Leb128Reader<R, P>
76where
77 P: Leb128DecodePolicy,
78{
79 /// Creates a LEB128 reader.
80 ///
81 /// # Parameters
82 ///
83 /// - `inner`: Underlying byte input.
84 ///
85 /// # Returns
86 ///
87 /// Returns a reader using policy `P`.
88 #[must_use]
89 #[inline]
90 pub const fn new(inner: R) -> Self {
91 Self {
92 inner,
93 buffer: [0; MIN_CODEC_BUFFER_CAPACITY],
94 marker: PhantomData,
95 }
96 }
97
98 /// Returns whether this reader rejects non-canonical encodings.
99 ///
100 /// # Returns
101 ///
102 /// Returns `true` when policy `P` requires canonical encodings.
103 #[must_use]
104 #[inline(always)]
105 pub const fn is_strict(&self) -> bool {
106 P::STRICT
107 }
108
109 /// Returns a shared reference to the underlying reader.
110 ///
111 /// # Returns
112 ///
113 /// Returns the wrapped reader.
114 #[must_use]
115 #[inline(always)]
116 pub const fn inner(&self) -> &R {
117 &self.inner
118 }
119
120 /// Returns an exclusive reference to the underlying reader.
121 ///
122 /// # Returns
123 ///
124 /// Returns mutable access to the wrapped reader.
125 #[must_use]
126 #[inline(always)]
127 pub fn inner_mut(&mut self) -> &mut R {
128 &mut self.inner
129 }
130
131 /// Consumes this wrapper and returns the underlying reader.
132 ///
133 /// # Returns
134 ///
135 /// Returns the wrapped reader.
136 #[must_use]
137 #[inline(always)]
138 pub fn into_inner(self) -> R {
139 self.inner
140 }
141}
142
143macro_rules! impl_read_value {
144 ($policy:ty, $method:ident, $ty:ty, $doc:literal) => {
145 #[doc = $doc]
146 #[doc = ""]
147 #[doc = "# Returns"]
148 #[doc = ""]
149 #[doc = concat!("Returns the decoded `", stringify!($ty), "`.")]
150 #[doc = ""]
151 #[doc = "# Errors"]
152 #[doc = ""]
153 #[doc = "Returns an input error or an invalid-data error when the \
154 payload is malformed or violates the selected policy."]
155 #[inline(always)]
156 pub fn $method(&mut self) -> Result<$ty> {
157 type Codec = Leb128Codec<$ty, $policy>;
158
159 read_leb128_from_reader::<{ Codec::MAX_DECODE_UNITS_PER_VALUE }, Codec, _>(
160 &mut self.inner,
161 &mut self.buffer,
162 )
163 }
164 };
165}
166
167macro_rules! impl_for_policy {
168 (
169 $policy:ty,
170 $read_usize:ident,
171 $read_u64:ident,
172 $read_utf8_string_usize:ident,
173 $read_utf8_string_u64:ident,
174 {
175 $(($method:ident, $ty:ty, $doc:literal)),* $(,)?
176 }
177 $(,)?
178 ) => {
179 impl<R> Leb128Reader<R, $policy>
180 where
181 R: ByteInput,
182 {
183 $(
184 impl_read_value!($policy, $method, $ty, $doc);
185 )*
186
187 /// Reads a UTF-8 string prefixed by an unsigned LEB128 byte length.
188 ///
189 /// The length prefix is decoded as usize, so this format is
190 /// target-width dependent. Prefer a fixed-width length prefix for
191 /// persistent files and cross-platform protocols.
192 ///
193 /// # Parameters
194 ///
195 /// - max_len: Maximum accepted UTF-8 payload length in bytes.
196 ///
197 /// # Returns
198 ///
199 /// Returns the decoded UTF-8 string.
200 ///
201 /// # Errors
202 ///
203 /// Returns an I/O error for length or payload reads,
204 /// InvalidData when the encoded length exceeds max_len, or
205 /// InvalidData when the payload is not valid UTF-8.
206 ///
207 /// # Stream position
208 ///
209 /// If the decoded length exceeds `max_len`, the length prefix has been
210 /// consumed, but the payload remains unread. If UTF-8 validation fails,
211 /// the prefix and complete payload have been consumed. These operations
212 /// do not roll back; recover only at an outer framing boundary or a
213 /// trusted seek checkpoint. See [`StringReadExt`](crate::StringReadExt)
214 /// for the shared length-prefixed read contract.
215 #[inline]
216 pub fn $read_utf8_string_usize(
217 &mut self,
218 max_len: usize,
219 ) -> Result<String> {
220 let len = self.$read_usize()?;
221 read_utf8_payload(&mut self.inner, len, max_len)
222 }
223
224 /// Reads a UTF-8 string prefixed by an unsigned LEB128 u64 byte
225 /// length.
226 ///
227 /// Prefer this method over the usize variant for persistent files
228 /// and cross-platform protocols because the length field is
229 /// independent of the current Rust target's pointer width.
230 ///
231 /// # Parameters
232 ///
233 /// - max_len: Maximum accepted UTF-8 payload length in bytes.
234 ///
235 /// # Returns
236 ///
237 /// Returns the decoded UTF-8 string.
238 ///
239 /// # Errors
240 ///
241 /// Returns an input, conversion, or allocation error, or an
242 /// invalid-data error for a malformed or excessive length or
243 /// invalid UTF-8.
244 ///
245 /// # Stream position
246 ///
247 /// If the decoded length exceeds `max_len`, the length prefix has been
248 /// consumed, but the payload remains unread. If UTF-8 validation fails,
249 /// the prefix and complete payload have been consumed. These operations
250 /// do not roll back; recover only at an outer framing boundary or a
251 /// trusted seek checkpoint. See [`StringReadExt`](crate::StringReadExt)
252 /// for the shared length-prefixed read contract.
253 #[inline]
254 pub fn $read_utf8_string_u64(
255 &mut self,
256 max_len: usize,
257 ) -> Result<String> {
258 let len = self.$read_u64()?;
259 #[cfg(target_pointer_width = "64")]
260 let len = len as usize;
261 #[cfg(not(target_pointer_width = "64"))]
262 let len = usize_from_u64_len(len)?;
263 read_utf8_payload(&mut self.inner, len, max_len)
264 }
265 }
266 };
267}
268
269impl_for_policy!(
270 NonStrict,
271 read_usize_non_strict,
272 read_u64_non_strict,
273 read_utf8_string_usize_non_strict,
274 read_utf8_string_u64_non_strict,
275 {
276 (read_u8_non_strict, u8, "Reads an unsigned LEB128 u8."),
277 (read_u16_non_strict, u16, "Reads an unsigned LEB128 u16."),
278 (read_u32_non_strict, u32, "Reads an unsigned LEB128 u32."),
279 (read_u64_non_strict, u64, "Reads an unsigned LEB128 u64."),
280 (read_u128_non_strict, u128, "Reads an unsigned LEB128 u128."),
281 (read_usize_non_strict, usize, "Reads an unsigned LEB128 usize."),
282 (read_i8_non_strict, i8, "Reads a signed LEB128 i8."),
283 (read_i16_non_strict, i16, "Reads a signed LEB128 i16."),
284 (read_i32_non_strict, i32, "Reads a signed LEB128 i32."),
285 (read_i64_non_strict, i64, "Reads a signed LEB128 i64."),
286 (read_i128_non_strict, i128, "Reads a signed LEB128 i128."),
287 (read_isize_non_strict, isize, "Reads a signed LEB128 isize."),
288 },
289);
290impl_for_policy!(
291 Strict,
292 read_usize,
293 read_u64,
294 read_utf8_string_usize,
295 read_utf8_string_u64,
296 {
297 (read_u8, u8, "Reads an unsigned LEB128 u8."),
298 (read_u16, u16, "Reads an unsigned LEB128 u16."),
299 (read_u32, u32, "Reads an unsigned LEB128 u32."),
300 (read_u64, u64, "Reads an unsigned LEB128 u64."),
301 (read_u128, u128, "Reads an unsigned LEB128 u128."),
302 (read_usize, usize, "Reads an unsigned LEB128 usize."),
303 (read_i8, i8, "Reads a signed LEB128 i8."),
304 (read_i16, i16, "Reads a signed LEB128 i16."),
305 (read_i32, i32, "Reads a signed LEB128 i32."),
306 (read_i64, i64, "Reads a signed LEB128 i64."),
307 (read_i128, i128, "Reads a signed LEB128 i128."),
308 (read_isize, isize, "Reads a signed LEB128 isize."),
309 },
310);
311impl<R, P> Input for Leb128Reader<R, P>
312where
313 R: ByteInput,
314{
315 /// Byte element produced by this reader.
316 type Item = u8;
317
318 /// Reports whether the wrapped input is buffered.
319 ///
320 /// # Returns
321 ///
322 /// Returns the wrapped input's buffering state.
323 #[inline(always)]
324 fn is_buffered(&self) -> bool {
325 self.inner.is_buffered()
326 }
327
328 /// Reads up to `count` bytes into an indexed output range.
329 ///
330 /// # Parameters
331 ///
332 /// - `output`: Destination slice.
333 /// - `index`: First destination index.
334 /// - `count`: Maximum number of bytes to read.
335 ///
336 /// # Returns
337 ///
338 /// Returns the number of bytes read.
339 ///
340 /// # Errors
341 ///
342 /// Returns an error reported by the wrapped input.
343 ///
344 /// # Safety
345 ///
346 /// `index..index + count` must be a valid range within `output`.
347 #[inline(always)]
348 unsafe fn read_unchecked(&mut self, output: &mut [u8], index: usize, count: usize) -> Result<usize> {
349 // SAFETY: The caller upholds the wrapped input's range contract.
350 unsafe { self.inner.read_unchecked(output, index, count) }
351 }
352}
353
354impl<R, P> Seekable for Leb128Reader<R, P>
355where
356 R: SeekableByteInput,
357{
358 /// Unit used to address positions in the wrapped byte stream.
359 type Unit = u8;
360
361 /// Seeks the wrapped reader.
362 ///
363 /// # Parameters
364 ///
365 /// - `position`: Target seek position.
366 ///
367 /// # Returns
368 ///
369 /// Returns the new stream position.
370 ///
371 /// # Errors
372 ///
373 /// Returns the seek error reported by the wrapped reader.
374 #[inline(always)]
375 fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
376 self.inner.seek_to(position)
377 }
378}