Skip to main content

qubit_io_binary/stream/
buffered_zig_zag_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 ZigZag-encoded integer 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::Leb128DecodePolicy;
18use qubit_codec_binary::NonStrict;
19use qubit_codec_binary::Strict;
20use qubit_codec_binary::ZigZagCodec;
21use qubit_io::Buffer;
22use qubit_io::ByteInput;
23use qubit_io::Input;
24use qubit_io::Seekable;
25use qubit_io::SeekableByteInput;
26
27use super::internal::TranscodeDecodeInputExt;
28use crate::util::MIN_CODEC_BUFFER_CAPACITY;
29
30/// Buffered reader for ZigZag + unsigned LEB128 integers.
31///
32/// Values are decoded directly from the internal input buffer while the codec
33/// scans for the underlying LEB128 terminating byte.
34///
35/// # Buffered state
36///
37/// This reader may prefetch bytes from the wrapped reader. As a result,
38/// [`Self::inner`] can observe an underlying stream position ahead of the
39/// logical position exposed by this wrapper.
40///
41/// # Target-width integers
42///
43/// `isize` methods use the current Rust target's pointer width. Prefer
44/// fixed-width integer methods such as `read_i64` for persistent files and
45/// cross-platform protocols.
46///
47/// # Type Parameters
48///
49/// - `R`: Underlying byte input.
50/// - `P`: Canonicality policy for the underlying unsigned LEB128 encoding.
51///
52/// # Examples
53///
54/// ```
55/// use qubit_codec_binary::Strict;
56/// use qubit_io_binary::BufferedZigZagReader;
57///
58/// let mut reader = BufferedZigZagReader::<_, Strict>::new(
59///     std::io::Cursor::new([0xAC, 0x02]),
60/// );
61/// assert_eq!(reader.read_i32()?, 150);
62/// # Ok::<(), std::io::Error>(())
63/// ```
64pub struct BufferedZigZagReader<R, P>
65where
66    R: ByteInput,
67{
68    /// Buffered codec input and wrapped reader.
69    input: TranscodeDecodeInput<R>,
70    /// Associates the selected decoding policy without storing a value.
71    marker: PhantomData<fn() -> P>,
72}
73
74impl<R, P> BufferedZigZagReader<R, P>
75where
76    R: ByteInput,
77    P: Leb128DecodePolicy,
78{
79    /// Creates a buffered ZigZag reader with the default buffer capacity.
80    ///
81    /// # Parameters
82    ///
83    /// - `inner`: Underlying byte input.
84    ///
85    /// # Returns
86    ///
87    /// Returns a buffered reader using policy `P`.
88    #[must_use]
89    #[inline]
90    pub fn new(inner: R) -> Self {
91        Self {
92            input: TranscodeDecodeInput::new(inner),
93            marker: PhantomData,
94        }
95    }
96
97    /// Creates a buffered ZigZag reader with at least `capacity` bytes.
98    ///
99    /// # Parameters
100    ///
101    /// - `inner`: Underlying byte input.
102    /// - `capacity`: Requested internal buffer capacity in bytes.
103    ///
104    /// # Returns
105    ///
106    /// Returns a buffered reader whose capacity also satisfies the largest
107    /// supported codec payload.
108    #[must_use]
109    #[inline]
110    pub fn with_capacity(inner: R, capacity: usize) -> Self {
111        Self {
112            input: TranscodeDecodeInput::with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY)),
113            marker: PhantomData,
114        }
115    }
116
117    /// Tries to create a buffered ZigZag reader with at least `capacity` bytes.
118    ///
119    /// # Errors
120    ///
121    /// Returns an allocation error when the requested buffer cannot be
122    /// allocated.
123    ///
124    /// # Returns
125    ///
126    /// Returns the reader when allocation succeeds.
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 LEB128 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
175impl_input_methods!(BufferedZigZagReader<R, P> where R: ByteInput);
176impl_seekable_methods!(BufferedZigZagReader<R, P> where R: SeekableByteInput);
177
178macro_rules! impl_read_value {
179    ($policy:ty, $method:ident, $ty:ty, $doc:literal) => {
180        #[doc = $doc]
181        #[doc = ""]
182        #[doc = "# Returns"]
183        #[doc = ""]
184        #[doc = concat!("Returns the decoded `", stringify!($ty), "`.")]
185        #[doc = ""]
186        #[doc = "# Errors"]
187        #[doc = ""]
188        #[doc = "Returns an input error or an invalid-data error when the \
189                 payload is malformed or violates the selected policy."]
190        #[inline(always)]
191        pub fn $method(&mut self) -> Result<$ty> {
192            type Codec = ZigZagCodec<$ty, $policy>;
193
194            self.input.read_decoded::<Codec>()
195        }
196    };
197}
198
199macro_rules! impl_for_policy {
200    (
201        $policy:ty,
202        {
203            $(($method:ident, $ty:ty, $doc:literal)),* $(,)?
204        }
205        $(,)?
206    ) => {
207        impl<R> BufferedZigZagReader<R, $policy>
208        where
209            R: ByteInput,
210        {
211            $(
212                impl_read_value!($policy, $method, $ty, $doc);
213            )*
214        }
215    };
216}
217
218impl_for_policy!(
219    NonStrict,
220    {
221        (read_i8_non_strict, i8, "Reads a ZigZag i8."),
222        (read_i16_non_strict, i16, "Reads a ZigZag i16."),
223        (read_i32_non_strict, i32, "Reads a ZigZag i32."),
224        (read_i64_non_strict, i64, "Reads a ZigZag i64."),
225        (read_i128_non_strict, i128, "Reads a ZigZag i128."),
226        (read_isize_non_strict, isize, "Reads a ZigZag isize."),
227    },
228);
229impl_for_policy!(
230    Strict,
231    {
232        (read_i8, i8, "Reads a ZigZag i8."),
233        (read_i16, i16, "Reads a ZigZag i16."),
234        (read_i32, i32, "Reads a ZigZag i32."),
235        (read_i64, i64, "Reads a ZigZag i64."),
236        (read_i128, i128, "Reads a ZigZag i128."),
237        (read_isize, isize, "Reads a ZigZag isize."),
238    },
239);
240impl<R, P> Input for BufferedZigZagReader<R, P>
241where
242    R: ByteInput,
243{
244    type Item = u8;
245
246    /// Reports that this adapter buffers input.
247    ///
248    /// # Returns
249    ///
250    /// Always returns `true`.
251    #[inline(always)]
252    fn is_buffered(&self) -> bool {
253        true
254    }
255
256    /// Reads up to `count` bytes into an indexed output range.
257    ///
258    /// # Parameters
259    ///
260    /// - `output`: Destination slice.
261    /// - `index`: First destination index.
262    /// - `count`: Maximum number of bytes to read.
263    ///
264    /// # Returns
265    ///
266    /// Returns the number of bytes read.
267    ///
268    /// # Errors
269    ///
270    /// Returns an error reported while reading the buffered input.
271    ///
272    /// # Safety
273    ///
274    /// `index..index + count` must be a valid range within `output`.
275    #[inline(always)]
276    unsafe fn read_unchecked(&mut self, output: &mut [u8], index: usize, count: usize) -> Result<usize> {
277        // SAFETY: The caller upholds the indexed destination range contract.
278        unsafe { self.input.read_unchecked(output, index, count) }
279    }
280}
281
282impl<R, P> Seekable for BufferedZigZagReader<R, P>
283where
284    R: SeekableByteInput,
285{
286    type Unit = u8;
287
288    /// Seeks relative to this reader's logical position. Relative seeks within
289    /// the buffered window preserve unread bytes; successful seeks outside the
290    /// window discard the old buffer. The returned position is logical.
291    ///
292    /// # Parameters
293    ///
294    /// - `position`: Target seek position.
295    ///
296    /// # Returns
297    ///
298    /// Returns the new logical stream position in bytes.
299    ///
300    /// # Errors
301    ///
302    /// Returns the seek error reported by the wrapped reader and preserves
303    /// buffered bytes when seeking fails, including when an in-window seek
304    /// cannot query the wrapped position.
305    #[inline(always)]
306    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
307        self.input.seek(position)
308    }
309}