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