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.
48pub struct BufferedBinaryReader<R, O = BigEndian>
49where
50 R: Input<Item = u8>,
51{
52 /// Buffered codec input and wrapped reader.
53 input: TranscodeDecodeInput<R>,
54 /// Associates the selected byte order without storing a value.
55 marker: PhantomData<fn() -> O>,
56}
57
58impl<R, O> BufferedBinaryReader<R, O>
59where
60 R: Input<Item = u8>,
61 O: ByteOrderSpec,
62{
63 /// Creates a buffered binary reader with the default buffer capacity.
64 ///
65 /// # Parameters
66 ///
67 /// - `inner`: Underlying byte input.
68 ///
69 /// # Returns
70 ///
71 /// Returns a buffered reader using byte order `O`.
72 #[must_use]
73 #[inline]
74 pub fn new(inner: R) -> Self {
75 Self {
76 input: TranscodeDecodeInput::new(inner),
77 marker: PhantomData,
78 }
79 }
80
81 /// Creates a buffered binary reader with at least `capacity` bytes.
82 ///
83 /// # Parameters
84 ///
85 /// - `inner`: Underlying byte input.
86 /// - `capacity`: Requested internal buffer capacity in bytes.
87 ///
88 /// # Returns
89 ///
90 /// Returns a buffered reader whose capacity also satisfies the largest
91 /// supported codec payload.
92 #[must_use]
93 #[inline]
94 pub fn with_capacity(inner: R, capacity: usize) -> Self {
95 Self {
96 input: TranscodeDecodeInput::with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY)),
97 marker: PhantomData,
98 }
99 }
100
101 /// Tries to create a buffered binary reader with at least `capacity` bytes.
102 ///
103 /// # Errors
104 ///
105 /// Returns an allocation error when the requested buffer cannot be
106 /// allocated.
107 #[inline]
108 pub fn try_with_capacity(inner: R, capacity: usize) -> std::result::Result<Self, TryReserveError> {
109 Ok(Self {
110 input: TranscodeDecodeInput::try_with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY))?,
111 marker: PhantomData,
112 })
113 }
114
115 /// Returns the byte order selected by this reader.
116 ///
117 /// # Returns
118 ///
119 /// Returns the compile-time byte order as a runtime value.
120 #[must_use]
121 #[inline(always)]
122 pub const fn byte_order(&self) -> ByteOrder {
123 O::ORDER
124 }
125
126 /// Returns a shared reference to the underlying reader.
127 ///
128 /// The underlying reader may already be positioned past unread bytes held
129 /// in this wrapper's internal buffer.
130 ///
131 /// # Returns
132 ///
133 /// Returns the wrapped reader.
134 #[must_use]
135 #[inline(always)]
136 pub const fn inner(&self) -> &R {
137 self.input.inner()
138 }
139
140 /// Consumes this wrapper and preserves its unread buffered bytes.
141 ///
142 /// # Returns
143 ///
144 /// Returns the wrapped reader and the buffer whose [`Buffer::readable`]
145 /// slice contains every prefetched byte not yet consumed logically. To
146 /// continue the same logical stream, consume that slice before reading
147 /// from the returned reader.
148 #[inline(always)]
149 #[must_use = "the returned inner reader and unread buffer must be handled"]
150 pub fn into_parts(self) -> (R, Buffer<u8>) {
151 self.input.into_parts()
152 }
153}
154
155macro_rules! impl_value_read {
156 ($order:ty, $method:ident, $ty:ty, $doc:literal) => {
157 #[doc = $doc]
158 #[doc = ""]
159 #[doc = "# Returns"]
160 #[doc = ""]
161 #[doc = concat!("Returns the decoded `", stringify!($ty), "`.")]
162 #[doc = ""]
163 #[doc = "# Errors"]
164 #[doc = ""]
165 #[doc = "Returns an input error, including an unexpected-end-of-input \
166 error when the scalar is truncated."]
167 #[inline(always)]
168 pub fn $method(&mut self) -> Result<$ty> {
169 type Codec = BinaryCodec<$ty, $order>;
170 self.input.read_decoded::<Codec>()
171 }
172 };
173}
174
175macro_rules! impl_for_order {
176 ($order:ty) => {
177 impl<R> BufferedBinaryReader<R, $order>
178 where
179 R: Input<Item = u8>,
180 {
181 impl_value_read!($order, read_u8, u8, "Reads an unsigned 8-bit integer.");
182 impl_value_read!($order, read_i8, i8, "Reads a signed 8-bit integer.");
183 impl_value_read!($order, read_u16, u16, "Reads an unsigned 16-bit integer.");
184 impl_value_read!($order, read_u32, u32, "Reads an unsigned 32-bit integer.");
185 impl_value_read!($order, read_u64, u64, "Reads an unsigned 64-bit integer.");
186 impl_value_read!($order, read_u128, u128, "Reads an unsigned 128-bit integer.");
187 impl_value_read!($order, read_i16, i16, "Reads a signed 16-bit integer.");
188 impl_value_read!($order, read_i32, i32, "Reads a signed 32-bit integer.");
189 impl_value_read!($order, read_i64, i64, "Reads a signed 64-bit integer.");
190 impl_value_read!($order, read_i128, i128, "Reads a signed 128-bit integer.");
191 impl_value_read!($order, read_f32, f32, "Reads a 32-bit float.");
192 impl_value_read!($order, read_f64, f64, "Reads a 64-bit float.");
193
194 /// Reads a UTF-8 string prefixed by a `u16` byte length.
195 ///
196 /// # Errors
197 ///
198 /// Returns an input error, or [`std::io::ErrorKind::InvalidData`]
199 /// when the byte length exceeds `max_len` or the payload is not
200 /// valid UTF-8.
201 pub fn read_string_with_u16_len(&mut self, max_len: usize) -> Result<String> {
202 let len = usize::from(self.read_u16()?);
203 read_utf8_payload(self, len, max_len)
204 }
205
206 /// Reads a UTF-8 string prefixed by a `u32` byte length.
207 ///
208 /// # Errors
209 ///
210 /// Returns an input error, or [`std::io::ErrorKind::InvalidData`]
211 /// when the byte length does not fit `usize`, exceeds `max_len`,
212 /// or the payload is not valid UTF-8.
213 pub fn read_string_with_u32_len(&mut self, max_len: usize) -> Result<String> {
214 #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
215 let len = self.read_u32()? as usize;
216 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
217 let len = usize_from_u32_len(self.read_u32()?)?;
218 read_utf8_payload(self, 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 BufferedBinaryReader<R, O>
229where
230 R: Input<Item = u8>,
231{
232 type Item = u8;
233
234 /// Reports that this adapter buffers input.
235 ///
236 /// # Returns
237 ///
238 /// Always returns `true`.
239 #[inline(always)]
240 fn is_buffered(&self) -> bool {
241 true
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 while reading the buffered 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 indexed destination range contract.
266 unsafe { self.input.read_unchecked(output, index, count) }
267 }
268}
269
270impl<R, O> Seekable for BufferedBinaryReader<R, O>
271where
272 R: Input<Item = u8> + Seekable<Unit = u8>,
273{
274 type Unit = u8;
275
276 /// Seeks the wrapped reader and discards buffered bytes after success.
277 ///
278 /// # Parameters
279 ///
280 /// - `position`: Target seek position.
281 ///
282 /// # Returns
283 ///
284 /// Returns the new physical stream position.
285 ///
286 /// # Errors
287 ///
288 /// Returns the seek error reported by the wrapped reader and preserves
289 /// buffered bytes when seeking fails.
290 #[inline(always)]
291 fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
292 self.input.seek(position)
293 }
294}