use core::result;
use crate::ctx::TryIntoCtx;
use crate::error;
pub trait Pwrite<Ctx: Copy, E> {
#[inline]
fn pwrite<N: TryIntoCtx<Ctx, Self, Error = E>>(
&mut self,
n: N,
offset: usize,
) -> result::Result<usize, E>
where
Ctx: Default,
{
self.pwrite_with(n, offset, Ctx::default())
}
fn pwrite_with<N: TryIntoCtx<Ctx, Self, Error = E>>(
&mut self,
n: N,
offset: usize,
ctx: Ctx,
) -> result::Result<usize, E>;
#[inline]
fn gwrite<N: TryIntoCtx<Ctx, Self, Error = E>>(
&mut self,
n: N,
offset: &mut usize,
) -> result::Result<usize, E>
where
Ctx: Default,
{
let ctx = Ctx::default();
self.gwrite_with(n, offset, ctx)
}
#[inline]
fn gwrite_with<N: TryIntoCtx<Ctx, Self, Error = E>>(
&mut self,
n: N,
offset: &mut usize,
ctx: Ctx,
) -> result::Result<usize, E> {
let o = *offset;
self.pwrite_with(n, o, ctx).map(|size| {
*offset += size;
size
})
}
}
impl<Ctx: Copy, E: From<error::Error>> Pwrite<Ctx, E> for [u8] {
fn pwrite_with<N: TryIntoCtx<Ctx, Self, Error = E>>(
&mut self,
n: N,
offset: usize,
ctx: Ctx,
) -> result::Result<usize, E> {
if offset > self.len() {
return Err(error::Error::BadOffset(offset).into());
}
let dst = &mut self[offset..];
n.try_into_ctx(dst, ctx)
}
}