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