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