Skip to main content

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