qubit_io_binary/stream/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//! Reader for ZigZag-encoded integer values.
10
11use core::marker::PhantomData;
12use std::io::Result;
13use std::io::SeekFrom;
14
15use qubit_codec_binary::Leb128DecodePolicy;
16use qubit_codec_binary::NonStrict;
17use qubit_codec_binary::Strict;
18use qubit_codec_binary::ZigZagCodec;
19use qubit_io::ByteInput;
20use qubit_io::Input;
21use qubit_io::Seekable;
22use qubit_io::SeekableByteInput;
23
24use crate::util::MIN_CODEC_BUFFER_CAPACITY;
25use crate::util::read_leb128_from_reader;
26
27/// Reader wrapper for ZigZag + unsigned LEB128 integers.
28///
29/// A synchronous read error may occur after part of a value has been consumed.
30/// A later call starts at the current input position; it does not resume the
31/// failed value. Recover only at a framing boundary or trusted seek checkpoint.
32///
33/// # Target-width integers
34///
35/// `isize` methods use the current Rust target's pointer width. Prefer
36/// fixed-width integer methods such as `read_i64` for persistent files and
37/// cross-platform protocols.
38///
39/// # Type Parameters
40///
41/// - `R`: Underlying byte input.
42/// - `P`: Canonicality policy for the underlying unsigned LEB128 encoding.
43///
44/// # Examples
45///
46/// ```
47/// use qubit_codec_binary::NonStrict;
48/// use qubit_io_binary::ZigZagReader;
49/// use std::io::Cursor;
50///
51/// let mut reader = ZigZagReader::<_, NonStrict>::new(Cursor::new(vec![1]));
52/// assert_eq!(reader.read_i8_non_strict().unwrap(), -1);
53/// ```
54pub struct ZigZagReader<R, P> {
55 /// Wrapped byte input.
56 inner: R,
57 /// Scratch storage for the largest encoded ZigZag payload.
58 buffer: [u8; MIN_CODEC_BUFFER_CAPACITY],
59 /// Associates the selected decoding policy without storing a value.
60 marker: PhantomData<fn() -> P>,
61}
62
63impl<R, P> ZigZagReader<R, P>
64where
65 P: Leb128DecodePolicy,
66{
67 /// Creates a ZigZag reader.
68 ///
69 /// # Parameters
70 ///
71 /// - `inner`: Underlying byte input.
72 ///
73 /// # Returns
74 ///
75 /// Returns a reader using policy `P`.
76 #[must_use]
77 #[inline]
78 pub const fn new(inner: R) -> Self {
79 Self {
80 inner,
81 buffer: [0; MIN_CODEC_BUFFER_CAPACITY],
82 marker: PhantomData,
83 }
84 }
85
86 /// Returns whether this reader rejects non-canonical LEB128 encodings.
87 ///
88 /// # Returns
89 ///
90 /// Returns `true` when policy `P` requires canonical encodings.
91 #[must_use]
92 #[inline(always)]
93 pub const fn is_strict(&self) -> bool {
94 P::STRICT
95 }
96
97 /// Returns a shared reference to the underlying reader.
98 ///
99 /// # Returns
100 ///
101 /// Returns the wrapped reader.
102 #[must_use]
103 #[inline(always)]
104 pub const fn inner(&self) -> &R {
105 &self.inner
106 }
107
108 /// Returns an exclusive reference to the underlying reader.
109 ///
110 /// # Returns
111 ///
112 /// Returns mutable access to the wrapped reader.
113 #[must_use]
114 #[inline(always)]
115 pub fn inner_mut(&mut self) -> &mut R {
116 &mut self.inner
117 }
118
119 /// Consumes this wrapper and returns the underlying reader.
120 ///
121 /// # Returns
122 ///
123 /// Returns the wrapped reader.
124 #[must_use]
125 #[inline(always)]
126 pub fn into_inner(self) -> R {
127 self.inner
128 }
129}
130
131macro_rules! impl_read_value {
132 ($policy:ty, $method:ident, $ty:ty, $doc:literal) => {
133 #[doc = $doc]
134 #[doc = ""]
135 #[doc = "# Returns"]
136 #[doc = ""]
137 #[doc = concat!("Returns the decoded `", stringify!($ty), "`.")]
138 #[doc = ""]
139 #[doc = "# Errors"]
140 #[doc = ""]
141 #[doc = "Returns an input error or an invalid-data error when the \
142 payload is malformed or violates the selected policy."]
143 #[inline(always)]
144 pub fn $method(&mut self) -> Result<$ty> {
145 type Codec = ZigZagCodec<$ty, $policy>;
146
147 read_leb128_from_reader::<{ Codec::MAX_DECODE_UNITS_PER_VALUE }, Codec, _>(
148 &mut self.inner,
149 &mut self.buffer,
150 )
151 }
152 };
153}
154
155macro_rules! impl_for_policy {
156 (
157 $policy:ty,
158 {
159 $(($method:ident, $ty:ty, $doc:literal)),* $(,)?
160 }
161 $(,)?
162 ) => {
163 impl<R> ZigZagReader<R, $policy>
164 where
165 R: ByteInput,
166 {
167 $(
168 impl_read_value!($policy, $method, $ty, $doc);
169 )*
170 }
171 };
172}
173
174impl_for_policy!(
175 NonStrict,
176 {
177 (read_i8_non_strict, i8, "Reads a ZigZag i8."),
178 (read_i16_non_strict, i16, "Reads a ZigZag i16."),
179 (read_i32_non_strict, i32, "Reads a ZigZag i32."),
180 (read_i64_non_strict, i64, "Reads a ZigZag i64."),
181 (read_i128_non_strict, i128, "Reads a ZigZag i128."),
182 (read_isize_non_strict, isize, "Reads a ZigZag isize."),
183 },
184);
185impl_for_policy!(
186 Strict,
187 {
188 (read_i8, i8, "Reads a ZigZag i8."),
189 (read_i16, i16, "Reads a ZigZag i16."),
190 (read_i32, i32, "Reads a ZigZag i32."),
191 (read_i64, i64, "Reads a ZigZag i64."),
192 (read_i128, i128, "Reads a ZigZag i128."),
193 (read_isize, isize, "Reads a ZigZag isize."),
194 },
195);
196impl<R, P> Input for ZigZagReader<R, P>
197where
198 R: ByteInput,
199{
200 type Item = u8;
201
202 /// Reports whether the wrapped input is buffered.
203 ///
204 /// # Returns
205 ///
206 /// Returns the wrapped input's buffering state.
207 #[inline(always)]
208 fn is_buffered(&self) -> bool {
209 self.inner.is_buffered()
210 }
211
212 /// Reads up to `count` bytes into an indexed output range.
213 ///
214 /// # Parameters
215 ///
216 /// - `output`: Destination slice.
217 /// - `index`: First destination index.
218 /// - `count`: Maximum number of bytes to read.
219 ///
220 /// # Returns
221 ///
222 /// Returns the number of bytes read.
223 ///
224 /// # Errors
225 ///
226 /// Returns an error reported by the wrapped input.
227 ///
228 /// # Safety
229 ///
230 /// `index..index + count` must be a valid range within `output`.
231 #[inline(always)]
232 unsafe fn read_unchecked(&mut self, output: &mut [u8], index: usize, count: usize) -> Result<usize> {
233 // SAFETY: The caller upholds the wrapped input's range contract.
234 unsafe { self.inner.read_unchecked(output, index, count) }
235 }
236}
237
238impl<R, P> Seekable for ZigZagReader<R, P>
239where
240 R: SeekableByteInput,
241{
242 type Unit = u8;
243
244 /// Seeks the wrapped reader.
245 ///
246 /// # Parameters
247 ///
248 /// - `position`: Target seek position.
249 ///
250 /// # Returns
251 ///
252 /// Returns the new stream position.
253 ///
254 /// # Errors
255 ///
256 /// Returns the seek error reported by the wrapped reader.
257 #[inline(always)]
258 fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
259 self.inner.seek_to(position)
260 }
261}
262
263impl_input_methods!(ZigZagReader<R, P> where R: ByteInput);
264impl_seekable_methods!(ZigZagReader<R, P> where R: SeekableByteInput);