Skip to main content

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