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