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