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 = "use the wrapped reader through the returned reference"]
103 #[inline(always)]
104 pub const fn inner(&self) -> &R {
105 &self.inner
106 }
107
108 /// Consumes this wrapper and returns the underlying reader.
109 ///
110 /// # Returns
111 ///
112 /// Returns the wrapped reader.
113 #[must_use = "use the wrapped reader returned by this method"]
114 #[inline(always)]
115 pub fn into_inner(self) -> R {
116 self.inner
117 }
118
119 /// Returns an exclusive reference to the underlying reader.
120 ///
121 /// # Returns
122 ///
123 /// Returns mutable access to the wrapped reader.
124 #[must_use = "use the wrapped reader through the returned mutable reference"]
125 #[inline(always)]
126 pub fn inner_mut(&mut self) -> &mut R {
127 &mut 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 /// Codec that decodes this signed integer using the selected policy.
146 type Codec = ZigZagCodec<$ty, $policy>;
147
148 read_leb128_from_reader::<{ Codec::MAX_DECODE_UNITS_PER_VALUE }, Codec, _>(
149 &mut self.inner,
150 &mut self.buffer,
151 )
152 }
153 };
154}
155
156macro_rules! impl_for_policy {
157 (
158 $policy:ty,
159 {
160 $(($method:ident, $ty:ty, $doc:literal)),* $(,)?
161 }
162 $(,)?
163 ) => {
164 impl<R> ZigZagReader<R, $policy>
165 where
166 R: ByteInput,
167 {
168 $(
169 impl_read_value!($policy, $method, $ty, $doc);
170 )*
171 }
172 };
173}
174
175impl_for_policy!(
176 NonStrict,
177 {
178 (read_i8_non_strict, i8, "Reads an i8 encoded as ZigZag and unsigned LEB128."),
179 (read_i16_non_strict, i16, "Reads an i16 encoded as ZigZag and unsigned LEB128."),
180 (read_i32_non_strict, i32, "Reads an i32 encoded as ZigZag and unsigned LEB128."),
181 (read_i64_non_strict, i64, "Reads an i64 encoded as ZigZag and unsigned LEB128."),
182 (read_i128_non_strict, i128, "Reads an i128 encoded as ZigZag and unsigned LEB128."),
183 (read_isize_non_strict, isize, "Reads an isize encoded as ZigZag and unsigned LEB128."),
184 },
185);
186impl_for_policy!(
187 Strict,
188 {
189 (read_i8, i8, "Reads an i8 encoded as ZigZag and unsigned LEB128."),
190 (read_i16, i16, "Reads an i16 encoded as ZigZag and unsigned LEB128."),
191 (read_i32, i32, "Reads an i32 encoded as ZigZag and unsigned LEB128."),
192 (read_i64, i64, "Reads an i64 encoded as ZigZag and unsigned LEB128."),
193 (read_i128, i128, "Reads an i128 encoded as ZigZag and unsigned LEB128."),
194 (read_isize, isize, "Reads an isize encoded as ZigZag and unsigned LEB128."),
195 },
196);
197impl<R, P> Input for ZigZagReader<R, P>
198where
199 R: ByteInput,
200{
201 /// Byte type produced by reads from the wrapped input.
202 type Item = u8;
203
204 /// Reports whether the wrapped input is buffered.
205 ///
206 /// # Returns
207 ///
208 /// Returns the wrapped input's buffering state.
209 #[inline(always)]
210 fn is_buffered(&self) -> bool {
211 self.inner.is_buffered()
212 }
213
214 /// Reads up to `count` bytes into an indexed output range.
215 ///
216 /// # Parameters
217 ///
218 /// - `output`: Destination slice.
219 /// - `index`: First destination index.
220 /// - `count`: Maximum number of bytes to read.
221 ///
222 /// # Returns
223 ///
224 /// Returns the number of bytes read.
225 ///
226 /// # Errors
227 ///
228 /// Returns an error reported by the wrapped input.
229 ///
230 /// # Safety
231 ///
232 /// `index..index + count` must be a valid range within `output`.
233 #[inline(always)]
234 unsafe fn read_unchecked(&mut self, output: &mut [u8], index: usize, count: usize) -> Result<usize> {
235 // SAFETY: The caller upholds the wrapped input's range contract.
236 unsafe { self.inner.read_unchecked(output, index, count) }
237 }
238}
239
240impl<R, P> Seekable for ZigZagReader<R, P>
241where
242 R: SeekableByteInput,
243{
244 /// Positioning unit used by the wrapped byte stream.
245 type Unit = u8;
246
247 /// Seeks the wrapped reader.
248 ///
249 /// # Parameters
250 ///
251 /// - `position`: Target seek position.
252 ///
253 /// # Returns
254 ///
255 /// Returns the new stream position.
256 ///
257 /// # Errors
258 ///
259 /// Returns the seek error reported by the wrapped reader.
260 #[inline(always)]
261 fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
262 self.inner.seek_to(position)
263 }
264}
265
266impl_input_methods!(ZigZagReader<R, P> where R: ByteInput);
267impl_seekable_methods!(ZigZagReader<R, P> where R: SeekableByteInput);