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    /// # Errors
120    ///
121    /// Returns an allocation error when the requested buffer cannot be
122    /// allocated.
123    #[inline]
124    pub fn try_with_capacity(inner: R, capacity: usize) -> std::result::Result<Self, TryReserveError> {
125        Ok(Self {
126            input: TranscodeDecodeInput::try_with_capacity(inner, capacity.max(MIN_CODEC_BUFFER_CAPACITY))?,
127            marker: PhantomData,
128        })
129    }
130
131    /// Returns the byte order selected by this reader.
132    ///
133    /// # Returns
134    ///
135    /// Returns the compile-time byte order as a runtime value.
136    #[must_use]
137    #[inline(always)]
138    pub const fn byte_order(&self) -> ByteOrder {
139        O::ORDER
140    }
141
142    /// Returns a shared reference to the underlying reader.
143    ///
144    /// The underlying reader may already be positioned past unread bytes held
145    /// in this wrapper's internal buffer.
146    ///
147    /// # Returns
148    ///
149    /// Returns the wrapped reader.
150    #[must_use]
151    #[inline(always)]
152    pub const fn inner(&self) -> &R {
153        self.input.inner()
154    }
155
156    /// Consumes this wrapper and preserves its unread buffered bytes.
157    ///
158    /// # Returns
159    ///
160    /// Returns the wrapped reader and the buffer whose [`Buffer::readable`]
161    /// slice contains every prefetched byte not yet consumed logically. To
162    /// continue the same logical stream, consume that slice before reading
163    /// from the returned reader.
164    #[inline(always)]
165    #[must_use = "the returned inner reader and unread buffer must be handled"]
166    pub fn into_parts(self) -> (R, Buffer<u8>) {
167        self.input.into_parts()
168    }
169}
170
171macro_rules! impl_value_read {
172    ($order:ty, $method:ident, $ty:ty, $doc:literal) => {
173        #[doc = $doc]
174        #[doc = ""]
175        #[doc = "# Returns"]
176        #[doc = ""]
177        #[doc = concat!("Returns the decoded `", stringify!($ty), "`.")]
178        #[doc = ""]
179        #[doc = "# Errors"]
180        #[doc = ""]
181        #[doc = "Returns an input error, including an unexpected-end-of-input \
182                 error when the scalar is truncated."]
183        #[inline(always)]
184        pub fn $method(&mut self) -> Result<$ty> {
185            type Codec = BinaryCodec<$ty, $order>;
186            self.input.read_decoded::<Codec>()
187        }
188    };
189}
190
191macro_rules! impl_for_order {
192    ($order:ty) => {
193        impl<R> BufferedBinaryReader<R, $order>
194        where
195            R: ByteInput,
196        {
197            impl_value_read!($order, read_u8, u8, "Reads an unsigned 8-bit integer.");
198            impl_value_read!($order, read_i8, i8, "Reads a signed 8-bit integer.");
199            impl_value_read!($order, read_u16, u16, "Reads an unsigned 16-bit integer.");
200            impl_value_read!($order, read_u32, u32, "Reads an unsigned 32-bit integer.");
201            impl_value_read!($order, read_u64, u64, "Reads an unsigned 64-bit integer.");
202            impl_value_read!($order, read_u128, u128, "Reads an unsigned 128-bit integer.");
203            impl_value_read!($order, read_i16, i16, "Reads a signed 16-bit integer.");
204            impl_value_read!($order, read_i32, i32, "Reads a signed 32-bit integer.");
205            impl_value_read!($order, read_i64, i64, "Reads a signed 64-bit integer.");
206            impl_value_read!($order, read_i128, i128, "Reads a signed 128-bit integer.");
207            impl_value_read!($order, read_f32, f32, "Reads a 32-bit float.");
208            impl_value_read!($order, read_f64, f64, "Reads a 64-bit float.");
209
210            /// Reads a UTF-8 string prefixed by a `u16` byte length.
211            ///
212            /// # Errors
213            ///
214            /// Returns an input error, or [`std::io::ErrorKind::InvalidData`]
215            /// when the byte length exceeds `max_len` or the payload is not
216            /// valid UTF-8.
217            ///
218            /// # Stream position
219            ///
220            /// If the decoded length exceeds `max_len`, the length prefix has been
221            /// consumed logically, but the payload has not. If UTF-8 validation
222            /// fails, the prefix and complete payload have been consumed logically.
223            /// The underlying input may already have prefetched payload bytes;
224            /// its position is not the logical consumption position. These operations
225            /// do not roll back; recover only at an outer framing boundary or a
226            /// trusted seek checkpoint. See [`StringReadExt`](crate::StringReadExt)
227            /// for the shared length-prefixed read contract.
228            pub fn read_string_with_u16_len(&mut self, max_len: usize) -> Result<String> {
229                let len = usize::from(self.read_u16()?);
230                read_utf8_payload(self, len, max_len)
231            }
232
233            /// Reads a UTF-8 string prefixed by a `u32` byte length.
234            ///
235            /// # Errors
236            ///
237            /// Returns an input error, or [`std::io::ErrorKind::InvalidData`]
238            /// when the byte length does not fit `usize`, exceeds `max_len`,
239            /// or the payload is not valid UTF-8.
240            ///
241            /// # Stream position
242            ///
243            /// If the decoded length exceeds `max_len`, the length prefix has been
244            /// consumed logically, but the payload has not. If UTF-8 validation
245            /// fails, the prefix and complete payload have been consumed logically.
246            /// The underlying input may already have prefetched payload bytes;
247            /// its position is not the logical consumption position. These operations
248            /// do not roll back; recover only at an outer framing boundary or a
249            /// trusted seek checkpoint. See [`StringReadExt`](crate::StringReadExt)
250            /// for the shared length-prefixed read contract.
251            pub fn read_string_with_u32_len(&mut self, max_len: usize) -> Result<String> {
252                #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
253                let len = self.read_u32()? as usize;
254                #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
255                let len = usize_from_u32_len(self.read_u32()?)?;
256                read_utf8_payload(self, len, max_len)
257            }
258        }
259    };
260}
261
262impl_for_order!(BigEndian);
263impl_for_order!(LittleEndian);
264impl_for_order!(NativeEndian);
265
266impl<R, O> Input for BufferedBinaryReader<R, O>
267where
268    R: ByteInput,
269{
270    type Item = u8;
271
272    /// Reports that this adapter buffers input.
273    ///
274    /// # Returns
275    ///
276    /// Always returns `true`.
277    #[inline(always)]
278    fn is_buffered(&self) -> bool {
279        true
280    }
281
282    /// Reads up to `count` bytes into an indexed output range.
283    ///
284    /// # Parameters
285    ///
286    /// - `output`: Destination slice.
287    /// - `index`: First destination index.
288    /// - `count`: Maximum number of bytes to read.
289    ///
290    /// # Returns
291    ///
292    /// Returns the number of bytes read.
293    ///
294    /// # Errors
295    ///
296    /// Returns an error reported while reading the buffered input.
297    ///
298    /// # Safety
299    ///
300    /// `index..index + count` must be a valid range within `output`.
301    #[inline(always)]
302    unsafe fn read_unchecked(&mut self, output: &mut [u8], index: usize, count: usize) -> Result<usize> {
303        // SAFETY: The caller upholds the indexed destination range contract.
304        unsafe { self.input.read_unchecked(output, index, count) }
305    }
306}
307
308impl<R, O> Seekable for BufferedBinaryReader<R, O>
309where
310    R: SeekableByteInput,
311{
312    type Unit = u8;
313
314    /// Seeks relative to this reader's logical position. Relative seeks within
315    /// the buffered window preserve unread bytes; successful seeks outside the
316    /// window discard the old buffer. The returned position is logical.
317    ///
318    /// # Parameters
319    ///
320    /// - `position`: Target seek position.
321    ///
322    /// # Returns
323    ///
324    /// Returns the new logical stream position in bytes.
325    ///
326    /// # Errors
327    ///
328    /// Returns the seek error reported by the wrapped reader and preserves
329    /// buffered bytes when seeking fails, including when an in-window seek
330    /// cannot query the wrapped position.
331    #[inline(always)]
332    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
333        self.input.seek(position)
334    }
335}