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