use std::fmt;
use std::future::Future;
use std::io::{self, SeekFrom};
use std::pin::Pin;
use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::task::{Context, Poll, ready};
use futures_core::Stream;
use crate::Result;
use crate::aio::run;
use crate::blobs::{FileInfo, PIECE, position_after};
use crate::pool::Pool;
pub struct StoredFile {
info: FileInfo,
file: Arc<RwLock<crate::blobs::StoredFile>>,
inline: bool,
label: String,
pool: Arc<Pool>,
position: u64,
piece: Option<Piece>,
ended: bool,
}
type Piece = Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send>>;
impl fmt::Debug for StoredFile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "StoredFile({}, at {})", self.label, self.position)
}
}
impl StoredFile {
pub(super) fn new(file: crate::blobs::StoredFile, pool: Arc<Pool>) -> StoredFile {
let (info, inline, label) = (file.info().clone(), file.is_inline(), file.label().to_owned());
let file = Arc::new(RwLock::new(file));
StoredFile { info, file, inline, label, pool, position: 0, piece: None, ended: false }
}
pub fn info(&self) -> &FileInfo {
&self.info
}
pub fn read_all(&self) -> impl Future<Output = Result<Vec<u8>>> + Send + 'static {
let (file, inline) = (Arc::clone(&self.file), self.inline);
let reading = Arc::clone(&self.file);
let read = run::read(&self.pool, self.what("a whole read"), move || alone(&reading).read_all());
async move {
if inline {
return alone(&file).read_all();
}
read.await
}
}
pub fn read_at<'a>(&self, bytes: &'a mut [u8], offset: u64) -> impl Future<Output = io::Result<usize>> + Send + 'a {
let (file, inline) = (Arc::clone(&self.file), self.inline);
let wanted =
usize::try_from(self.info.size.saturating_sub(offset)).map_or(bytes.len(), |left| left.min(bytes.len()));
let reading = Arc::clone(&self.file);
let read = run::read(&self.pool, self.what("a read of a range"), move || {
let mut range = vec![0; wanted];
Ok(shared(&reading).read_at(&mut range, offset).map(|read| {
range.truncate(read);
range
}))
});
async move {
if inline {
return shared(&file).read_at(bytes, offset);
}
let range = read.await.map_err(io::Error::other)??;
bytes[..range.len()].copy_from_slice(&range);
Ok(range.len())
}
}
pub fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
self.position = position_after(self.position, self.info.size, to)?;
self.piece = None;
self.ended = false;
Ok(self.position)
}
fn read_piece(&self, at: u64) -> Piece {
let reading = Arc::clone(&self.file);
let read = move || alone(&reading).read_piece(at, PIECE);
if self.inline {
return Box::pin(std::future::ready(read()));
}
Box::pin(run::read(&self.pool, self.what("a piece of its stream"), read))
}
fn what(&self, verb: &str) -> String {
format!("{}: {verb}", self.label)
}
}
impl Stream for StoredFile {
type Item = Result<Vec<u8>>;
fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Result<Vec<u8>>>> {
if self.ended || self.position >= self.info.size {
return Poll::Ready(None);
}
if self.piece.is_none() {
let piece = self.read_piece(self.position);
self.piece = Some(piece);
}
let Some(piece) = self.piece.as_mut() else { return Poll::Ready(None) };
let read = ready!(piece.as_mut().poll(context));
self.piece = None;
match &read {
Ok(bytes) => self.position += bytes.len() as u64,
Err(_) => self.ended = true,
}
Poll::Ready(Some(read))
}
}
fn alone(file: &RwLock<crate::blobs::StoredFile>) -> RwLockWriteGuard<'_, crate::blobs::StoredFile> {
file.write().unwrap_or_else(PoisonError::into_inner)
}
fn shared(file: &RwLock<crate::blobs::StoredFile>) -> RwLockReadGuard<'_, crate::blobs::StoredFile> {
file.read().unwrap_or_else(PoisonError::into_inner)
}
#[cfg(test)]
#[path = "read_tests.rs"]
mod tests;