use std::sync::Arc;
use crate::error::VfsResult;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SourceId(u64);
impl SourceId {
pub const ROOT: SourceId = SourceId(0);
#[must_use]
pub const fn new(id: u64) -> Self {
Self(id)
}
#[must_use]
pub const fn get(self) -> u64 {
self.0
}
}
impl Default for SourceId {
fn default() -> Self {
Self::ROOT
}
}
pub enum SourceView<'a> {
Mmap(&'a [u8]),
Block(Arc<[u8]>, core::ops::Range<usize>),
}
impl core::ops::Deref for SourceView<'_> {
type Target = [u8];
fn deref(&self) -> &[u8] {
match self {
SourceView::Mmap(s) => s,
SourceView::Block(arc, r) => arc.get(r.clone()).unwrap_or(&[]),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Extent {
pub offset: u64,
pub len: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Extents {
runs: Vec<Extent>,
}
impl Extents {
#[must_use]
pub fn dense(len: u64) -> Self {
if len == 0 {
Self { runs: Vec::new() }
} else {
Self {
runs: vec![Extent { offset: 0, len }],
}
}
}
#[must_use]
pub fn from_runs(runs: Vec<Extent>) -> Self {
Self { runs }
}
#[must_use]
pub fn runs(&self) -> &[Extent] {
&self.runs
}
#[must_use]
pub fn allocated_len(&self) -> u64 {
self.runs
.iter()
.fold(0u64, |acc, r| acc.saturating_add(r.len))
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.runs.is_empty()
}
}
pub trait ImageSource: Send + Sync {
fn len(&self) -> u64;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn read_at(&self, offset: u64, buf: &mut [u8]) -> VfsResult<usize>;
fn extents(&self) -> Extents {
Extents::dense(self.len())
}
fn view(&self, offset: u64, len: usize) -> Option<SourceView<'_>> {
let _ = (offset, len);
None
}
fn source_id(&self) -> SourceId {
SourceId::ROOT
}
}
pub type DynSource = Arc<dyn ImageSource>;
pub fn read_exact_at(src: &dyn ImageSource, offset: u64, buf: &mut [u8]) -> VfsResult<()> {
let got = src.read_at(offset, buf)?;
if got == buf.len() {
Ok(())
} else {
Err(crate::error::VfsError::OutOfRange {
what: "read_exact_at",
offset,
len: buf.len() as u64,
bound: src.len(),
})
}
}