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