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::Input;
23use qubit_io::Seekable;
24
25use super::internal::TranscodeDecodeInputExt;
26use crate::util::MIN_CODEC_BUFFER_CAPACITY;
27
28/// Buffered reader for ZigZag + unsigned LEB128 integers.
29///
30/// Values are decoded directly from the internal input buffer while the codec
31/// scans for the underlying LEB128 terminating byte.
32///
33/// # Buffered state
34///
35/// This reader may prefetch bytes from the wrapped reader. As a result,
36/// [`Self::inner`] can observe an underlying stream position ahead of the
37/// logical position exposed by this wrapper.
38///
39/// # Target-width integers
40///
41/// `isize` methods use the current Rust target's pointer width. Prefer
42/// fixed-width integer methods such as `read_i64` for persistent files and
43/// cross-platform protocols.
44///
45/// # Type Parameters
46///
47/// - `R`: Underlying byte input.
48/// - `P`: LEB128 canonicality policy applied after ZigZag decoding.
49///
50/// # Examples
51///
52/// ```
53/// use qubit_codec_binary::Strict;
54/// use qubit_io_binary::BufferedZigZagReader;
55///
56/// let mut reader = BufferedZigZagReader::<_, Strict>::new(
57///     std::io::Cursor::new([0xAC, 0x02]),
58/// );
59/// assert_eq!(reader.read_i32()?, 150);
60/// # Ok::<(), std::io::Error>(())
61/// ```
62pub struct BufferedZigZagReader<R, P>
63where
64    R: Input<Item = u8>,
65{
66    /// Buffered codec input and wrapped reader.
67    input: TranscodeDecodeInput<R>,
68    /// Associates the selected decoding policy without storing a value.
69    marker: PhantomData<fn() -> P>,
70}
71
72impl<R, P> BufferedZigZagReader<R, P>
73where
74    R: Input<Item = u8>,
75    P: Leb128DecodePolicy,
76{
77    /// Creates a buffered ZigZag reader with the default buffer capacity.
78    ///
79    /// # Parameters
80    ///
81    /// - `inner`: Underlying byte input.
82    ///
83    /// # Returns
84    ///
85    /// Returns a buffered reader using policy `P`.
86    #[must_use]
87    #[inline]
88    pub fn new(inner: R) -> Self {
89        Self {
90            input: TranscodeDecodeInput::new(inner),
91            marker: PhantomData,
92        }
93    }
94
95    /// Creates a buffered ZigZag reader with at least `capacity` bytes.
96    ///
97    /// # Parameters
98    ///
99    /// - `inner`: Underlying byte input.
100    /// - `capacity`: Requested internal buffer capacity in bytes.
101    ///
102    /// # Returns
103    ///
104    /// Returns a buffered reader whose capacity also satisfies the largest
105    /// supported codec payload.
106    #[must_use]
107    #[inline]
108    pub fn with_capacity(inner: R, capacity: usize) -> Self {
109        Self {
110            input: TranscodeDecodeInput::with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY)),
111            marker: PhantomData,
112        }
113    }
114
115    /// Tries to create a buffered ZigZag reader with at least `capacity` bytes.
116    ///
117    /// # Errors
118    ///
119    /// Returns an allocation error when the requested buffer cannot be
120    /// allocated.
121    ///
122    /// # Returns
123    ///
124    /// Returns the reader when allocation succeeds.
125    #[inline]
126    pub fn try_with_capacity(inner: R, capacity: usize) -> std::result::Result<Self, TryReserveError> {
127        Ok(Self {
128            input: TranscodeDecodeInput::try_with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY))?,
129            marker: PhantomData,
130        })
131    }
132
133    /// Returns whether this reader rejects non-canonical LEB128 encodings.
134    ///
135    /// # Returns
136    ///
137    /// Returns `true` when policy `P` requires canonical encodings.
138    #[must_use]
139    #[inline(always)]
140    pub const fn is_strict(&self) -> bool {
141        P::STRICT
142    }
143
144    /// Returns a shared reference to the underlying reader.
145    ///
146    /// The underlying reader may already be positioned past unread bytes held
147    /// in this wrapper's internal buffer.
148    ///
149    /// # Returns
150    ///
151    /// Returns the wrapped reader.
152    #[must_use]
153    #[inline(always)]
154    pub const fn inner(&self) -> &R {
155        self.input.inner()
156    }
157
158    /// Consumes this wrapper and preserves its unread buffered bytes.
159    ///
160    /// # Returns
161    ///
162    /// Returns the wrapped reader and the buffer whose [`Buffer::readable`]
163    /// slice contains every prefetched byte not yet consumed logically. To
164    /// continue the same logical stream, consume that slice before reading
165    /// from the returned reader.
166    #[inline(always)]
167    #[must_use = "the returned inner reader and unread buffer must be handled"]
168    pub fn into_parts(self) -> (R, Buffer<u8>) {
169        self.input.into_parts()
170    }
171}
172
173impl_input_methods!(BufferedZigZagReader<R, P> where R: Input<Item = u8>);
174impl_seekable_methods!(BufferedZigZagReader<R, P> where R: Input<Item = u8> + Seekable<Unit = u8>);
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 = ZigZagCodec<$ty, $policy>;
191
192            self.input.read_decoded::<Codec>()
193        }
194    };
195}
196
197macro_rules! impl_for_policy {
198    (
199        $policy:ty,
200        {
201            $(($method:ident, $ty:ty, $doc:literal)),* $(,)?
202        }
203        $(,)?
204    ) => {
205        impl<R> BufferedZigZagReader<R, $policy>
206        where
207            R: Input<Item = u8>,
208        {
209            $(
210                impl_read_value!($policy, $method, $ty, $doc);
211            )*
212        }
213    };
214}
215
216impl_for_policy!(
217    NonStrict,
218    {
219        (read_i8_non_strict, i8, "Reads a ZigZag i8."),
220        (read_i16_non_strict, i16, "Reads a ZigZag i16."),
221        (read_i32_non_strict, i32, "Reads a ZigZag i32."),
222        (read_i64_non_strict, i64, "Reads a ZigZag i64."),
223        (read_i128_non_strict, i128, "Reads a ZigZag i128."),
224        (read_isize_non_strict, isize, "Reads a ZigZag isize."),
225    },
226);
227impl_for_policy!(
228    Strict,
229    {
230        (read_i8, i8, "Reads a ZigZag i8."),
231        (read_i16, i16, "Reads a ZigZag i16."),
232        (read_i32, i32, "Reads a ZigZag i32."),
233        (read_i64, i64, "Reads a ZigZag i64."),
234        (read_i128, i128, "Reads a ZigZag i128."),
235        (read_isize, isize, "Reads a ZigZag isize."),
236    },
237);
238impl<R, P> Input for BufferedZigZagReader<R, P>
239where
240    R: Input<Item = u8>,
241{
242    type Item = u8;
243
244    /// Reports that this adapter buffers input.
245    ///
246    /// # Returns
247    ///
248    /// Always returns `true`.
249    #[inline(always)]
250    fn is_buffered(&self) -> bool {
251        true
252    }
253
254    /// Reads up to `count` bytes into an indexed output range.
255    ///
256    /// # Parameters
257    ///
258    /// - `output`: Destination slice.
259    /// - `index`: First destination index.
260    /// - `count`: Maximum number of bytes to read.
261    ///
262    /// # Returns
263    ///
264    /// Returns the number of bytes read.
265    ///
266    /// # Errors
267    ///
268    /// Returns an error reported while reading the buffered input.
269    ///
270    /// # Safety
271    ///
272    /// `index..index + count` must be a valid range within `output`.
273    #[inline(always)]
274    unsafe fn read_unchecked(&mut self, output: &mut [u8], index: usize, count: usize) -> Result<usize> {
275        // SAFETY: The caller upholds the indexed destination range contract.
276        unsafe { self.input.read_unchecked(output, index, count) }
277    }
278}
279
280impl<R, P> Seekable for BufferedZigZagReader<R, P>
281where
282    R: Input<Item = u8> + Seekable<Unit = u8>,
283{
284    type Unit = u8;
285
286    /// Seeks the wrapped reader and discards buffered bytes after success.
287    ///
288    /// # Parameters
289    ///
290    /// - `position`: Target seek position.
291    ///
292    /// # Returns
293    ///
294    /// Returns the new physical stream position.
295    ///
296    /// # Errors
297    ///
298    /// Returns the seek error reported by the wrapped reader and preserves
299    /// buffered bytes when seeking fails.
300    #[inline(always)]
301    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
302        self.input.seek(position)
303    }
304}