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