use core::convert::Infallible;
use core::num::NonZeroUsize;
use std::io::Error;
use std::io::ErrorKind;
use std::io::Result;
use std::string::FromUtf8Error;
use qubit_codec::Codec;
use qubit_codec::DecodeFailure;
use qubit_codec_binary::Leb128Codec;
use qubit_codec_binary::Leb128DecodeError;
use qubit_codec_binary::NonStrict;
use qubit_io::ByteInput;
use qubit_io::ByteOutput;
use qubit_io::Input;
use qubit_io::Output;
use qubit_utils::try_reserve_vec;
const U32_LENGTH_OVERFLOW: &str = "string length exceeds maximum encodable u32 length";
#[cfg(not(any(
target_pointer_width = "16",
target_pointer_width = "32",
target_pointer_width = "64",
)))]
const U64_LENGTH_OVERFLOW: &str = "string length exceeds maximum encodable u64 length";
pub(crate) const MIN_CODEC_BUFFER_CAPACITY: usize = {
const ENCODE: usize = Leb128Codec::<u128, NonStrict>::MAX_ENCODE_UNITS_PER_VALUE;
const DECODE: usize = Leb128Codec::<u128, NonStrict>::MAX_DECODE_UNITS_PER_VALUE;
if ENCODE > DECODE { ENCODE } else { DECODE }
};
#[inline(always)]
pub(crate) fn write_all<O>(output: &mut O, input: &[u8]) -> Result<()>
where
O: ByteOutput + ?Sized,
{
Output::write_fully(output, input)
}
#[must_use]
#[inline(always)]
pub(crate) unsafe fn decode_infallible_unchecked<C>(input: &[u8], index: usize) -> C::Value
where
C: Codec<Unit = u8, DecodeError = Infallible> + Default,
{
let mut codec = C::default();
match unsafe { Codec::decode(&mut codec, input, index) } {
Ok((value, _)) => value,
Err(DecodeFailure::Invalid { source, .. }) => match source {},
Err(DecodeFailure::Incomplete { .. }) => {
unreachable!("infallible codec reported incomplete input")
}
}
}
#[must_use = "the returned byte count determines the encoded payload range"]
#[inline(always)]
pub(crate) unsafe fn encode_infallible_unchecked<C>(value: C::Value, output: &mut [u8], index: usize) -> usize
where
C: Codec<Unit = u8, EncodeError = Infallible> + Default,
{
let mut codec = C::default();
match unsafe { Codec::encode(&mut codec, &value, output, index) } {
Ok(written) => written,
Err(error) => match error {},
}
}
#[inline(always)]
pub(crate) unsafe fn decode_leb128_unchecked<C>(
input: &[u8],
index: usize,
) -> std::result::Result<(C::Value, NonZeroUsize), Leb128DecodeError>
where
C: Codec<Unit = u8, DecodeError = Leb128DecodeError> + Default,
{
let mut codec = C::default();
unsafe { Codec::decode(&mut codec, input, index) }.map_err(|failure| match failure {
DecodeFailure::Invalid { source, .. } => source,
DecodeFailure::Incomplete {
source: Some(source), ..
} => source,
DecodeFailure::Incomplete { required_total, .. } => {
Leb128DecodeError::incomplete(index, required_total, input.len().saturating_sub(index))
}
})
}
pub(crate) fn read_leb128_payload<const N: usize, C, R>(reader: &mut R) -> Result<C::Value>
where
R: ByteInput + ?Sized,
C: Codec<Unit = u8, DecodeError = Leb128DecodeError> + Default,
{
let mut bytes = [0u8; N];
for index in 0..N {
Input::read_exactly(reader, &mut bytes[index..=index])?;
if bytes[index] & 0x80 == 0 {
return unsafe { decode_leb128_unchecked::<C>(&bytes, 0) }
.map(|(value, _)| value)
.map_err(map_leb128_decode_error);
}
}
unsafe { decode_leb128_unchecked::<C>(&bytes, 0) }
.map(|(value, _)| value)
.map_err(map_leb128_decode_error)
}
pub(crate) fn read_leb128_from_reader<const N: usize, C, R>(
reader: &mut R,
buffer: &mut [u8; MIN_CODEC_BUFFER_CAPACITY],
) -> Result<C::Value>
where
R: ByteInput + ?Sized,
C: Codec<Unit = u8, DecodeError = Leb128DecodeError> + Default,
{
let payload = buffer.get_mut(..N).ok_or_else(|| {
Error::new(
ErrorKind::InvalidInput,
"LEB128 codec width exceeds the internal buffer",
)
})?;
for index in 0..N {
Input::read_exactly(reader, &mut payload[index..=index])?;
if payload[index] & 0x80 == 0 {
return unsafe { decode_leb128_unchecked::<C>(payload, 0) }
.map(|(value, _)| value)
.map_err(map_leb128_decode_error);
}
}
unsafe { decode_leb128_unchecked::<C>(payload, 0) }
.map(|(value, _)| value)
.map_err(map_leb128_decode_error)
}
#[must_use]
#[inline(always)]
pub(crate) fn map_leb128_decode_error(error: Leb128DecodeError) -> Error {
Error::new(ErrorKind::InvalidData, error)
}
pub(crate) fn read_utf8_payload<R>(reader: &mut R, len: usize, max_len: usize) -> Result<String>
where
R: ByteInput + ?Sized,
{
let mut bytes = Vec::new();
read_utf8_payload_bytes(reader, &mut bytes, len, max_len)?;
String::from_utf8(bytes).map_err(invalid_utf8_error)
}
pub(crate) fn read_utf8_payload_into<R>(reader: &mut R, bytes: &mut Vec<u8>, len: usize, max_len: usize) -> Result<()>
where
R: ByteInput + ?Sized,
{
read_utf8_payload_bytes(reader, bytes, len, max_len)?;
std::str::from_utf8(bytes)
.map(|_| ())
.map_err(|error| Error::new(ErrorKind::InvalidData, error))
}
fn read_utf8_payload_bytes<R>(reader: &mut R, bytes: &mut Vec<u8>, len: usize, max_len: usize) -> Result<()>
where
R: ByteInput + ?Sized,
{
if len > max_len {
return Err(length_exceeded_error(len, max_len));
}
bytes.clear();
try_reserve_vec(bytes, len)?;
bytes.resize(len, 0);
Input::read_exactly(reader, bytes)
}
#[inline(always)]
pub(crate) fn write_utf8_payload<W>(writer: &mut W, value: &str) -> Result<()>
where
W: ByteOutput + ?Sized,
{
write_all(writer, value.as_bytes())
}
#[inline]
pub(crate) fn write_utf8_string_with_u16_len<W, F>(writer: &mut W, value: &str, write_len: F) -> Result<()>
where
W: ByteOutput + ?Sized,
F: FnOnce(&mut W, u16) -> Result<()>,
{
let bytes = value.as_bytes();
write_len(writer, checked_u16_len(bytes.len())?)?;
write_all(writer, bytes)
}
#[inline]
pub(crate) fn write_utf8_string_with_u32_len<W, F>(writer: &mut W, value: &str, write_len: F) -> Result<()>
where
W: ByteOutput + ?Sized,
F: FnOnce(&mut W, u32) -> Result<()>,
{
let bytes = value.as_bytes();
write_len(writer, checked_u32_len(bytes.len())?)?;
write_all(writer, bytes)
}
#[inline]
pub(crate) fn checked_u16_len(len: usize) -> Result<u16> {
u16::try_from(len).map_err(|_| {
Error::new(
ErrorKind::InvalidInput,
format!("string length {len} exceeds maximum encodable u16 length"),
)
})
}
#[inline]
pub(crate) fn checked_u32_len(len: usize) -> Result<u32> {
if len <= u32::MAX as usize {
Ok(len as u32)
} else {
Err(Error::new(ErrorKind::InvalidInput, U32_LENGTH_OVERFLOW))
}
}
#[inline]
pub(crate) fn checked_u64_len(len: usize) -> Result<u64> {
#[cfg(any(
target_pointer_width = "16",
target_pointer_width = "32",
target_pointer_width = "64",
))]
{
Ok(len as u64)
}
#[cfg(not(any(
target_pointer_width = "16",
target_pointer_width = "32",
target_pointer_width = "64",
)))]
{
u64::try_from(len).map_err(|_| Error::new(ErrorKind::InvalidInput, U64_LENGTH_OVERFLOW))
}
}
#[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
#[inline]
pub(crate) fn usize_from_u32_len(len: u32) -> Result<usize> {
usize::try_from(len).map_err(|_| {
Error::new(
ErrorKind::InvalidData,
format!("string length {len} exceeds maximum supported usize length"),
)
})
}
#[cfg(not(target_pointer_width = "64"))]
#[inline]
pub(crate) fn usize_from_u64_len(len: u64) -> Result<usize> {
usize::try_from(len).map_err(|_| {
Error::new(
ErrorKind::InvalidData,
format!("string length {len} exceeds maximum supported usize length"),
)
})
}
#[must_use]
#[inline]
pub(crate) fn length_exceeded_error(len: usize, max_len: usize) -> Error {
Error::new(
ErrorKind::InvalidData,
format!("string length {len} exceeds maximum length of {max_len} bytes"),
)
}
#[must_use]
#[inline]
pub(crate) fn invalid_utf8_error(error: FromUtf8Error) -> Error {
Error::new(ErrorKind::InvalidData, error)
}