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