use core::result;
use core::ops::{Index, IndexMut, RangeFrom, Add, AddAssign};
use ctx::{TryIntoCtx, MeasureWith};
use error;
pub trait Pwrite<Ctx, E, I = usize> : Index<I> + IndexMut<RangeFrom<I>> + MeasureWith<Ctx, Units = I>
where
Ctx: Copy,
I: Add + Copy + PartialOrd,
E: From<error::Error<I>>,
{
fn pwrite<N: TryIntoCtx<Ctx, <Self as Index<RangeFrom<I>>>::Output, Error = E, Size = I>>(&mut self, n: N, offset: I) -> result::Result<I, E> where Ctx: Default {
self.pwrite_with(n, offset, Ctx::default())
}
fn pwrite_with<N: TryIntoCtx<Ctx, <Self as Index<RangeFrom<I>>>::Output, Error = E, Size = I>>(&mut self, n: N, offset: I, ctx: Ctx) -> result::Result<I, E> {
let len = self.measure_with(&ctx);
if offset >= len {
return Err(error::Error::BadOffset(offset).into())
}
let dst = &mut self[offset..];
n.try_into_ctx(dst, ctx)
}
#[inline]
fn gwrite<N: TryIntoCtx<Ctx, <Self as Index<RangeFrom<I>>>::Output, Error = E, Size = I>>(&mut self, n: N, offset: &mut I) -> result::Result<I, E> where
I: AddAssign,
Ctx: Default {
let ctx = Ctx::default();
self.gwrite_with(n, offset, ctx)
}
#[inline]
fn gwrite_with<N: TryIntoCtx<Ctx, <Self as Index<RangeFrom<I>>>::Output, Error = E, Size = I>>(&mut self, n: N, offset: &mut I, ctx: Ctx) -> result::Result<I, E>
where I: AddAssign,
{
let o = *offset;
match self.pwrite_with(n, o, ctx) {
Ok(size) => {
*offset += size;
Ok(size)
},
err => err
}
}
}
impl<Ctx: Copy,
I: Add + Copy + PartialOrd,
E: From<error::Error<I>>,
R: ?Sized + Index<I> + IndexMut<RangeFrom<I>> + MeasureWith<Ctx, Units = I>>
Pwrite<Ctx, E, I> for R {}