Skip to main content

qubit_io_binary/stream/
buffered_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::{
11    collections::TryReserveError,
12    io::{
13        Result,
14        SeekFrom,
15    },
16};
17
18#[cfg(not(target_pointer_width = "64"))]
19use crate::util::usize_from_u64_len;
20use crate::util::{
21    MIN_CODEC_BUFFER_CAPACITY,
22    read_utf8_payload,
23};
24use qubit_codec::TranscodeDecodeInput;
25use qubit_codec_binary::{
26    Leb128Codec,
27    Leb128DecodePolicy,
28    NonStrict,
29    Strict,
30};
31use qubit_io::{
32    Buffer,
33    Input,
34    Seekable,
35};
36
37use super::internal::TranscodeDecodeInputExt;
38
39/// Buffered reader for LEB128 integers.
40///
41/// Values are decoded directly from the internal input buffer while the codec
42/// scans for the LEB128 terminating byte.
43///
44/// # Buffered state
45///
46/// This reader may prefetch bytes from the wrapped reader. As a result,
47/// [`Self::inner`] can observe an underlying stream position ahead of the
48/// logical position exposed by this wrapper.
49///
50/// # Target-width integers
51///
52/// `usize` and `isize` methods use the current Rust target's pointer width.
53/// Prefer fixed-width integer methods such as `read_u64` or `read_i64` for
54/// persistent files and cross-platform protocols.
55///
56/// # Type Parameters
57///
58/// - `R`: Underlying byte input.
59/// - `P`: LEB128 canonicality policy.
60pub struct BufferedLeb128Reader<R, P>
61where
62    R: Input<Item = u8>,
63{
64    /// Buffered codec input and wrapped reader.
65    input: TranscodeDecodeInput<R>,
66    /// Associates the selected decoding policy without storing a value.
67    marker: PhantomData<fn() -> P>,
68}
69
70impl<R, P> BufferedLeb128Reader<R, P>
71where
72    R: Input<Item = u8>,
73    P: Leb128DecodePolicy,
74{
75    /// Creates a buffered LEB128 reader with the default buffer capacity.
76    ///
77    /// # Parameters
78    ///
79    /// - `inner`: Underlying byte input.
80    ///
81    /// # Returns
82    ///
83    /// Returns a buffered reader using policy `P`.
84    #[must_use]
85    #[inline]
86    pub fn new(inner: R) -> Self {
87        Self {
88            input: TranscodeDecodeInput::new(inner),
89            marker: PhantomData,
90        }
91    }
92
93    /// Creates a buffered LEB128 reader with at least `capacity` bytes.
94    ///
95    /// # Parameters
96    ///
97    /// - `inner`: Underlying byte input.
98    /// - `capacity`: Requested internal buffer capacity in bytes.
99    ///
100    /// # Returns
101    ///
102    /// Returns a buffered reader whose capacity also satisfies the largest
103    /// supported codec payload.
104    #[must_use]
105    #[inline]
106    pub fn with_capacity(inner: R, capacity: usize) -> Self {
107        Self {
108            input: TranscodeDecodeInput::with_capacity(
109                inner,
110                capacity.max(MIN_CODEC_BUFFER_CAPACITY),
111            ),
112            marker: PhantomData,
113        }
114    }
115
116    /// Tries to create a buffered LEB128 reader with at least `capacity` bytes.
117    ///
118    /// # Errors
119    ///
120    /// Returns an allocation error when the requested buffer cannot be
121    /// allocated.
122    #[inline]
123    pub fn try_with_capacity(
124        inner: R,
125        capacity: usize,
126    ) -> std::result::Result<Self, TryReserveError> {
127        Ok(Self {
128            input: TranscodeDecodeInput::try_with_capacity(
129                inner,
130                capacity.max(MIN_CODEC_BUFFER_CAPACITY),
131            )?,
132            marker: PhantomData,
133        })
134    }
135
136    /// Returns whether this reader rejects non-canonical encodings.
137    ///
138    /// # Returns
139    ///
140    /// Returns `true` when policy `P` requires canonical encodings.
141    #[must_use]
142    #[inline(always)]
143    pub const fn is_strict(&self) -> bool {
144        P::STRICT
145    }
146
147    /// Returns a shared reference to the underlying reader.
148    ///
149    /// The underlying reader may already be positioned past unread bytes held
150    /// in this wrapper's internal buffer.
151    ///
152    /// # Returns
153    ///
154    /// Returns the wrapped reader.
155    #[must_use]
156    #[inline(always)]
157    pub const fn inner(&self) -> &R {
158        self.input.inner()
159    }
160
161    /// Consumes this wrapper and preserves its unread buffered bytes.
162    ///
163    /// # Returns
164    ///
165    /// Returns the wrapped reader and the buffer whose [`Buffer::readable`]
166    /// slice contains every prefetched byte not yet consumed logically. To
167    /// continue the same logical stream, consume that slice before reading
168    /// from the returned reader.
169    #[inline(always)]
170    #[must_use = "the returned inner reader and unread buffer must be handled"]
171    pub fn into_parts(self) -> (R, Buffer<u8>) {
172        self.input.into_parts()
173    }
174}
175
176macro_rules! impl_read_value {
177    ($policy:ty, $method:ident, $ty:ty, $doc:literal) => {
178        #[doc = $doc]
179        #[doc = ""]
180        #[doc = "# Returns"]
181        #[doc = ""]
182        #[doc = concat!("Returns the decoded `", stringify!($ty), "`.")]
183        #[doc = ""]
184        #[doc = "# Errors"]
185        #[doc = ""]
186        #[doc = "Returns an input error or an invalid-data error when the \
187                 payload is malformed or violates the selected policy."]
188        #[inline(always)]
189        pub fn $method(&mut self) -> Result<$ty> {
190            type Codec = Leb128Codec<$ty, $policy>;
191
192            self.input.read_decoded::<Codec>()
193        }
194    };
195}
196
197macro_rules! impl_for_policy {
198    (
199        $policy:ty,
200        $read_usize:ident,
201        $read_u64:ident,
202        $read_utf8_string_usize:ident,
203        $read_utf8_string_u64:ident,
204        {
205            $(($method:ident, $ty:ty, $doc:literal)),* $(,)?
206        }
207        $(,)?
208    ) => {
209        impl<R> BufferedLeb128Reader<R, $policy>
210        where
211            R: Input<Item = u8>,
212        {
213            $(
214                impl_read_value!($policy, $method, $ty, $doc);
215            )*
216
217            /// Reads a UTF-8 string prefixed by an unsigned LEB128 byte length.
218            ///
219            /// The length prefix is decoded as usize, so this format is
220            /// target-width dependent. Prefer a fixed-width length prefix for
221            /// persistent files and cross-platform protocols.
222            ///
223            /// # Parameters
224            ///
225            /// - max_len: Maximum accepted UTF-8 payload length in bytes.
226            ///
227            /// # Returns
228            ///
229            /// Returns the decoded UTF-8 string.
230            ///
231            /// # Errors
232            ///
233            /// Returns an input or allocation error, or an invalid-data error
234            /// for a malformed or excessive length or invalid UTF-8.
235            #[inline]
236            pub fn $read_utf8_string_usize(
237                &mut self,
238                max_len: usize,
239            ) -> Result<String> {
240                let len = self.$read_usize()?;
241                read_utf8_payload(&mut self.input, len, max_len)
242            }
243
244            /// Reads a UTF-8 string prefixed by an unsigned LEB128 u64 byte
245            /// length.
246            ///
247            /// Prefer this method over the usize variant for persistent files
248            /// and cross-platform protocols because the length field is
249            /// independent of the current Rust target's pointer width.
250            ///
251            /// # Parameters
252            ///
253            /// - max_len: Maximum accepted UTF-8 payload length in bytes.
254            ///
255            /// # Returns
256            ///
257            /// Returns the decoded UTF-8 string.
258            ///
259            /// # Errors
260            ///
261            /// Returns an input, conversion, or allocation error, or an
262            /// invalid-data error for a malformed or excessive length or
263            /// invalid UTF-8.
264            #[inline]
265            pub fn $read_utf8_string_u64(
266                &mut self,
267                max_len: usize,
268            ) -> Result<String> {
269                let len = self.$read_u64()?;
270                #[cfg(target_pointer_width = "64")]
271                let len = len as usize;
272                #[cfg(not(target_pointer_width = "64"))]
273                let len = usize_from_u64_len(len)?;
274                read_utf8_payload(&mut self.input, len, max_len)
275            }
276        }
277    };
278}
279
280impl_for_policy!(
281    NonStrict,
282    read_usize_non_strict,
283    read_u64_non_strict,
284    read_utf8_string_usize_non_strict,
285    read_utf8_string_u64_non_strict,
286    {
287        (read_u8_non_strict, u8, "Reads an unsigned LEB128 u8."),
288        (read_u16_non_strict, u16, "Reads an unsigned LEB128 u16."),
289        (read_u32_non_strict, u32, "Reads an unsigned LEB128 u32."),
290        (read_u64_non_strict, u64, "Reads an unsigned LEB128 u64."),
291        (read_u128_non_strict, u128, "Reads an unsigned LEB128 u128."),
292        (read_usize_non_strict, usize, "Reads an unsigned LEB128 usize."),
293        (read_i8_non_strict, i8, "Reads a signed LEB128 i8."),
294        (read_i16_non_strict, i16, "Reads a signed LEB128 i16."),
295        (read_i32_non_strict, i32, "Reads a signed LEB128 i32."),
296        (read_i64_non_strict, i64, "Reads a signed LEB128 i64."),
297        (read_i128_non_strict, i128, "Reads a signed LEB128 i128."),
298        (read_isize_non_strict, isize, "Reads a signed LEB128 isize."),
299    },
300);
301impl_for_policy!(
302    Strict,
303    read_usize,
304    read_u64,
305    read_utf8_string_usize,
306    read_utf8_string_u64,
307    {
308        (read_u8, u8, "Reads an unsigned LEB128 u8."),
309        (read_u16, u16, "Reads an unsigned LEB128 u16."),
310        (read_u32, u32, "Reads an unsigned LEB128 u32."),
311        (read_u64, u64, "Reads an unsigned LEB128 u64."),
312        (read_u128, u128, "Reads an unsigned LEB128 u128."),
313        (read_usize, usize, "Reads an unsigned LEB128 usize."),
314        (read_i8, i8, "Reads a signed LEB128 i8."),
315        (read_i16, i16, "Reads a signed LEB128 i16."),
316        (read_i32, i32, "Reads a signed LEB128 i32."),
317        (read_i64, i64, "Reads a signed LEB128 i64."),
318        (read_i128, i128, "Reads a signed LEB128 i128."),
319        (read_isize, isize, "Reads a signed LEB128 isize."),
320    },
321);
322impl<R, P> Input for BufferedLeb128Reader<R, P>
323where
324    R: Input<Item = u8>,
325{
326    type Item = u8;
327
328    /// Reports that this adapter buffers input.
329    ///
330    /// # Returns
331    ///
332    /// Always returns `true`.
333    #[inline(always)]
334    fn is_buffered(&self) -> bool {
335        true
336    }
337
338    /// Reads up to `count` bytes into an indexed output range.
339    ///
340    /// # Parameters
341    ///
342    /// - `output`: Destination slice.
343    /// - `index`: First destination index.
344    /// - `count`: Maximum number of bytes to read.
345    ///
346    /// # Returns
347    ///
348    /// Returns the number of bytes read.
349    ///
350    /// # Errors
351    ///
352    /// Returns an error reported while reading the buffered input.
353    ///
354    /// # Safety
355    ///
356    /// `index..index + count` must be a valid range within `output`.
357    #[inline(always)]
358    unsafe fn read_unchecked(
359        &mut self,
360        output: &mut [u8],
361        index: usize,
362        count: usize,
363    ) -> Result<usize> {
364        // SAFETY: The caller upholds the indexed destination range contract.
365        unsafe { self.input.read_unchecked(output, index, count) }
366    }
367}
368
369impl<R, P> Seekable for BufferedLeb128Reader<R, P>
370where
371    R: Input<Item = u8> + Seekable<Unit = u8>,
372{
373    type Unit = u8;
374
375    /// Seeks the wrapped reader and discards buffered bytes after success.
376    ///
377    /// # Parameters
378    ///
379    /// - `position`: Target seek position.
380    ///
381    /// # Returns
382    ///
383    /// Returns the new physical stream position.
384    ///
385    /// # Errors
386    ///
387    /// Returns the seek error reported by the wrapped reader and preserves
388    /// buffered bytes when seeking fails.
389    #[inline(always)]
390    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
391        self.input.seek(position)
392    }
393}