use core::mem::{MaybeUninit, size_of};
use core::ptr::copy_nonoverlapping;
use core::{result, str};
#[cfg(feature = "std")]
use std::ffi::{CStr, CString};
use crate::endian::Endian;
use crate::{Pread, Pwrite, error};
pub trait MeasureWith<Ctx> {
fn measure_with(&self, ctx: &Ctx) -> usize;
}
impl<Ctx> MeasureWith<Ctx> for [u8] {
#[inline]
fn measure_with(&self, _ctx: &Ctx) -> usize {
self.len()
}
}
impl<Ctx, T: AsRef<[u8]>> MeasureWith<Ctx> for T {
#[inline]
fn measure_with(&self, _ctx: &Ctx) -> usize {
self.as_ref().len()
}
}
#[derive(Debug, Copy, Clone)]
pub enum StrCtx {
Delimiter(u8),
DelimiterUntil(u8, usize),
Length(usize),
}
pub const NULL: u8 = 0;
pub const SPACE: u8 = 0x20;
pub const RET: u8 = 0x0a;
pub const TAB: u8 = 0x09;
impl Default for StrCtx {
#[inline]
fn default() -> Self {
StrCtx::Delimiter(NULL)
}
}
impl StrCtx {
pub fn len(&self) -> usize {
match self {
StrCtx::Delimiter(_) | StrCtx::DelimiterUntil(_, _) => 1,
StrCtx::Length(_) => 0,
}
}
pub fn is_empty(&self) -> bool {
matches!(self, StrCtx::Length(_))
}
}
pub trait FromCtx<Ctx: Copy = (), This: ?Sized = [u8]> {
fn from_ctx(this: &This, ctx: Ctx) -> Self;
}
pub trait TryFromCtx<'a, Ctx: Copy = (), This: ?Sized = [u8]>
where
Self: 'a + Sized,
{
type Error;
fn try_from_ctx(from: &'a This, ctx: Ctx) -> Result<(Self, usize), Self::Error>;
}
pub trait IntoCtx<Ctx: Copy = (), This: ?Sized = [u8]>: Sized {
fn into_ctx(self, _: &mut This, ctx: Ctx);
}
pub trait TryIntoCtx<Ctx: Copy = (), This: ?Sized = [u8]>: Sized {
type Error;
fn try_into_ctx(self, _: &mut This, ctx: Ctx) -> Result<usize, Self::Error>;
}
pub trait SizeWith<Ctx = ()> {
fn size_with(ctx: &Ctx) -> usize;
}
#[rustfmt::skip]
macro_rules! signed_to_unsigned {
(i8) => {u8 };
(u8) => {u8 };
(i16) => {u16};
(u16) => {u16};
(i32) => {u32};
(u32) => {u32};
(i64) => {u64};
(u64) => {u64};
(i128) => {u128};
(u128) => {u128};
(f32) => {u32};
(f64) => {u64};
}
macro_rules! write_into {
($typ:ty, $size:expr, $n:expr, $dst:expr, $endian:expr) => {{
assert!($dst.len() >= $size);
let bytes = if $endian.is_little() {
$n.to_le()
} else {
$n.to_be()
}
.to_ne_bytes();
unsafe {
copy_nonoverlapping((&bytes).as_ptr(), $dst.as_mut_ptr(), $size);
}
}};
}
macro_rules! into_ctx_impl {
($typ:tt, $size:expr) => {
impl IntoCtx<Endian> for $typ {
#[inline]
fn into_ctx(self, dst: &mut [u8], le: Endian) {
assert!(dst.len() >= $size);
write_into!($typ, $size, self, dst, le);
}
}
impl<'a> IntoCtx<Endian> for &'a $typ {
#[inline]
fn into_ctx(self, dst: &mut [u8], le: Endian) {
(*self).into_ctx(dst, le)
}
}
impl TryIntoCtx<Endian> for $typ
where
$typ: IntoCtx<Endian>,
{
type Error = error::Error;
#[inline]
fn try_into_ctx(self, dst: &mut [u8], le: Endian) -> error::Result<usize> {
if $size > dst.len() {
Err(error::Error::TooBig {
size: $size,
len: dst.len(),
})
} else {
<$typ as IntoCtx<Endian>>::into_ctx(self, dst, le);
Ok($size)
}
}
}
impl<'a> TryIntoCtx<Endian> for &'a $typ {
type Error = error::Error;
#[inline]
fn try_into_ctx(self, dst: &mut [u8], le: Endian) -> error::Result<usize> {
(*self).try_into_ctx(dst, le)
}
}
};
}
macro_rules! from_ctx_impl {
($typ:tt, $size:expr) => {
impl<'a> FromCtx<Endian> for $typ {
#[inline]
fn from_ctx(src: &[u8], le: Endian) -> Self {
assert!(src.len() >= $size);
let mut data: signed_to_unsigned!($typ) = 0;
unsafe {
copy_nonoverlapping(
src.as_ptr(),
&mut data as *mut signed_to_unsigned!($typ) as *mut u8,
$size,
);
}
(if le.is_little() {
data.to_le()
} else {
data.to_be()
}) as $typ
}
}
impl<'a> TryFromCtx<'a, Endian> for $typ
where
$typ: FromCtx<Endian>,
{
type Error = error::Error;
#[inline]
fn try_from_ctx(
src: &'a [u8],
le: Endian,
) -> result::Result<(Self, usize), Self::Error> {
if $size > src.len() {
Err(error::Error::TooBig {
size: $size,
len: src.len(),
})
} else {
Ok((FromCtx::from_ctx(&src, le), $size))
}
}
}
impl<'a, T> FromCtx<Endian, T> for $typ
where
T: AsRef<[u8]>,
{
#[inline]
fn from_ctx(src: &T, le: Endian) -> Self {
let src = src.as_ref();
assert!(src.len() >= $size);
let mut data: signed_to_unsigned!($typ) = 0;
unsafe {
copy_nonoverlapping(
src.as_ptr(),
&mut data as *mut signed_to_unsigned!($typ) as *mut u8,
$size,
);
}
(if le.is_little() {
data.to_le()
} else {
data.to_be()
}) as $typ
}
}
impl<'a, T> TryFromCtx<'a, Endian, T> for $typ
where
$typ: FromCtx<Endian, T>,
T: AsRef<[u8]>,
{
type Error = error::Error;
#[inline]
fn try_from_ctx(src: &'a T, le: Endian) -> result::Result<(Self, usize), Self::Error> {
let src = src.as_ref();
Self::try_from_ctx(src, le)
}
}
};
}
macro_rules! ctx_impl {
($typ:tt, $size:expr) => {
from_ctx_impl!($typ, $size);
};
}
ctx_impl!(u8, 1);
ctx_impl!(i8, 1);
ctx_impl!(u16, 2);
ctx_impl!(i16, 2);
ctx_impl!(u32, 4);
ctx_impl!(i32, 4);
ctx_impl!(u64, 8);
ctx_impl!(i64, 8);
ctx_impl!(u128, 16);
ctx_impl!(i128, 16);
macro_rules! from_ctx_float_impl {
($typ:tt, $size:expr) => {
impl<'a> FromCtx<Endian> for $typ {
#[inline]
fn from_ctx(src: &[u8], le: Endian) -> Self {
assert!(src.len() >= ::core::mem::size_of::<Self>());
let mut data: signed_to_unsigned!($typ) = 0;
unsafe {
copy_nonoverlapping(
src.as_ptr(),
&mut data as *mut signed_to_unsigned!($typ) as *mut u8,
$size,
);
}
$typ::from_bits(if le.is_little() {
data.to_le()
} else {
data.to_be()
})
}
}
impl<'a> TryFromCtx<'a, Endian> for $typ
where
$typ: FromCtx<Endian>,
{
type Error = error::Error;
#[inline]
fn try_from_ctx(
src: &'a [u8],
le: Endian,
) -> result::Result<(Self, usize), Self::Error> {
if $size > src.len() {
Err(error::Error::TooBig {
size: $size,
len: src.len(),
})
} else {
Ok((FromCtx::from_ctx(src, le), $size))
}
}
}
};
}
from_ctx_float_impl!(f32, 4);
from_ctx_float_impl!(f64, 8);
into_ctx_impl!(u8, 1);
into_ctx_impl!(i8, 1);
into_ctx_impl!(u16, 2);
into_ctx_impl!(i16, 2);
into_ctx_impl!(u32, 4);
into_ctx_impl!(i32, 4);
into_ctx_impl!(u64, 8);
into_ctx_impl!(i64, 8);
into_ctx_impl!(u128, 16);
into_ctx_impl!(i128, 16);
macro_rules! into_ctx_float_impl {
($typ:tt, $size:expr) => {
impl IntoCtx<Endian> for $typ {
#[inline]
fn into_ctx(self, dst: &mut [u8], le: Endian) {
assert!(dst.len() >= $size);
write_into!(signed_to_unsigned!($typ), $size, self.to_bits(), dst, le);
}
}
impl<'a> IntoCtx<Endian> for &'a $typ {
#[inline]
fn into_ctx(self, dst: &mut [u8], le: Endian) {
(*self).into_ctx(dst, le)
}
}
impl TryIntoCtx<Endian> for $typ
where
$typ: IntoCtx<Endian>,
{
type Error = error::Error;
#[inline]
fn try_into_ctx(self, dst: &mut [u8], le: Endian) -> error::Result<usize> {
if $size > dst.len() {
Err(error::Error::TooBig {
size: $size,
len: dst.len(),
})
} else {
<$typ as IntoCtx<Endian>>::into_ctx(self, dst, le);
Ok($size)
}
}
}
impl<'a> TryIntoCtx<Endian> for &'a $typ {
type Error = error::Error;
#[inline]
fn try_into_ctx(self, dst: &mut [u8], le: Endian) -> error::Result<usize> {
(*self).try_into_ctx(dst, le)
}
}
};
}
into_ctx_float_impl!(f32, 4);
into_ctx_float_impl!(f64, 8);
impl<'a> TryFromCtx<'a, StrCtx> for &'a str {
type Error = error::Error;
#[inline]
fn try_from_ctx(src: &'a [u8], ctx: StrCtx) -> Result<(Self, usize), Self::Error> {
let len = match ctx {
StrCtx::Length(len) => len,
StrCtx::Delimiter(delimiter) => src.iter().take_while(|c| **c != delimiter).count(),
StrCtx::DelimiterUntil(delimiter, len) => {
if len > src.len() {
return Err(error::Error::TooBig {
size: len,
len: src.len(),
});
};
src.iter()
.take_while(|c| **c != delimiter)
.take(len)
.count()
}
};
if len > src.len() {
return Err(error::Error::TooBig {
size: len,
len: src.len(),
});
};
match str::from_utf8(&src[..len]) {
Ok(res) => Ok((res, len + ctx.len())),
Err(_) => Err(error::Error::BadInput {
size: src.len(),
msg: "invalid utf8",
}),
}
}
}
impl<'a, T> TryFromCtx<'a, StrCtx, T> for &'a str
where
T: AsRef<[u8]>,
{
type Error = error::Error;
#[inline]
fn try_from_ctx(src: &'a T, ctx: StrCtx) -> result::Result<(Self, usize), Self::Error> {
let src = src.as_ref();
TryFromCtx::try_from_ctx(src, ctx)
}
}
impl<'a> TryIntoCtx for &'a [u8] {
type Error = error::Error;
#[inline]
fn try_into_ctx(self, dst: &mut [u8], _ctx: ()) -> error::Result<usize> {
let src_len = self.len() as isize;
let dst_len = dst.len() as isize;
if src_len > dst_len {
Err(error::Error::TooBig {
size: self.len(),
len: dst.len(),
})
} else {
unsafe { copy_nonoverlapping(self.as_ptr(), dst.as_mut_ptr(), src_len as usize) };
Ok(self.len())
}
}
}
impl<'a> TryIntoCtx for &'a str {
type Error = error::Error;
#[inline]
fn try_into_ctx(self, dst: &mut [u8], _ctx: ()) -> error::Result<usize> {
let bytes = self.as_bytes();
TryIntoCtx::try_into_ctx(bytes, dst, ())
}
}
macro_rules! sizeof_impl {
($ty:ty) => {
impl SizeWith<Endian> for $ty {
#[inline]
fn size_with(_ctx: &Endian) -> usize {
size_of::<$ty>()
}
}
impl SizeWith for $ty {
#[inline]
fn size_with(_ctx: &()) -> usize {
size_of::<$ty>()
}
}
};
}
sizeof_impl!(u8);
sizeof_impl!(i8);
sizeof_impl!(u16);
sizeof_impl!(i16);
sizeof_impl!(u32);
sizeof_impl!(i32);
sizeof_impl!(u64);
sizeof_impl!(i64);
sizeof_impl!(u128);
sizeof_impl!(i128);
sizeof_impl!(f32);
sizeof_impl!(f64);
impl<'a> TryFromCtx<'a, usize> for &'a [u8] {
type Error = error::Error;
#[inline]
fn try_from_ctx(src: &'a [u8], size: usize) -> result::Result<(Self, usize), Self::Error> {
if size > src.len() {
Err(error::Error::TooBig {
size,
len: src.len(),
})
} else {
Ok((&src[..size], size))
}
}
}
impl<'a, Ctx: Copy, T: TryFromCtx<'a, Ctx, Error = error::Error>, const N: usize>
TryFromCtx<'a, Ctx> for [T; N]
{
type Error = error::Error;
fn try_from_ctx(src: &'a [u8], ctx: Ctx) -> Result<(Self, usize), Self::Error> {
let mut offset = 0;
let mut buf: [MaybeUninit<T>; N] = core::array::from_fn(|_| MaybeUninit::uninit());
let mut error_ctx = None;
for (idx, element) in buf.iter_mut().enumerate() {
match src.gread_with::<T>(&mut offset, ctx) {
Ok(val) => {
*element = MaybeUninit::new(val);
}
Err(e) => {
error_ctx = Some((e, idx));
break;
}
}
}
if let Some((e, idx)) = error_ctx {
for element in &mut buf[0..idx].iter_mut() {
unsafe {
element.assume_init_drop();
}
}
Err(e)
} else {
Ok((buf.map(|element| unsafe { element.assume_init() }), offset))
}
}
}
impl<Ctx: Copy, T: TryIntoCtx<Ctx, Error = error::Error>, const N: usize> TryIntoCtx<Ctx>
for [T; N]
{
type Error = error::Error;
fn try_into_ctx(self, buf: &mut [u8], ctx: Ctx) -> Result<usize, Self::Error> {
let mut offset = 0;
for element in self {
buf.gwrite_with(element, &mut offset, ctx)?;
}
Ok(offset)
}
}
impl<Ctx, T: SizeWith<Ctx>, const N: usize> SizeWith<Ctx> for [T; N] {
fn size_with(ctx: &Ctx) -> usize {
T::size_with(ctx) * N
}
}
#[cfg(feature = "std")]
impl<'a> TryFromCtx<'a> for &'a CStr {
type Error = error::Error;
#[inline]
fn try_from_ctx(src: &'a [u8], _ctx: ()) -> result::Result<(Self, usize), Self::Error> {
let cstr = CStr::from_bytes_until_nul(src).map_err(|_| error::Error::BadInput {
size: 0,
msg: "The input doesn't contain a null byte",
})?;
Ok((cstr, cstr.to_bytes_with_nul().len()))
}
}
#[cfg(feature = "std")]
impl<'a> TryFromCtx<'a> for CString {
type Error = error::Error;
#[inline]
fn try_from_ctx(src: &'a [u8], _ctx: ()) -> result::Result<(Self, usize), Self::Error> {
let (raw, bytes_read) = <&CStr as TryFromCtx>::try_from_ctx(src, _ctx)?;
Ok((raw.to_owned(), bytes_read))
}
}
#[cfg(feature = "std")]
impl<'a> TryIntoCtx for &'a CStr {
type Error = error::Error;
#[inline]
fn try_into_ctx(self, dst: &mut [u8], _ctx: ()) -> error::Result<usize> {
dst.pwrite(self.to_bytes_with_nul(), 0)
}
}
#[cfg(feature = "std")]
impl TryIntoCtx for CString {
type Error = error::Error;
#[inline]
fn try_into_ctx(self, dst: &mut [u8], _ctx: ()) -> error::Result<usize> {
self.as_c_str().try_into_ctx(dst, ())
}
}
#[cfg(test)]
#[cfg(feature = "std")]
mod tests {
use super::*;
#[test]
fn parse_a_cstr() {
let src = CString::new("Hello World").unwrap();
let as_bytes = src.as_bytes_with_nul();
let (got, bytes_read) = <&CStr as TryFromCtx>::try_from_ctx(as_bytes, ()).unwrap();
assert_eq!(bytes_read, as_bytes.len());
assert_eq!(got, src.as_c_str());
}
#[test]
fn round_trip_a_c_str() {
let src = CString::new("Hello World").unwrap();
let src = src.as_c_str();
let as_bytes = src.to_bytes_with_nul();
let mut buffer = vec![0; as_bytes.len()];
let bytes_written = src.try_into_ctx(&mut buffer, ()).unwrap();
assert_eq!(bytes_written, as_bytes.len());
let (got, bytes_read) = <&CStr as TryFromCtx>::try_from_ctx(&buffer, ()).unwrap();
assert_eq!(bytes_read, as_bytes.len());
assert_eq!(got, src);
}
}