use std::fmt::Debug;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use crate::error::FsError;
use crate::error::FsErrorKind;
use crate::error::FsOperation;
use crate::error::FsResult;
use crate::metadata::FileSystemLimit;
use crate::metadata::OpenedFileInfo;
use crate::read::RandomAccessReadPolicy;
use crate::spi::RandomAccessReadSession;
pub struct RandomAccessReader {
info: OpenedFileInfo,
len: u64,
limit: FileSystemLimit,
provider_id: String,
session: Box<dyn RandomAccessReadSession>,
}
impl RandomAccessReader {
pub(crate) fn new(
info: OpenedFileInfo,
len: u64,
limit: FileSystemLimit,
provider_id: String,
session: Box<dyn RandomAccessReadSession>,
) -> Self {
Self {
info,
len,
limit,
provider_id,
session,
}
}
#[inline]
#[must_use]
pub fn info(&self) -> &OpenedFileInfo {
&self.info
}
#[inline]
#[must_use]
pub fn len(&self) -> u64 {
self.len
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn read_at(&mut self, offset: u64, output: &mut [u8]) -> FsResult<usize> {
let count = RandomAccessReadPolicy::validate_read(offset, output.len(), self.len, self.limit)
.map_err(|e| e.with_path(self.info.path().clone()).with_provider(&self.provider_id))?;
if count == 0 {
return Ok(0);
}
let n = self.session.read_at(offset, &mut output[..count]).map_err(|e| {
e.with_missing_context(self.info.path(), None, &self.provider_id)
.with_operation(FsOperation::Read)
})?;
if n > count {
return Err(FsError::new(
FsErrorKind::ProviderContractViolation,
FsOperation::Read,
"provider returned more bytes than supplied buffer",
)
.with_path(self.info.path().clone())
.with_provider(&self.provider_id));
}
Ok(n)
}
}
impl Debug for RandomAccessReader {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
f.debug_struct("RandomAccessReader")
.field("info", &self.info)
.field("len", &self.len)
.finish_non_exhaustive()
}
}