qubit-io-binary 0.8.6

Synchronous and asynchronous binary stream I/O adapters for Rust
Documentation
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================

//! Reader for fixed-width binary values.

use core::marker::PhantomData;
use std::io::Result;
use std::io::SeekFrom;

use qubit_codec::BigEndian;
use qubit_codec::ByteOrder;
use qubit_codec::ByteOrderSpec;
use qubit_codec::LittleEndian;
use qubit_codec::NativeEndian;
use qubit_codec_binary::BinaryCodec;
use qubit_io::ByteInput;
use qubit_io::Input;
use qubit_io::Seekable;
use qubit_io::SeekableByteInput;

use crate::util::decode_infallible_unchecked;
use crate::util::read_utf8_payload;
#[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
use crate::util::usize_from_u32_len;

/// Reader wrapper for fixed-width binary values.
///
/// The byte order is selected by the `O` type parameter. Use
/// `BinaryReader<R, BigEndian>` for big-endian data and
/// `BinaryReader<R, LittleEndian>` for little-endian data.
///
/// If a synchronous read fails partway through a value, some bytes may already
/// be consumed. Do not blindly retry; use an outer framing boundary or a
/// trusted seek checkpoint to recover.
///
/// # Type Parameters
///
/// - `R`: Underlying byte input.
/// - `O`: Compile-time byte-order specification.
///
/// # Examples
///
/// ```
/// use qubit_codec::BigEndian;
/// use qubit_io_binary::BinaryReader;
/// use std::io::Cursor;
///
/// let mut reader = BinaryReader::<_, BigEndian>::new(Cursor::new([0x12, 0x34]));
/// assert_eq!(reader.read_u16()?, 0x1234);
/// # Ok::<(), std::io::Error>(())
/// ```
pub struct BinaryReader<R, O = BigEndian> {
    /// Wrapped byte input.
    inner: R,
    /// Scratch storage for the largest fixed-width scalar.
    buffer: [u8; 16],
    /// Associates the selected byte order without storing a value.
    marker: PhantomData<fn() -> O>,
}

impl_input_methods!(BinaryReader<R, O> where R: ByteInput);
impl_seekable_methods!(BinaryReader<R, O> where R: SeekableByteInput);

impl<R, O> BinaryReader<R, O>
where
    O: ByteOrderSpec,
{
    /// Creates a binary reader.
    ///
    /// # Parameters
    ///
    /// - `inner`: Underlying byte reader.
    ///
    /// # Returns
    ///
    /// Returns a reader using the byte order selected by `O`.
    #[must_use]
    #[inline]
    pub const fn new(inner: R) -> Self {
        Self {
            inner,
            buffer: [0; 16],
            marker: PhantomData,
        }
    }

    /// Returns the byte order selected by this reader.
    ///
    /// # Returns
    ///
    /// Returns the compile-time byte order as a runtime value.
    #[must_use]
    #[inline(always)]
    pub const fn byte_order(&self) -> ByteOrder {
        O::ORDER
    }

    /// Returns a shared reference to the underlying reader.
    ///
    /// # Returns
    ///
    /// Returns the wrapped reader.
    #[must_use = "the underlying reader must be used or returned to its owner"]
    #[inline(always)]
    pub const fn inner(&self) -> &R {
        &self.inner
    }

    /// Returns an exclusive reference to the underlying reader.
    ///
    /// # Returns
    ///
    /// Returns mutable access to the wrapped reader.
    #[must_use = "the underlying reader must be used or returned to its owner"]
    #[inline(always)]
    pub fn inner_mut(&mut self) -> &mut R {
        &mut self.inner
    }

    /// Consumes this wrapper and returns the underlying reader.
    ///
    /// # Returns
    ///
    /// Returns the wrapped reader.
    #[must_use = "the extracted reader must be used or returned to its owner"]
    #[inline(always)]
    pub fn into_inner(self) -> R {
        self.inner
    }
}

macro_rules! impl_value_read {
    ($order:ty, $method:ident, $ty:ty, $doc:literal) => {
        #[doc = $doc]
        #[doc = ""]
        #[doc = "# Returns"]
        #[doc = ""]
        #[doc = concat!("Returns the decoded `", stringify!($ty), "`.")]
        #[doc = ""]
        #[doc = "# Errors"]
        #[doc = ""]
        #[doc = "Returns an input error, including an unexpected-end-of-input \
                 error when the scalar is truncated."]
        #[inline]
        pub fn $method(&mut self) -> Result<$ty> {
            type Codec = BinaryCodec<$ty, $order>;

            const LEN: usize = Codec::MIN_UNITS_PER_VALUE;
            Input::read_exactly(&mut self.inner, &mut self.buffer[..LEN])?;
            // SAFETY: `LEN` is declared by the codec and the preceding exact
            // read initialized that prefix of the fixed internal buffer.
            unsafe { Ok(decode_infallible_unchecked::<Codec>(&self.buffer, 0)) }
        }
    };
}

