use super::{ReadAt, WriteAt, Size};
use std::cmp::min;
use std::io::{Result, Error, ErrorKind};
pub struct Slice<I> {
io: I,
offset: u64,
size: Option<u64>,
}
impl<I> Slice<I> {
pub fn new(io: I, offset: u64, size: Option<u64>) -> Self {
Slice {
io: io,
offset: offset,
size: size,
}
}
fn avail(&self, pos: u64, bytes: usize) -> usize {
match self.size {
None => bytes,
Some(size) if pos >= size => 0,
Some(size) => min(bytes as u64, size - pos) as usize,
}
}
}
impl<I> Slice<I>
where I: Size
{
pub fn new_to_end(io: I, offset: u64) -> Result<Self> {
match io.size() {
Ok(Some(size)) => Ok(Self::new(io, offset, Some(size - offset))),
_ => Err(Error::new(ErrorKind::InvalidData, "unknown base size")),
}
}
}
impl<I> ReadAt for Slice<I>
where I: ReadAt
{
fn read_at(&self, pos: u64, buf: &mut [u8]) -> Result<usize> {
let bytes = self.avail(pos, buf.len());
self.io.read_at(pos + self.offset, &mut buf[..bytes])
}
}
impl<I> WriteAt for Slice<I>
where I: WriteAt
{
fn write_at(&mut self, pos: u64, buf: &[u8]) -> Result<usize> {
let bytes = self.avail(pos, buf.len());
self.io.write_at(pos + self.offset, &buf[..bytes])
}
fn flush(&mut self) -> Result<()> {
self.io.flush()
}
}
impl<I> Size for Slice<I> {
fn size(&self) -> Result<Option<u64>> {
Ok(self.size)
}
}