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::<{ Codec::MAX_DECODE_UNITS_PER_VALUE }, Codec, _>(
131 &mut self.inner,
132 &mut self.buffer,
133 )
134 }
135 };
136}
137
138macro_rules! impl_for_policy {
139 (
140 $policy:ty,
141 {
142 $(($method:ident, $ty:ty, $doc:literal)),* $(,)?
143 }
144 $(,)?
145 ) => {
146 impl<R> ZigZagReader<R, $policy>
147 where
148 R: Input<Item = u8>,
149 {
150 $(
151 impl_read_value!($policy, $method, $ty, $doc);
152 )*
153 }
154 };
155}
156
157impl_for_policy!(
158 NonStrict,
159 {
160 (read_i8_non_strict, i8, "Reads a ZigZag i8."),
161 (read_i16_non_strict, i16, "Reads a ZigZag i16."),
162 (read_i32_non_strict, i32, "Reads a ZigZag i32."),
163 (read_i64_non_strict, i64, "Reads a ZigZag i64."),
164 (read_i128_non_strict, i128, "Reads a ZigZag i128."),
165 (read_isize_non_strict, isize, "Reads a ZigZag isize."),
166 },
167);
168impl_for_policy!(
169 Strict,
170 {
171 (read_i8, i8, "Reads a ZigZag i8."),
172 (read_i16, i16, "Reads a ZigZag i16."),
173 (read_i32, i32, "Reads a ZigZag i32."),
174 (read_i64, i64, "Reads a ZigZag i64."),
175 (read_i128, i128, "Reads a ZigZag i128."),
176 (read_isize, isize, "Reads a ZigZag isize."),
177 },
178);
179impl<R, P> Input for ZigZagReader<R, P>
180where
181 R: Input<Item = u8>,
182{
183 type Item = u8;
184
185 /// Reports whether the wrapped input is buffered.
186 ///
187 /// # Returns
188 ///
189 /// Returns the wrapped input's buffering state.
190 #[inline(always)]
191 fn is_buffered(&self) -> bool {
192 self.inner.is_buffered()
193 }
194
195 /// Reads up to `count` bytes into an indexed output range.
196 ///
197 /// # Parameters
198 ///
199 /// - `output`: Destination slice.
200 /// - `index`: First destination index.
201 /// - `count`: Maximum number of bytes to read.
202 ///
203 /// # Returns
204 ///
205 /// Returns the number of bytes read.
206 ///
207 /// # Errors
208 ///
209 /// Returns an error reported by the wrapped input.
210 ///
211 /// # Safety
212 ///
213 /// `index..index + count` must be a valid range within `output`.
214 #[inline(always)]
215 unsafe fn read_unchecked(&mut self, output: &mut [u8], index: usize, count: usize) -> Result<usize> {
216 // SAFETY: The caller upholds the wrapped input's range contract.
217 unsafe { self.inner.read_unchecked(output, index, count) }
218 }
219}
220
221impl<R, P> Seekable for ZigZagReader<R, P>
222where
223 R: Seekable<Unit = u8>,
224{
225 type Unit = u8;
226
227 /// Seeks the wrapped reader.
228 ///
229 /// # Parameters
230 ///
231 /// - `position`: Target seek position.
232 ///
233 /// # Returns
234 ///
235 /// Returns the new stream position.
236 ///
237 /// # Errors
238 ///
239 /// Returns the seek error reported by the wrapped reader.
240 #[inline(always)]
241 fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
242 self.inner.seek_to(position)
243 }
244}