macro_rules! impl_for_order {
    ($order:ty) => {
        impl<R> BinaryReader<R, $order>
        where
            R: ByteInput,
        {
            impl_value_read!($order, read_u8, u8, "Reads an unsigned 8-bit integer.");
            impl_value_read!($order, read_i8, i8, "Reads a signed 8-bit integer.");
            impl_value_read!($order, read_u16, u16, "Reads an unsigned 16-bit integer.");
            impl_value_read!($order, read_u32, u32, "Reads an unsigned 32-bit integer.");
            impl_value_read!($order, read_u64, u64, "Reads an unsigned 64-bit integer.");
            impl_value_read!($order, read_u128, u128, "Reads an unsigned 128-bit integer.");
            impl_value_read!($order, read_i16, i16, "Reads a signed 16-bit integer.");
            impl_value_read!($order, read_i32, i32, "Reads a signed 32-bit integer.");
            impl_value_read!($order, read_i64, i64, "Reads a signed 64-bit integer.");
            impl_value_read!($order, read_i128, i128, "Reads a signed 128-bit integer.");
            impl_value_read!($order, read_f32, f32, "Reads a 32-bit float.");
            impl_value_read!($order, read_f64, f64, "Reads a 64-bit float.");

            /// Reads a UTF-8 string prefixed by a 16-bit byte length.
            ///
            /// # Parameters
            ///
            /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
            ///
            /// # Returns
            ///
            /// Returns the decoded UTF-8 string.
            ///
            /// # Errors
            ///
            /// Returns an input or allocation error, or
            /// [`std::io::ErrorKind::InvalidData`] when the encoded length
            /// exceeds `max_len` or the payload is not valid UTF-8.
            ///
            /// # Stream position
            ///
            /// If the decoded length exceeds `max_len`, the length prefix has been
            /// consumed, but the payload remains unread. If UTF-8 validation fails,
            /// the prefix and complete payload have been consumed. These operations
            /// do not roll back; recover only at an outer framing boundary or a
            /// trusted seek checkpoint. See [`StringReadExt`](crate::StringReadExt)
            /// for the shared length-prefixed read contract.
            #[inline]
            pub fn read_string_with_u16_len(&mut self, max_len: usize) -> Result<String> {
                let len = usize::from(self.read_u16()?);
                read_utf8_payload(&mut self.inner, len, max_len)
            }

            /// Reads a UTF-8 string prefixed by a 32-bit byte length.
            ///
            /// # Parameters
            ///
            /// - `max_len`: Maximum accepted UTF-8 payload length in bytes.
            ///
            /// # Returns
            ///
            /// Returns the decoded UTF-8 string.
            ///
            /// # Errors
            ///
            /// Returns an input, conversion, or allocation error, or
            /// [`std::io::ErrorKind::InvalidData`] when the encoded length
            /// exceeds `max_len` or the payload is not valid UTF-8.
            ///
            /// # Stream position
            ///
            /// If the decoded length exceeds `max_len`, the length prefix has been
            /// consumed, but the payload remains unread. If UTF-8 validation fails,
            /// the prefix and complete payload have been consumed. These operations
            /// do not roll back; recover only at an outer framing boundary or a
            /// trusted seek checkpoint. See [`StringReadExt`](crate::StringReadExt)
            /// for the shared length-prefixed read contract.
            #[inline]
            pub fn read_string_with_u32_len(&mut self, max_len: usize) -> Result<String> {
                let len = self.read_u32()?;
                #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
                let len = len as usize;
                #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
                let len = usize_from_u32_len(len)?;
                read_utf8_payload(&mut self.inner, len, max_len)
            }
        }
    };
}

impl_for_order!(BigEndian);
impl_for_order!(LittleEndian);
impl_for_order!(NativeEndian);

impl<R, O> Input for BinaryReader<R, O>
where
    R: ByteInput,
{
    /// The byte type yielded by this reader.
    type Item = u8;

    /// Reports whether the wrapped input is buffered.
    ///
    /// # Returns
    ///
    /// Returns the wrapped input's buffering state.
    #[inline(always)]
    fn is_buffered(&self) -> bool {
        self.inner.is_buffered()
    }

    /// Reads up to `count` bytes into an indexed output range.
    ///
    /// # Parameters
    ///
    /// - `output`: Destination slice.
    /// - `index`: First destination index.
    /// - `count`: Maximum number of bytes to read.
    ///
    /// # Returns
    ///
    /// Returns the number of bytes read.
    ///
    /// # Errors
    ///
    /// Returns an error reported by the wrapped input.
    ///
    /// # Safety
    ///
    /// `index..index + count` must be a valid range within `output`.
    #[inline(always)]
    unsafe fn read_unchecked(&mut self, output: &mut [u8], index: usize, count: usize) -> Result<usize> {
        // SAFETY: The caller upholds the same indexed range contract required
        // by the wrapped input.
        unsafe { self.inner.read_unchecked(output, index, count) }
    }
}

impl<R, O> Seekable for BinaryReader<R, O>
where
    R: SeekableByteInput,
{
    /// The unit used to measure positions in the wrapped byte stream: bytes.
    type Unit = u8;

    /// Seeks the wrapped input.
    ///
    /// # Parameters
    ///
    /// - `position`: Target seek position.
    ///
    /// # Returns
    ///
    /// Returns the new stream position.
    ///
    /// # Errors
    ///
    /// Returns the seek error reported by the wrapped reader.
    #[inline(always)]
    fn seek_to(&mut self, position: SeekFrom) -> Result<u64> {
        self.inner.seek_to(position)
    }
}