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(target_pointer_width = "32", target_pointer_width = "64")))]
27use crate::util::usize_from_u32_len;
28
29/// Reader wrapper for fixed-width binary values.
30///
31/// The byte order is selected by the `O` type parameter. Use
32/// `BinaryReader<R, BigEndian>` for big-endian data and
33/// `BinaryReader<R, LittleEndian>` for little-endian data.
34///
35/// # Type Parameters
36///
37/// - `R`: Underlying byte input.
38/// - `O`: Compile-time byte-order specification.
39///
40/// # Examples
41///
42/// ```
43/// use qubit_codec::BigEndian;
44/// use qubit_io_binary::BinaryReader;
45/// use std::io::Cursor;
46///
47/// let mut reader = BinaryReader::<_, BigEndian>::new(Cursor::new([0x12, 0x34]));
48/// assert_eq!(reader.read_u16()?, 0x1234);
49/// # Ok::<(), std::io::Error>(())
50/// ```
51pub struct BinaryReader<R, O = BigEndian> {
52    /// Wrapped byte input.
53    inner: R,
54    /// Scratch storage for the largest fixed-width scalar.
55    buffer: [u8; 16],
56    /// Associates the selected byte order without storing a value.
57    marker: PhantomData<fn() -> O>,
58}
59
60impl_input_methods!(BinaryReader<R, O> where R: Input<Item = u8>);
61impl_seekable_methods!(BinaryReader<R, O> where R: Seekable<Unit = u8>);
62
63impl<R, O> BinaryReader<R, O>
64where
65    O: ByteOrderSpec,
66{
67    /// Creates a binary reader.
68    ///
69    /// # Parameters
70    ///
71    /// - `inner`: Underlying byte reader.
72    ///
73    /// # Returns
74    ///
75    /// Returns a reader using the byte order selected by `O`.
76    #[must_use]
77    #[inline]
78    pub const fn new(inner: R) -> Self {
79        Self {
80            inner,
81            buffer: [0; 16],
82            marker: PhantomData,
83        }
84    }
85
86    /// Returns the byte order selected by this reader.
87    ///
88    /// # Returns
89    ///
90    /// Returns the compile-time byte order as a runtime value.
91    #[must_use]
92    #[inline(always)]
93    pub const fn byte_order(&self) -> ByteOrder {
94        O::ORDER
95    }
96
97    /// Returns a shared reference to the underlying reader.
98    ///
99    /// # Returns
100    ///
101    /// Returns the wrapped reader.
102    #[must_use]
103    #[inline(always)]
104    pub const fn inner(&self) -> &R {
105        &self.inner
106    }
107
108    /// Returns an exclusive reference to the underlying reader.
109    ///
110    /// # Returns
111    ///
112    /// Returns mutable access to the wrapped reader.
113    #[must_use]
114    #[inline(always)]
115    pub fn inner_mut(&mut self) -> &mut R {
116        &mut self.inner
117    }
118
119    /// Consumes this wrapper and returns the underlying reader.
120    ///
121    /// # Returns
122    ///
123    /// Returns the wrapped reader.
124    #[must_use]
125    #[inline(always)]
126    pub fn into_inner(self) -> R {
127        self.inner
128    }
129}
130
131macro_rules! impl_value_read {
132    ($order:ty, $method:ident, $ty:ty, $doc:literal) => {
133        #[doc = $doc]
134        #[doc = ""]
135        #[doc = "# Returns"]
136        #[doc = ""]
137        #[doc = concat!("Returns the decoded `", stringify!($ty), "`.")]
138        #[doc = ""]
139        #[doc = "# Errors"]
140        #[doc = ""]
141        #[doc = "Returns an input error, including an unexpected-end-of-input \
142                 error when the scalar is truncated."]
143        #[inline]
144        pub fn $method(&mut self) -> Result<$ty> {
145            type Codec = BinaryCodec<$ty, $order>;
146
147            const LEN: usize = Codec::MIN_UNITS_PER_VALUE;
148            Input::read_exactly(&mut self.inner, &mut self.buffer[..LEN])?;
149            // SAFETY: `LEN` is declared by the codec and the preceding exact
150            // read initialized that prefix of the fixed internal buffer.
151            unsafe { Ok(decode_infallible_unchecked::<Codec>(&self.buffer, 0)) }
152        }
153    };
154}
155
156macro_rules! impl_for_order {
157    ($order:ty) => {
158        impl<R> BinaryReader<R, $order>
159        where
160            R: Input<Item = u8>,
161        {
162            impl_value_read!($order, read_u8, u8, "Reads an unsigned 8-bit integer.");
163            impl_value_read!($order, read_i8, i8, "Reads a signed 8-bit integer.");
164            impl_value_read!($order, read_u16, u16, "Reads an unsigned 16-bit integer.");
165            impl_value_read!($order, read_u32, u32, "Reads an unsigned 32-bit integer.");
166            impl_value_read!($order, read_u64, u64, "Reads an unsigned 64-bit integer.");
167            impl_value_read!($order, read_u128, u128, "Reads an unsigned 128-bit integer.");
168            impl_value_read!($order, read_i16, i16, "Reads a signed 16-bit integer.");
169            impl_value_read!($order, read_i32, i32, "Reads a signed 32-bit integer.");
170            impl_value_read!($order, read_i64, i64, "Reads a signed 64-bit integer.");
171            impl_value_read!($order, read_i128, i128, "Reads a signed 128-bit integer.");
172            impl_value_read!($order, read_f32, f32, "Reads a 32-bit float.");
173            impl_value_read!($order, read_f64, f64, "Reads a 64-bit float.");
174
175            /// Reads a UTF-8 string prefixed by a 16-bit byte length.
176            ///
177            /// # Parameters
178            ///
179            /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
180            ///
181            /// # Returns
182            ///
183            /// Returns the decoded UTF-8 string.
184            ///
185            /// # Errors
186            ///
187            /// Returns an input or allocation error, or
188            /// [`std::io::ErrorKind::InvalidData`] when the encoded length
189            /// exceeds `max_len` or the payload is not valid UTF-8.
190            #[inline]
191            pub fn read_string_with_u16_len(&mut self, max_len: usize) -> Result<String> {
192                let len = usize::from(self.read_u16()?);
193                read_utf8_payload(&mut self.inner, len, max_len)
194            }
195
196            /// Reads a UTF-8 string prefixed by a 32-bit byte length.
197            ///
198            /// # Parameters
199            ///
200            /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
201            ///
202            /// # Returns
203            ///
204            /// Returns the decoded UTF-8 string.
205            ///
206            /// # Errors
207            ///
208            /// Returns an input, conversion, or allocation error, or
209            /// [`std::io::ErrorKind::InvalidData`] when the encoded length
210            /// exceeds `max_len` or the payload is not valid UTF-8.
211            #[inline]
212            pub fn read_string_with_u32_len(&mut self, max_len: usize) -> Result<String> {
213                let len = self.read_u32()?;
214                #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
215                let len = len as usize;
216                #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
217                let len = usize_from_u32_len(len)?;
218                read_utf8_payload(&mut self.inner, len, max_len)
219            }
220        }
221    };
222}
223
224impl_for_order!(BigEndian);
225impl_for_order!(LittleEndian);
226impl_for_order!(NativeEndian);
227
228impl<R, O> Input for BinaryReader<R, O>
229where
230    R: Input<Item = u8>,
231{
232    type Item = u8;
233
234    /// Reports whether the wrapped input is buffered.
235    ///
236    /// # Returns
237    ///
238    /// Returns the wrapped input's buffering state.
239    #[inline(always)]
240    fn is_buffered(&self) -> bool {
241        self.inner.is_buffered()
242    }
243
244    /// Reads up to `count` bytes into an indexed output range.
245    ///
246    /// # Parameters
247    ///
248    /// - `output`: Destination slice.
249    /// - `index`: First destination index.
250    /// - `count`: Maximum number of bytes to read.
251    ///
252    /// # Returns
253    ///
254    /// Returns the number of bytes read.
255    ///
256    /// # Errors
257    ///
258    /// Returns an error reported by the wrapped input.
259    ///
260    /// # Safety
261    ///
262    /// `index..index + count` must be a valid range within `output`.
263    #[inline(always)]
264    unsafe fn read_unchecked(&mut self, output: &mut [u8], index: usize, count: usize) -> Result<usize> {
265        // SAFETY: The caller upholds the same indexed range contract required
266        // by the wrapped input.
267        unsafe { self.inner.read_unchecked(output, index, count) }
268    }
269}
270
271impl<R, O> Seekable for BinaryReader<R, O>
272where
273    R: Seekable<Unit = u8>,
274{
275    type Unit = u8;
276
277    /// Seeks the wrapped input.
278    ///
279    /// # Parameters
280    ///
281    /// - `position`: Target seek position.
282    ///
283    /// # Returns
284    ///
285    /// Returns the new stream position.
286    ///
287    /// # Errors
288    ///
289    /// Returns the seek error reported by the wrapped reader.
290    #[inline(always)]
291    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
292        self.inner.seek_to(position)
293    }
294}