use std::io;
use bytes::Buf;
use super::format::Endianness;
use crate::byte_order::{read_network_u64, write_network_u64};
pub(crate) const ERR_UNSUPPORTED_PREFIX: &str = "unsupported length prefix size";
pub(crate) const ERR_FRAME_TOO_LARGE: &str = "frame too large";
pub(crate) const ERR_INCOMPLETE_PREFIX: &str = "incomplete length prefix";
#[inline]
fn u64_from_le_bytes(bytes: [u8; 8]) -> u64 {
let mut wire_bytes = bytes.as_slice();
wire_bytes.get_u64_le()
}
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))
}
#[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(())
}
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)?;
let val = match endianness {
Endianness::Big => read_network_u64(buf),
Endianness::Little => u64_from_le_bytes(buf),
};
Ok(val)
}
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)
}
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(())
}
}
}
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,
}
}
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,
))
}
}
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(())
}
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;
}
}
#[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 {
use rstest::rstest;
use super::*;
use crate::frame::format::Endianness;
#[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");
}
}