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