use core::result;
use crate::ctx::TryFromCtx;
use crate::error;
pub trait Pread<Ctx: Copy, E> {
#[inline]
fn pread<'a, N: TryFromCtx<'a, Ctx, Self, Error = E>>(
&'a self,
offset: usize,
) -> result::Result<N, E>
where
Ctx: Default,
{
self.pread_with(offset, Ctx::default())
}
#[inline]
fn pread_with<'a, N: TryFromCtx<'a, Ctx, Self, Error = E>>(
&'a self,
offset: usize,
ctx: Ctx,
) -> result::Result<N, E> {
let mut ignored = offset;
self.gread_with(&mut ignored, ctx)
}
#[inline]
fn gread<'a, N: TryFromCtx<'a, Ctx, Self, Error = E>>(
&'a self,
offset: &mut usize,
) -> result::Result<N, E>
where
Ctx: Default,
{
let ctx = Ctx::default();
self.gread_with(offset, ctx)
}
fn gread_with<'a, N: TryFromCtx<'a, Ctx, Self, Error = E>>(
&'a self,
offset: &mut usize,
ctx: Ctx,
) -> result::Result<N, E>;
#[inline]
fn gread_inout<'a, N: TryFromCtx<'a, Ctx, Self, Error = E>>(
&'a self,
offset: &mut usize,
inout: &mut [N],
) -> result::Result<(), E>
where
Ctx: Default,
{
for i in inout.iter_mut() {
*i = self.gread(offset)?;
}
Ok(())
}
#[inline]
fn gread_inout_with<'a, N: TryFromCtx<'a, Ctx, Self, Error = E>>(
&'a self,
offset: &mut usize,
inout: &mut [N],
ctx: Ctx,
) -> result::Result<(), E> {
for i in inout.iter_mut() {
*i = self.gread_with(offset, ctx)?;
}
Ok(())
}
}
impl<Ctx: Copy, E: From<error::Error>> Pread<Ctx, E> for [u8] {
fn gread_with<'a, N: TryFromCtx<'a, Ctx, Self, Error = E>>(
&'a self,
offset: &mut usize,
ctx: Ctx,
) -> result::Result<N, E> {
let start = *offset;
if start >= self.len() {
return Err(error::Error::BadOffset(start).into());
}
N::try_from_ctx(&self[start..], ctx).map(|(n, size)| {
*offset += size;
n
})
}
}