wireframe 0.4.0-alpha1

Simplify building servers and clients for custom binary protocols.
Documentation
//! Conversion helpers for length prefix encoding.
use std::io;

use bytes::Buf;

use super::format::Endianness;
use crate::byte_order::{read_network_u64, write_network_u64};

/// Explains that the configured wire prefix cannot represent any supported
/// fixed-width integer and therefore cannot be decoded safely.
pub(crate) const ERR_UNSUPPORTED_PREFIX: &str = "unsupported length prefix size";
/// Preserves the distinction between an invalid local frame length and an I/O
/// failure when encoding a bounded wire prefix.
pub(crate) const ERR_FRAME_TOO_LARGE: &str = "frame too large";
/// Reports truncation before decoding so callers never mistake a partial
/// length prefix for a complete zero-length frame.
pub(crate) const ERR_INCOMPLETE_PREFIX: &str = "incomplete length prefix";

/// Decodes an explicitly little-endian eight-byte prefix independently of the
/// host architecture selected to run the codec.
#[inline]
fn u64_from_le_bytes(bytes: [u8; 8]) -> u64 {
    let mut wire_bytes = bytes.as_slice();
    wire_bytes.get_u64_le()
}

/// Checked conversion from `usize` to a specific prefix integer type.
///
/// Returns `ERR_FRAME_TOO_LARGE` if the value does not fit in `T`.
fn checked_prefix_cast<T: TryFrom<usize>>(len: usize) -> io::Result<T> {
    T::try_from(len).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, ERR_FRAME_TOO_LARGE))
}

/// Copy `prefix` into the appropriate slice of `buf` for the given endianness.
///
/// Callers must guarantee that `prefix.len()` is one of `{1, 2, 4, 8}`.
#[inline]
fn fill_buf_with_prefix(
    buf: &mut [u8; 8],
    prefix: &[u8],
    endianness: Endianness,
) -> io::Result<()> {
    let size = prefix.len();
    if !matches!(size, 1 | 2 | 4 | 8) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            ERR_UNSUPPORTED_PREFIX,
        ));
    }
    let target = match endianness {
        Endianness::Big => {
            let start = 8usize.checked_sub(size).ok_or_else(|| {
                io::Error::new(io::ErrorKind::InvalidInput, ERR_UNSUPPORTED_PREFIX)
            })?;
            let end = start.checked_add(size).ok_or_else(|| {
                io::Error::new(io::ErrorKind::InvalidInput, ERR_UNSUPPORTED_PREFIX)
            })?;
            buf.get_mut(start..end).ok_or_else(|| {
                io::Error::new(io::ErrorKind::InvalidInput, ERR_UNSUPPORTED_PREFIX)
            })?
        }
        Endianness::Little => buf
            .get_mut(..size)
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, ERR_UNSUPPORTED_PREFIX))?,
    };
    target.copy_from_slice(prefix);
    Ok(())
}

/// Converts a byte slice into a `u64` according to `size` and `endianness`.
///
/// Only prefix sizes of `1`, `2`, `4`, or `8` bytes are supported. `bytes` must
/// contain at least `size` bytes.
///
/// # Errors
/// Returns [`io::ErrorKind::InvalidInput`] if `size` is unsupported or
/// [`io::ErrorKind::UnexpectedEof`] if `bytes` is too short.
pub fn bytes_to_u64(bytes: &[u8], size: usize, endianness: Endianness) -> io::Result<u64> {
    if !matches!(size, 1 | 2 | 4 | 8) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            ERR_UNSUPPORTED_PREFIX,
        ));
    }
    if bytes.len() < size {
        return Err(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            ERR_INCOMPLETE_PREFIX,
        ));
    }

    let prefix = bytes
        .get(..size)
        .ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, ERR_INCOMPLETE_PREFIX))?;
    let mut buf = [0u8; 8];
    fill_buf_with_prefix(&mut buf, prefix, endianness)?;

    // Wire prefix declares its endianness; normalizing into an 8-byte buffer and
    // using explicit conversion helpers keeps decoding deterministic on any host
    // CPU.
    let val = match endianness {
        Endianness::Big => read_network_u64(buf),
        Endianness::Little => u64_from_le_bytes(buf),
    };
    Ok(val)
}

/// Convert a length value into a u64 based on the prefix size.
///
/// Callers are expected to validate `size` against the supported set
/// `{1, 2, 4, 8}` before invoking this helper.
fn convert_len_to_value(len: usize, size: usize) -> io::Result<u64> {
    let value = match size {
        1 => u64::from(checked_prefix_cast::<u8>(len)?),
        2 => u64::from(checked_prefix_cast::<u16>(len)?),
        4 => u64::from(checked_prefix_cast::<u32>(len)?),
        8 => checked_prefix_cast(len)?,
        _ => {
            debug_assert!(false, "size should be validated upstream");
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                ERR_UNSUPPORTED_PREFIX,
            ));
        }
    };
    Ok(value)
}

/// Write a u64 into `prefix` according to the specified endianness.
///
/// For big-endian, the function delegates to the typed network-order write
/// helpers mirroring how the read path delegates to `read_network_u64`.
fn write_bytes_with_endianness(
    value: u64,
    endianness: Endianness,
    prefix: &mut [u8],
) -> io::Result<()> {
    let size = prefix.len();
    match endianness {
        Endianness::Big => write_big_endian_prefix(value, size, prefix),
        Endianness::Little => {
            write_little_endian_prefix(value, prefix);
            Ok(())
        }
    }
}

