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