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