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