Skip to main content

qubit_io_binary/stream/
binary_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 fixed-width binary values.
10
11use core::marker::PhantomData;
12use std::io::Result;
13use std::io::SeekFrom;
14
15use qubit_codec::BigEndian;
16use qubit_codec::ByteOrder;
17use qubit_codec::ByteOrderSpec;
18use qubit_codec::LittleEndian;
19use qubit_codec::NativeEndian;
20use qubit_codec_binary::BinaryCodec;
21use qubit_io::Input;
22use qubit_io::Seekable;
23
24use crate::util::decode_infallible_unchecked;
25use crate::util::read_utf8_payload;
26#[cfg(not(any(
27    target_pointer_width = "32",
28    target_pointer_width = "64"
29)))]
30use crate::util::usize_from_u32_len;
31
32/// Reader wrapper for fixed-width binary values.
33///
34/// The byte order is selected by the `O` type parameter. Use
35/// `BinaryReader<R, BigEndian>` for big-endian data and
36/// `BinaryReader<R, LittleEndian>` for little-endian data.
37///
38/// # Type Parameters
39///
40/// - `R`: Underlying byte input.
41/// - `O`: Compile-time byte-order specification.
42pub struct BinaryReader<R, O = BigEndian> {
43    /// Wrapped byte input.
44    inner: R,
45    /// Scratch storage for the largest fixed-width scalar.
46    buffer: [u8; 16],
47    /// Associates the selected byte order without storing a value.
48    marker: PhantomData<fn() -> O>,
49}
50
51impl<R, O> BinaryReader<R, O>
52where
53    O: ByteOrderSpec,
54{
55    /// Creates a binary reader.
56    ///
57    /// # Parameters
58    ///
59    /// - `inner`: Underlying byte reader.
60    ///
61    /// # Returns
62    ///
63    /// Returns a reader using the byte order selected by `O`.
64    #[must_use]
65    #[inline]
66    pub const fn new(inner: R) -> Self {
67        Self {
68            inner,
69            buffer: [0; 16],
70            marker: PhantomData,
71        }
72    }
73
74    /// Returns the byte order selected by this reader.
75    ///
76    /// # Returns
77    ///
78    /// Returns the compile-time byte order as a runtime value.
79    #[must_use]
80    #[inline(always)]
81    pub const fn byte_order(&self) -> ByteOrder {
82        O::ORDER
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_value_read {
120    ($order: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, including an unexpected-end-of-input \
130                 error when the scalar is truncated."]
131        #[inline]
132        pub fn $method(&mut self) -> Result<$ty> {
133            type Codec = BinaryCodec<$ty, $order>;
134
135            const LEN: usize = Codec::MIN_UNITS_PER_VALUE;
136            Input::read_exactly(&mut self.inner, &mut self.buffer[..LEN])?;
137            // SAFETY: `LEN` is declared by the codec and the preceding exact
138            // read initialized that prefix of the fixed internal buffer.
139            unsafe { Ok(decode_infallible_unchecked::<Codec>(&self.buffer, 0)) }
140        }
141    };
142}
143
144macro_rules! impl_for_order {
145    ($order:ty) => {
146        impl<R> BinaryReader<R, $order>
147        where
148            R: Input<Item = u8>,
149        {
150            impl_value_read!(
151                $order,
152                read_u8,
153                u8,
154                "Reads an unsigned 8-bit integer."
155            );
156            impl_value_read!(
157                $order,
158                read_i8,
159                i8,
160                "Reads a signed 8-bit integer."
161            );
162            impl_value_read!(
163                $order,
164                read_u16,
165                u16,
166                "Reads an unsigned 16-bit integer."
167            );
168            impl_value_read!(
169                $order,
170                read_u32,
171                u32,
172                "Reads an unsigned 32-bit integer."
173            );
174            impl_value_read!(
175                $order,
176                read_u64,
177                u64,
178                "Reads an unsigned 64-bit integer."
179            );
180            impl_value_read!(
181                $order,
182                read_u128,
183                u128,
184                "Reads an unsigned 128-bit integer."
185            );
186            impl_value_read!(
187                $order,
188                read_i16,
189                i16,
190                "Reads a signed 16-bit integer."
191            );
192            impl_value_read!(
193                $order,
194                read_i32,
195                i32,
196                "Reads a signed 32-bit integer."
197            );
198            impl_value_read!(
199                $order,
200                read_i64,
201                i64,
202                "Reads a signed 64-bit integer."
203            );
204            impl_value_read!(
205                $order,
206                read_i128,
207                i128,
208                "Reads a signed 128-bit integer."
209            );
210            impl_value_read!($order, read_f32, f32, "Reads a 32-bit float.");
211            impl_value_read!($order, read_f64, f64, "Reads a 64-bit float.");
212
213            /// Reads a UTF-8 string prefixed by a 16-bit byte length.
214            ///
215            /// # Parameters
216            ///
217            /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
218            ///
219            /// # Returns
220            ///
221            /// Returns the decoded UTF-8 string.
222            ///
223            /// # Errors
224            ///
225            /// Returns an input or allocation error, or
226            /// [`std::io::ErrorKind::InvalidData`] when the encoded length
227            /// exceeds `max_len` or the payload is not valid UTF-8.
228            #[inline]
229            pub fn read_string_with_u16_len(
230                &mut self,
231                max_len: usize,
232            ) -> Result<String> {
233                let len = usize::from(self.read_u16()?);
234                read_utf8_payload(&mut self.inner, len, max_len)
235            }
236
237            /// Reads a UTF-8 string prefixed by a 32-bit byte length.
238            ///
239            /// # Parameters
240            ///
241            /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
242            ///
243            /// # Returns
244            ///
245            /// Returns the decoded UTF-8 string.
246            ///
247            /// # Errors
248            ///
249            /// Returns an input, conversion, or allocation error, or
250            /// [`std::io::ErrorKind::InvalidData`] when the encoded length
251            /// exceeds `max_len` or the payload is not valid UTF-8.
252            #[inline]
253            pub fn read_string_with_u32_len(
254                &mut self,
255                max_len: usize,
256            ) -> Result<String> {
257                let len = self.read_u32()?;
258                #[cfg(any(
259                    target_pointer_width = "32",
260                    target_pointer_width = "64"
261                ))]
262                let len = len as usize;
263                #[cfg(not(any(
264                    target_pointer_width = "32",
265                    target_pointer_width = "64"
266                )))]
267                let len = usize_from_u32_len(len)?;
268                read_utf8_payload(&mut self.inner, len, max_len)
269            }
270        }
271    };
272}
273
274impl_for_order!(BigEndian);
275impl_for_order!(LittleEndian);
276impl_for_order!(NativeEndian);
277
278impl<R, O> Input for BinaryReader<R, O>
279where
280    R: Input<Item = u8>,
281{
282    type Item = u8;
283
284    /// Reports whether the wrapped input is buffered.
285    ///
286    /// # Returns
287    ///
288    /// Returns the wrapped input's buffering state.
289    #[inline(always)]
290    fn is_buffered(&self) -> bool {
291        self.inner.is_buffered()
292    }
293
294    /// Reads up to `count` bytes into an indexed output range.
295    ///
296    /// # Parameters
297    ///
298    /// - `output`: Destination slice.
299    /// - `index`: First destination index.
300    /// - `count`: Maximum number of bytes to read.
301    ///
302    /// # Returns
303    ///
304    /// Returns the number of bytes read.
305    ///
306    /// # Errors
307    ///
308    /// Returns an error reported by the wrapped input.
309    ///
310    /// # Safety
311    ///
312    /// `index..index + count` must be a valid range within `output`.
313    #[inline(always)]
314    unsafe fn read_unchecked(
315        &mut self,
316        output: &mut [u8],
317        index: usize,
318        count: usize,
319    ) -> Result<usize> {
320        // SAFETY: The caller upholds the same indexed range contract required
321        // by the wrapped input.
322        unsafe { self.inner.read_unchecked(output, index, count) }
323    }
324}
325
326impl<R, O> Seekable for BinaryReader<R, O>
327where
328    R: Seekable<Unit = u8>,
329{
330    type Unit = u8;
331
332    /// Seeks the wrapped input.
333    ///
334    /// # Parameters
335    ///
336    /// - `position`: Target seek position.
337    ///
338    /// # Returns
339    ///
340    /// Returns the new stream position.
341    ///
342    /// # Errors
343    ///
344    /// Returns the seek error reported by the wrapped reader.
345    #[inline(always)]
346    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
347        self.inner.seek_to(position)
348    }
349}