use std::io::{self, Read, Seek, SeekFrom};
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::Mutex;
pub trait RandomAccessRead: Send + Sync {
fn len(&self) -> u64;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize>;
}
pub(crate) enum Backing {
Memory(Arc<[u8]>),
#[cfg(not(target_arch = "wasm32"))]
File {
file: Mutex<std::fs::File>,
len: u64,
},
Custom(Arc<dyn RandomAccessRead>),
}
impl Backing {
pub(crate) fn len(&self) -> u64 {
match self {
Self::Memory(bytes) => bytes.len() as u64,
#[cfg(not(target_arch = "wasm32"))]
Self::File { len, .. } => *len,
Self::Custom(source) => source.len(),
}
}
}
#[derive(Clone)]
pub(crate) struct BackingReader {
backing: Arc<Backing>,
pos: u64,
}
impl BackingReader {
pub(crate) const fn new(backing: Arc<Backing>) -> Self {
Self { backing, pos: 0 }
}
}
impl Read for BackingReader {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match self.backing.as_ref() {
Backing::Memory(bytes) => {
let Ok(offset) = usize::try_from(self.pos) else {
return Ok(0);
};
let Some(rest) = bytes.get(offset..) else {
return Ok(0);
};
let count = rest.len().min(buf.len());
if let (Some(src), Some(dst)) = (rest.get(..count), buf.get_mut(..count)) {
dst.copy_from_slice(src);
self.pos = self.pos.saturating_add(count as u64);
Ok(count)
} else {
Ok(0)
}
}
#[cfg(not(target_arch = "wasm32"))]
Backing::File { file, .. } => {
let mut guard = file
.lock()
.map_err(|_| io::Error::other("package file lock poisoned"))?;
guard.seek(SeekFrom::Start(self.pos))?;
let count = guard.read(buf)?;
drop(guard);
self.pos = self.pos.saturating_add(count as u64);
Ok(count)
}
Backing::Custom(source) => {
let count = source.read_at(self.pos, buf)?;
self.pos = self.pos.saturating_add(count as u64);
Ok(count)
}
}
}
}
impl Seek for BackingReader {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
let len = self.backing.len();
let target: i128 = match pos {
SeekFrom::Start(offset) => i128::from(offset),
SeekFrom::End(delta) => i128::from(len) + i128::from(delta),
SeekFrom::Current(delta) => i128::from(self.pos) + i128::from(delta),
};
let next = u64::try_from(target).map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidInput,
"cannot seek to a negative position",
)
})?;
self.pos = next;
Ok(next)
}
}