Skip to main content

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