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.
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::<{ Codec::MAX_DECODE_UNITS_PER_VALUE }, Codec, _>(
138                &mut self.inner,
139                &mut self.buffer,
140            )
141        }
142    };
143}
144
145macro_rules! impl_for_policy {
146    (
147        $policy:ty,
148        $read_usize:ident,
149        $read_u64:ident,
150        $read_utf8_string_usize:ident,
151        $read_utf8_string_u64:ident,
152        {
153            $(($method:ident, $ty:ty, $doc:literal)),* $(,)?
154        }
155        $(,)?
156    ) => {
157        impl<R> Leb128Reader<R, $policy>
158        where
159            R: Input<Item = u8>,
160        {
161            $(
162                impl_read_value!($policy, $method, $ty, $doc);
163            )*
164
165            /// Reads a UTF-8 string prefixed by an unsigned LEB128 byte length.
166            ///
167            /// The length prefix is decoded as usize, so this format is
168            /// target-width dependent. Prefer a fixed-width length prefix for
169            /// persistent files and cross-platform protocols.
170            ///
171            /// # Parameters
172            ///
173            /// - max_len: Maximum accepted UTF-8 payload length in bytes.
174            ///
175            /// # Returns
176            ///
177            /// Returns the decoded UTF-8 string.
178            ///
179            /// # Errors
180            ///
181            /// Returns an I/O error for length or payload reads,
182            /// InvalidData when the encoded length exceeds max_len, or
183            /// InvalidData when the payload is not valid UTF-8.
184            #[inline]
185            pub fn $read_utf8_string_usize(
186                &mut self,
187                max_len: usize,
188            ) -> Result<String> {
189                let len = self.$read_usize()?;
190                read_utf8_payload(&mut self.inner, len, max_len)
191            }
192
193            /// Reads a UTF-8 string prefixed by an unsigned LEB128 u64 byte
194            /// length.
195            ///
196            /// Prefer this method over the usize variant for persistent files
197            /// and cross-platform protocols because the length field is
198            /// independent of the current Rust target's pointer width.
199            ///
200            /// # Parameters
201            ///
202            /// - max_len: Maximum accepted UTF-8 payload length in bytes.
203            ///
204            /// # Returns
205            ///
206            /// Returns the decoded UTF-8 string.
207            ///
208            /// # Errors
209            ///
210            /// Returns an input, conversion, or allocation error, or an
211            /// invalid-data error for a malformed or excessive length or
212            /// invalid UTF-8.
213            #[inline]
214            pub fn $read_utf8_string_u64(
215                &mut self,
216                max_len: usize,
217            ) -> Result<String> {
218                let len = self.$read_u64()?;
219                #[cfg(target_pointer_width = "64")]
220                let len = len as usize;
221                #[cfg(not(target_pointer_width = "64"))]
222                let len = usize_from_u64_len(len)?;
223                read_utf8_payload(&mut self.inner, len, max_len)
224            }
225        }
226    };
227}
228
229impl_for_policy!(
230    NonStrict,
231    read_usize_non_strict,
232    read_u64_non_strict,
233    read_utf8_string_usize_non_strict,
234    read_utf8_string_u64_non_strict,
235    {
236        (read_u8_non_strict, u8, "Reads an unsigned LEB128 u8."),
237        (read_u16_non_strict, u16, "Reads an unsigned LEB128 u16."),
238        (read_u32_non_strict, u32, "Reads an unsigned LEB128 u32."),
239        (read_u64_non_strict, u64, "Reads an unsigned LEB128 u64."),
240        (read_u128_non_strict, u128, "Reads an unsigned LEB128 u128."),
241        (read_usize_non_strict, usize, "Reads an unsigned LEB128 usize."),
242        (read_i8_non_strict, i8, "Reads a signed LEB128 i8."),
243        (read_i16_non_strict, i16, "Reads a signed LEB128 i16."),
244        (read_i32_non_strict, i32, "Reads a signed LEB128 i32."),
245        (read_i64_non_strict, i64, "Reads a signed LEB128 i64."),
246        (read_i128_non_strict, i128, "Reads a signed LEB128 i128."),
247        (read_isize_non_strict, isize, "Reads a signed LEB128 isize."),
248    },
249);
250impl_for_policy!(
251    Strict,
252    read_usize,
253    read_u64,
254    read_utf8_string_usize,
255    read_utf8_string_u64,
256    {
257        (read_u8, u8, "Reads an unsigned LEB128 u8."),
258        (read_u16, u16, "Reads an unsigned LEB128 u16."),
259        (read_u32, u32, "Reads an unsigned LEB128 u32."),
260        (read_u64, u64, "Reads an unsigned LEB128 u64."),
261        (read_u128, u128, "Reads an unsigned LEB128 u128."),
262        (read_usize, usize, "Reads an unsigned LEB128 usize."),
263        (read_i8, i8, "Reads a signed LEB128 i8."),
264        (read_i16, i16, "Reads a signed LEB128 i16."),
265        (read_i32, i32, "Reads a signed LEB128 i32."),
266        (read_i64, i64, "Reads a signed LEB128 i64."),
267        (read_i128, i128, "Reads a signed LEB128 i128."),
268        (read_isize, isize, "Reads a signed LEB128 isize."),
269    },
270);
271impl<R, P> Input for Leb128Reader<R, P>
272where
273    R: Input<Item = u8>,
274{
275    type Item = u8;
276
277    /// Reports whether the wrapped input is buffered.
278    ///
279    /// # Returns
280    ///
281    /// Returns the wrapped input's buffering state.
282    #[inline(always)]
283    fn is_buffered(&self) -> bool {
284        self.inner.is_buffered()
285    }
286
287    /// Reads up to `count` bytes into an indexed output range.
288    ///
289    /// # Parameters
290    ///
291    /// - `output`: Destination slice.
292    /// - `index`: First destination index.
293    /// - `count`: Maximum number of bytes to read.
294    ///
295    /// # Returns
296    ///
297    /// Returns the number of bytes read.
298    ///
299    /// # Errors
300    ///
301    /// Returns an error reported by the wrapped input.
302    ///
303    /// # Safety
304    ///
305    /// `index..index + count` must be a valid range within `output`.
306    #[inline(always)]
307    unsafe fn read_unchecked(&mut self, output: &mut [u8], index: usize, count: usize) -> Result<usize> {
308        // SAFETY: The caller upholds the wrapped input's range contract.
309        unsafe { self.inner.read_unchecked(output, index, count) }
310    }
311}
312
313impl<R, P> Seekable for Leb128Reader<R, P>
314where
315    R: Seekable<Unit = u8>,
316{
317    type Unit = u8;
318
319    /// Seeks the wrapped reader.
320    ///
321    /// # Parameters
322    ///
323    /// - `position`: Target seek position.
324    ///
325    /// # Returns
326    ///
327    /// Returns the new stream position.
328    ///
329    /// # Errors
330    ///
331    /// Returns the seek error reported by the wrapped reader.
332    #[inline(always)]
333    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
334        self.inner.seek_to(position)
335    }
336}