qubit_io_binary/stream/buffered_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//! Buffered reader for fixed-width binary values.
10
11use core::marker::PhantomData;
12use std::collections::TryReserveError;
13use std::io::Result;
14use std::io::SeekFrom;
15
16use qubit_codec::BigEndian;
17use qubit_codec::ByteOrder;
18use qubit_codec::ByteOrderSpec;
19use qubit_codec::LittleEndian;
20use qubit_codec::NativeEndian;
21use qubit_codec::TranscodeDecodeInput;
22use qubit_codec_binary::BinaryCodec;
23use qubit_io::Buffer;
24use qubit_io::Input;
25use qubit_io::Seekable;
26
27use super::internal::TranscodeDecodeInputExt;
28use crate::util::MIN_CODEC_BUFFER_CAPACITY;
29use crate::util::read_utf8_payload;
30#[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
31use crate::util::usize_from_u32_len;
32
33/// Buffered reader for fixed-width binary values.
34///
35/// Scalar reads decode directly from the internal input buffer whenever enough
36/// bytes are available, avoiding a per-value temporary byte buffer.
37///
38/// # Buffered state
39///
40/// This reader may prefetch bytes from the wrapped reader. As a result,
41/// [`Self::inner`] can observe an underlying stream position ahead of the
42/// logical position exposed by this wrapper.
43///
44/// # Type Parameters
45///
46/// - `R`: Underlying byte input.
47/// - `O`: Compile-time byte-order specification.
48///
49/// # Examples
50///
51/// ```
52/// use qubit_codec::BigEndian;
53/// use qubit_io_binary::BufferedBinaryReader;
54///
55/// let mut reader = BufferedBinaryReader::<_, BigEndian>::new(std::io::Cursor::new([0x12, 0x34]));
56/// assert_eq!(reader.read_u16()?, 0x1234);
57/// # Ok::<(), std::io::Error>(())
58/// ```
59pub struct BufferedBinaryReader<R, O = BigEndian>
60where
61 R: Input<Item = u8>,
62{
63 /// Buffered codec input and wrapped reader.
64 input: TranscodeDecodeInput<R>,
65 /// Associates the selected byte order without storing a value.
66 marker: PhantomData<fn() -> O>,
67}
68
69impl_input_methods!(BufferedBinaryReader<R, O> where R: Input<Item = u8>);
70impl_seekable_methods!(BufferedBinaryReader<R, O> where R: Input<Item = u8> + Seekable<Unit = u8>);
71
72impl<R, O> BufferedBinaryReader<R, O>
73where
74 R: Input<Item = u8>,
75 O: ByteOrderSpec,
76{
77 /// Creates a buffered binary reader with the default buffer capacity.
78 ///
79 /// # Parameters
80 ///
81 /// - `inner`: Underlying byte input.
82 ///
83 /// # Returns
84 ///
85 /// Returns a buffered reader using byte order `O`.
86 #[must_use]
87 #[inline]
88 pub fn new(inner: R) -> Self {
89 Self {
90 input: TranscodeDecodeInput::new(inner),
91 marker: PhantomData,
92 }
93 }
94
95 /// Creates a buffered binary reader with at least `capacity` bytes.
96 ///
97 /// # Parameters
98 ///
99 /// - `inner`: Underlying byte input.
100 /// - `capacity`: Requested internal buffer capacity in bytes.
101 ///
102 /// # Returns
103 ///
104 /// Returns a buffered reader whose capacity also satisfies the largest
105 /// supported codec payload.
106 #[must_use]
107 #[inline]
108 pub fn with_capacity(inner: R, capacity: usize) -> Self {
109 Self {
110 input: TranscodeDecodeInput::with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY)),
111 marker: PhantomData,
112 }
113 }
114
115 /// Tries to create a buffered binary reader with at least `capacity` bytes.
116 ///
117 /// # Errors
118 ///
119 /// Returns an allocation error when the requested buffer cannot be
120 /// allocated.
121 #[inline]
122 pub fn try_with_capacity(inner: R, capacity: usize) -> std::result::Result<Self, TryReserveError> {
123 Ok(Self {
124 input: TranscodeDecodeInput::try_with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY))?,
125 marker: PhantomData,
126 })
127 }
128
129 /// Returns the byte order selected by this reader.
130 ///
131 /// # Returns
132 ///
133 /// Returns the compile-time byte order as a runtime value.
134 #[must_use]
135 #[inline(always)]
136 pub const fn byte_order(&self) -> ByteOrder {
137 O::ORDER
138 }
139
140 /// Returns a shared reference to the underlying reader.
141 ///
142 /// The underlying reader may already be positioned past unread bytes held
143 /// in this wrapper's internal buffer.
144 ///
145 /// # Returns
146 ///
147 /// Returns the wrapped reader.
148 #[must_use]
149 #[inline(always)]
150 pub const fn inner(&self) -> &R {
151 self.input.inner()
152 }
153
154 /// Consumes this wrapper and preserves its unread buffered bytes.
155 ///
156 /// # Returns
157 ///
158 /// Returns the wrapped reader and the buffer whose [`Buffer::readable`]
159 /// slice contains every prefetched byte not yet consumed logically. To
160 /// continue the same logical stream, consume that slice before reading
161 /// from the returned reader.
162 #[inline(always)]
163 #[must_use = "the returned inner reader and unread buffer must be handled"]
164 pub fn into_parts(self) -> (R, Buffer<u8>) {
165 self.input.into_parts()
166 }
167}
168
169macro_rules! impl_value_read {
170 ($order:ty, $method:ident, $ty:ty, $doc:literal) => {
171 #[doc = $doc]
172 #[doc = ""]
173 #[doc = "# Returns"]
174 #[doc = ""]
175 #[doc = concat!("Returns the decoded `", stringify!($ty), "`.")]
176 #[doc = ""]
177 #[doc = "# Errors"]
178 #[doc = ""]
179 #[doc = "Returns an input error, including an unexpected-end-of-input \
180 error when the scalar is truncated."]
181 #[inline(always)]
182 pub fn $method(&mut self) -> Result<$ty> {
183 type Codec = BinaryCodec<$ty, $order>;
184 self.input.read_decoded::<Codec>()
185 }
186 };
187}
188
189macro_rules! impl_for_order {
190 ($order:ty) => {
191 impl<R> BufferedBinaryReader<R, $order>
192 where
193 R: Input<Item = u8>,
194 {
195 impl_value_read!($order, read_u8, u8, "Reads an unsigned 8-bit integer.");
196 impl_value_read!($order, read_i8, i8, "Reads a signed 8-bit integer.");
197 impl_value_read!($order, read_u16, u16, "Reads an unsigned 16-bit integer.");
198 impl_value_read!($order, read_u32, u32, "Reads an unsigned 32-bit integer.");
199 impl_value_read!($order, read_u64, u64, "Reads an unsigned 64-bit integer.");
200 impl_value_read!($order, read_u128, u128, "Reads an unsigned 128-bit integer.");
201 impl_value_read!($order, read_i16, i16, "Reads a signed 16-bit integer.");
202 impl_value_read!($order, read_i32, i32, "Reads a signed 32-bit integer.");
203 impl_value_read!($order, read_i64, i64, "Reads a signed 64-bit integer.");
204 impl_value_read!($order, read_i128, i128, "Reads a signed 128-bit integer.");
205 impl_value_read!($order, read_f32, f32, "Reads a 32-bit float.");
206 impl_value_read!($order, read_f64, f64, "Reads a 64-bit float.");
207
208 /// Reads a UTF-8 string prefixed by a `u16` byte length.
209 ///
210 /// # Errors
211 ///
212 /// Returns an input error, or [`std::io::ErrorKind::InvalidData`]
213 /// when the byte length exceeds `max_len` or the payload is not
214 /// valid UTF-8.
215 pub fn read_string_with_u16_len(&mut self, max_len: usize) -> Result<String> {
216 let len = usize::from(self.read_u16()?);
217 read_utf8_payload(self, len, max_len)
218 }
219
220 /// Reads a UTF-8 string prefixed by a `u32` byte length.
221 ///
222 /// # Errors
223 ///
224 /// Returns an input error, or [`std::io::ErrorKind::InvalidData`]
225 /// when the byte length does not fit `usize`, exceeds `max_len`,
226 /// or the payload is not valid UTF-8.
227 pub fn read_string_with_u32_len(&mut self, max_len: usize) -> Result<String> {
228 #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
229 let len = self.read_u32()? as usize;
230 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
231 let len = usize_from_u32_len(self.read_u32()?)?;
232 read_utf8_payload(self, len, max_len)
233 }
234 }
235 };
236}
237
238impl_for_order!(BigEndian);
239impl_for_order!(LittleEndian);
240impl_for_order!(NativeEndian);
241
242impl<R, O> Input for BufferedBinaryReader<R, O>
243where
244 R: Input<Item = u8>,
245{
246 type Item = u8;
247
248 /// Reports that this adapter buffers input.
249 ///
250 /// # Returns
251 ///
252 /// Always returns `true`.
253 #[inline(always)]
254 fn is_buffered(&self) -> bool {
255 true
256 }
257
258 /// Reads up to `count` bytes into an indexed output range.
259 ///
260 /// # Parameters
261 ///
262 /// - `output`: Destination slice.
263 /// - `index`: First destination index.
264 /// - `count`: Maximum number of bytes to read.
265 ///
266 /// # Returns
267 ///
268 /// Returns the number of bytes read.
269 ///
270 /// # Errors
271 ///
272 /// Returns an error reported while reading the buffered input.
273 ///
274 /// # Safety
275 ///
276 /// `index..index + count` must be a valid range within `output`.
277 #[inline(always)]
278 unsafe fn read_unchecked(&mut self, output: &mut [u8], index: usize, count: usize) -> Result<usize> {
279 // SAFETY: The caller upholds the indexed destination range contract.
280 unsafe { self.input.read_unchecked(output, index, count) }
281 }
282}
283
284impl<R, O> Seekable for BufferedBinaryReader<R, O>
285where
286 R: Input<Item = u8> + Seekable<Unit = u8>,
287{
288 type Unit = u8;
289
290 /// Seeks the wrapped reader and discards buffered bytes after success.
291 ///
292 /// # Parameters
293 ///
294 /// - `position`: Target seek position.
295 ///
296 /// # Returns
297 ///
298 /// Returns the new physical stream position.
299 ///
300 /// # Errors
301 ///
302 /// Returns the seek error reported by the wrapped reader and preserves
303 /// buffered bytes when seeking fails.
304 #[inline(always)]
305 fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
306 self.input.seek(position)
307 }
308}