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.
49pub struct BufferedZigZagReader<R, P>
50where
51    R: Input<Item = u8>,
52{
53    /// Buffered codec input and wrapped reader.
54    input: TranscodeDecodeInput<R>,
55    /// Associates the selected decoding policy without storing a value.
56    marker: PhantomData<fn() -> P>,
57}
58
59impl<R, P> BufferedZigZagReader<R, P>
60where
61    R: Input<Item = u8>,
62    P: Leb128DecodePolicy,
63{
64    /// Creates a buffered ZigZag reader with the default buffer capacity.
65    ///
66    /// # Parameters
67    ///
68    /// - `inner`: Underlying byte input.
69    ///
70    /// # Returns
71    ///
72    /// Returns a buffered reader using policy `P`.
73    #[must_use]
74    #[inline]
75    pub fn new(inner: R) -> Self {
76        Self {
77            input: TranscodeDecodeInput::new(inner),
78            marker: PhantomData,
79        }
80    }
81
82    /// Creates a buffered ZigZag reader with at least `capacity` bytes.
83    ///
84    /// # Parameters
85    ///
86    /// - `inner`: Underlying byte input.
87    /// - `capacity`: Requested internal buffer capacity in bytes.
88    ///
89    /// # Returns
90    ///
91    /// Returns a buffered reader whose capacity also satisfies the largest
92    /// supported codec payload.
93    #[must_use]
94    #[inline]
95    pub fn with_capacity(inner: R, capacity: usize) -> Self {
96        Self {
97            input: TranscodeDecodeInput::with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY)),
98            marker: PhantomData,
99        }
100    }
101
102    /// Tries to create a buffered ZigZag reader with at least `capacity` bytes.
103    ///
104    /// # Errors
105    ///
106    /// Returns an allocation error when the requested buffer cannot be
107    /// allocated.
108    #[inline]
109    pub fn try_with_capacity(inner: R, capacity: usize) -> std::result::Result<Self, TryReserveError> {
110        Ok(Self {
111            input: TranscodeDecodeInput::try_with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY))?,
112            marker: PhantomData,
113        })
114    }
115
116    /// Returns whether this reader rejects non-canonical LEB128 encodings.
117    ///
118    /// # Returns
119    ///
120    /// Returns `true` when policy `P` requires canonical encodings.
121    #[must_use]
122    #[inline(always)]
123    pub const fn is_strict(&self) -> bool {
124        P::STRICT
125    }
126
127    /// Returns a shared reference to the underlying reader.
128    ///
129    /// The underlying reader may already be positioned past unread bytes held
130    /// in this wrapper's internal buffer.
131    ///
132    /// # Returns
133    ///
134    /// Returns the wrapped reader.
135    #[must_use]
136    #[inline(always)]
137    pub const fn inner(&self) -> &R {
138        self.input.inner()
139    }
140
141    /// Consumes this wrapper and preserves its unread buffered bytes.
142    ///
143    /// # Returns
144    ///
145    /// Returns the wrapped reader and the buffer whose [`Buffer::readable`]
146    /// slice contains every prefetched byte not yet consumed logically. To
147    /// continue the same logical stream, consume that slice before reading
148    /// from the returned reader.
149    #[inline(always)]
150    #[must_use = "the returned inner reader and unread buffer must be handled"]
151    pub fn into_parts(self) -> (R, Buffer<u8>) {
152        self.input.into_parts()
153    }
154}
155
156macro_rules! impl_read_value {
157    ($policy:ty, $method:ident, $ty:ty, $doc:literal) => {
158        #[doc = $doc]
159        #[doc = ""]
160        #[doc = "# Returns"]
161        #[doc = ""]
162        #[doc = concat!("Returns the decoded `", stringify!($ty), "`.")]
163        #[doc = ""]
164        #[doc = "# Errors"]
165        #[doc = ""]
166        #[doc = "Returns an input error or an invalid-data error when the \
167                 payload is malformed or violates the selected policy."]
168        #[inline(always)]
169        pub fn $method(&mut self) -> Result<$ty> {
170            type Codec = ZigZagCodec<$ty, $policy>;
171
172            self.input.read_decoded::<Codec>()
173        }
174    };
175}
176
177macro_rules! impl_for_policy {
178    (
179        $policy:ty,
180        {
181            $(($method:ident, $ty:ty, $doc:literal)),* $(,)?
182        }
183        $(,)?
184    ) => {
185        impl<R> BufferedZigZagReader<R, $policy>
186        where
187            R: Input<Item = u8>,
188        {
189            $(
190                impl_read_value!($policy, $method, $ty, $doc);
191            )*
192        }
193    };
194}
195
196impl_for_policy!(
197    NonStrict,
198    {
199        (read_i8_non_strict, i8, "Reads a ZigZag i8."),
200        (read_i16_non_strict, i16, "Reads a ZigZag i16."),
201        (read_i32_non_strict, i32, "Reads a ZigZag i32."),
202        (read_i64_non_strict, i64, "Reads a ZigZag i64."),
203        (read_i128_non_strict, i128, "Reads a ZigZag i128."),
204        (read_isize_non_strict, isize, "Reads a ZigZag isize."),
205    },
206);
207impl_for_policy!(
208    Strict,
209    {
210        (read_i8, i8, "Reads a ZigZag i8."),
211        (read_i16, i16, "Reads a ZigZag i16."),
212        (read_i32, i32, "Reads a ZigZag i32."),
213        (read_i64, i64, "Reads a ZigZag i64."),
214        (read_i128, i128, "Reads a ZigZag i128."),
215        (read_isize, isize, "Reads a ZigZag isize."),
216    },
217);
218impl<R, P> Input for BufferedZigZagReader<R, P>
219where
220    R: Input<Item = u8>,
221{
222    type Item = u8;
223
224    /// Reports that this adapter buffers input.
225    ///
226    /// # Returns
227    ///
228    /// Always returns `true`.
229    #[inline(always)]
230    fn is_buffered(&self) -> bool {
231        true
232    }
233
234    /// Reads up to `count` bytes into an indexed output range.
235    ///
236    /// # Parameters
237    ///
238    /// - `output`: Destination slice.
239    /// - `index`: First destination index.
240    /// - `count`: Maximum number of bytes to read.
241    ///
242    /// # Returns
243    ///
244    /// Returns the number of bytes read.
245    ///
246    /// # Errors
247    ///
248    /// Returns an error reported while reading the buffered input.
249    ///
250    /// # Safety
251    ///
252    /// `index..index + count` must be a valid range within `output`.
253    #[inline(always)]
254    unsafe fn read_unchecked(&mut self, output: &mut [u8], index: usize, count: usize) -> Result<usize> {
255        // SAFETY: The caller upholds the indexed destination range contract.
256        unsafe { self.input.read_unchecked(output, index, count) }
257    }
258}
259
260impl<R, P> Seekable for BufferedZigZagReader<R, P>
261where
262    R: Input<Item = u8> + Seekable<Unit = u8>,
263{
264    type Unit = u8;
265
266    /// Seeks the wrapped reader and discards buffered bytes after success.
267    ///
268    /// # Parameters
269    ///
270    /// - `position`: Target seek position.
271    ///
272    /// # Returns
273    ///
274    /// Returns the new physical stream position.
275    ///
276    /// # Errors
277    ///
278    /// Returns the seek error reported by the wrapped reader and preserves
279    /// buffered bytes when seeking fails.
280    #[inline(always)]
281    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
282        self.input.seek(position)
283    }
284}