/// Reject a length that the configured prefix width cannot represent.
///
/// A prefix only carries the low `size` bytes of the network-order encoding, so
/// a value wider than the prefix would otherwise be silently truncated.
///
/// # Examples
///
/// ```text
/// value_fits_prefix(255, 1) -> true
/// value_fits_prefix(256, 1) -> false
/// ```
fn value_fits_prefix(value: u64, size: usize) -> bool {
    match size {
        1 => u8::try_from(value).is_ok(),
        2 => u16::try_from(value).is_ok(),
        4 => u32::try_from(value).is_ok(),
        8 => true,
        _ => false,
    }
}

/// Validates the prefix width and whether `value` fits within that width.
///
/// # Errors
///
/// Returns [`io::ErrorKind::InvalidInput`] when the width is unsupported or
/// the value cannot be represented by the selected width.
///
/// # Examples
///
/// ```text
/// ensure_fits_prefix(255, 1) -> Ok(())
/// ensure_fits_prefix(256, 1) -> Err(InvalidInput)
/// ```
fn ensure_fits_prefix(value: u64, size: usize) -> io::Result<()> {
    if !matches!(size, 1 | 2 | 4 | 8) {
        Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            ERR_UNSUPPORTED_PREFIX,
        ))
    } else if value_fits_prefix(value, size) {
        Ok(())
    } else {
        Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            ERR_FRAME_TOO_LARGE,
        ))
    }
}

/// Encode `value` into `prefix` in network (big-endian) byte order.
///
/// Encoding the full width once and keeping its trailing bytes yields the same
/// digits as narrowing to the prefix width first, and it lets the fit check stay
/// separate from the write.
fn write_big_endian_prefix(value: u64, size: usize, prefix: &mut [u8]) -> io::Result<()> {
    ensure_fits_prefix(value, size)?;

    let encoded = write_network_u64(value);
    let start = 8usize
        .checked_sub(size)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, ERR_UNSUPPORTED_PREFIX))?;
    let trailing = encoded
        .get(start..)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, ERR_UNSUPPORTED_PREFIX))?;

    prefix.copy_from_slice(trailing);
    Ok(())
}

/// Encode `value` into `prefix` in little-endian byte order.
fn write_little_endian_prefix(value: u64, prefix: &mut [u8]) {
    for (i, byte) in prefix.iter_mut().enumerate() {
        let shift = 8 * i;
        *byte = ((value >> shift) & 0xff) as u8;
    }
}

/// Encodes an integer directly into `out` according to `size` and `endianness`.
///
/// The function supports prefix sizes of `1`, `2`, `4`, or `8` bytes.
///
/// # Errors
/// Returns [`io::ErrorKind::InvalidInput`] when the prefix size is unsupported
/// or when `len` does not fit into the requested prefix.
#[must_use = "length prefix byte count must be used"]
pub fn u64_to_bytes(
    len: usize,
    size: usize,
    endianness: Endianness,
    out: &mut [u8; 8],
) -> io::Result<usize> {
    if !matches!(size, 1 | 2 | 4 | 8) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            ERR_UNSUPPORTED_PREFIX,
        ));
    }

    let value = convert_len_to_value(len, size)?;

    let prefix = out
        .get_mut(..size)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, ERR_UNSUPPORTED_PREFIX))?;

    write_bytes_with_endianness(value, endianness, prefix)?;

    if let Some(tail) = out.get_mut(size..) {
        tail.fill(0);
    }

    Ok(size)
}

#[cfg(test)]
mod tests {
    //! Unit tests for prefix-buffer placement across supported endianness cases.

    use rstest::rstest;

    use super::*;
    use crate::frame::format::Endianness;

    /// Fixed-width decoding retains exact little-endian byte order.
    #[rstest]
    #[case::asymmetric([0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11], 0x1122_3344_5566_7788)]
    #[case::zero([0; 8], 0)]
    #[case::maximum([0xff; 8], u64::MAX)]
    fn little_endian_bytes_decode_exactly(#[case] wire_bytes: [u8; 8], #[case] expected: u64) {
        assert_eq!(
            u64_from_le_bytes(wire_bytes),
            expected,
            "u64_from_le_bytes(wire_bytes) should equal expected"
        );
    }

    #[rstest]
    #[case(&[0xab], Endianness::Big, [0, 0, 0, 0, 0, 0, 0, 0xab])]
    #[case(&[0x01, 0x02], Endianness::Big, [0, 0, 0, 0, 0, 0, 0x01, 0x02])]
    #[case(
        &[0x01, 0x02, 0x03, 0x04],
        Endianness::Big,
        [0, 0, 0, 0, 0x01, 0x02, 0x03, 0x04]
    )]
    #[case(
        &[1, 2, 3, 4, 5, 6, 7, 8],
        Endianness::Big,
        [1, 2, 3, 4, 5, 6, 7, 8]
    )]
    #[case(&[0xcd], Endianness::Little, [0xcd, 0, 0, 0, 0, 0, 0, 0])]
    #[case(&[0x01, 0x02], Endianness::Little, [0x01, 0x02, 0, 0, 0, 0, 0, 0])]
    #[case(
        &[0x01, 0x02, 0x03, 0x04],
        Endianness::Little,
        [0x01, 0x02, 0x03, 0x04, 0, 0, 0, 0]
    )]
    #[case(
        &[1, 2, 3, 4, 5, 6, 7, 8],
        Endianness::Little,
        [1, 2, 3, 4, 5, 6, 7, 8]
    )]
    fn fill_buf_with_prefix_copies_bytes_into_expected_region(
        #[case] input: &[u8],
        #[case] endianness: Endianness,
        #[case] expected: [u8; 8],
    ) {
        let mut buf = [0u8; 8];
        fill_buf_with_prefix(&mut buf, input, endianness).expect("prefix copy should succeed");
        assert_eq!(buf, expected, "buf should equal expected");
    }
}