use core::result;
use core::ops::{Index, RangeFrom, Add, AddAssign};
use ctx::{TryFromCtx, MeasureWith};
use error;
pub trait Pread<Ctx, E, I = usize> : Index<I> + Index<RangeFrom<I>> + MeasureWith<Ctx, Units = I>
where
Ctx: Copy,
I: Add + Copy + PartialOrd,
E: From<error::Error<I>>,
{
#[inline]
fn pread<'a, N: TryFromCtx<'a, Ctx, <Self as Index<RangeFrom<I>>>::Output, Error = E, Size = I>>(&'a self, offset: I) -> result::Result<N, E> where <Self as Index<RangeFrom<I>>>::Output: 'a, Ctx: Default {
self.pread_with(offset, Ctx::default())
}
#[inline]
fn pread_with<'a, N: TryFromCtx<'a, Ctx, <Self as Index<RangeFrom<I>>>::Output, Error = E, Size = I>>(&'a self, offset: I, ctx: Ctx) -> result::Result<N, E> where <Self as Index<RangeFrom<I>>>::Output: 'a {
let len = self.measure_with(&ctx);
if offset >= len {
return Err(error::Error::BadOffset(offset).into())
}
N::try_from_ctx(&self[offset..], ctx).and_then(|(n, _)| Ok(n))
}
#[inline]
fn gread<'a, N: TryFromCtx<'a, Ctx, <Self as Index<RangeFrom<I>>>::Output, Error = E, Size = I>>(&'a self, offset: &mut I) -> result::Result<N, E> where I: AddAssign, Ctx: Default, <Self as Index<RangeFrom<I>>>::Output: 'a {
let ctx = Ctx::default();
self.gread_with(offset, ctx)
}
#[inline]
fn gread_with<'a, N: TryFromCtx<'a, Ctx, <Self as Index<RangeFrom<I>>>::Output, Error = E, Size = I>>
(&'a self, offset: &mut I, ctx: Ctx) ->
result::Result<N, E>
where I: AddAssign, <Self as Index<RangeFrom<I>>>::Output: 'a
{
let o = *offset;
let len = self.measure_with(&ctx);
if o >= len {
return Err(error::Error::BadOffset(o).into())
}
N::try_from_ctx(&self[o..], ctx).and_then(|(n, size)| {
*offset += size;
Ok(n)
})
}
#[inline]
fn gread_inout<'a, N>(&'a self, offset: &mut I, inout: &mut [N]) -> result::Result<(), E>
where
I: AddAssign,
N: TryFromCtx<'a, Ctx, <Self as Index<RangeFrom<I>>>::Output, Error = E, Size = I>,
Ctx: Default,
<Self as Index<RangeFrom<I>>>::Output: 'a
{
let len = inout.len();
for i in 0..len {
inout[i] = self.gread(offset)?;
}
Ok(())
}
#[inline]
fn gread_inout_with<'a, N>(&'a self, offset: &mut I, inout: &mut [N], ctx: Ctx) -> result::Result<(), E>
where
I: AddAssign,
N: TryFromCtx<'a, Ctx, <Self as Index<RangeFrom<I>>>::Output, Error = E, Size = I>,
<Self as Index<RangeFrom<I>>>::Output: 'a
{
let len = inout.len();
for i in 0..len {
inout[i] = self.gread_with(offset, ctx)?;
}
Ok(())
}
}
impl<Ctx: Copy,
I: Add + Copy + PartialOrd,
E: From<error::Error<I>>,
R: ?Sized + Index<I> + Index<RangeFrom<I>> + MeasureWith<Ctx, Units = I>>
Pread<Ctx, E, I> for R {}