use std::{
future::Future,
pin::Pin,
sync::{Arc, Mutex, MutexGuard},
task::{Context, Poll},
};
use crate::error::{Error, Result};
pub const DEFAULT_WINDOW: usize = 4 * 1024;
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
#[derive(Default)]
pub(super) struct Slot {
pub(super) request: Option<(u64, usize, usize)>,
pub(super) buf: Vec<u8>,
}
#[derive(Default)]
pub(super) struct Link {
slot: Mutex<Slot>,
}
impl Link {
pub(super) fn lock(&self) -> MutexGuard<'_, Slot> {
self.slot.lock().unwrap_or_else(|e| e.into_inner())
}
}
pub struct Io {
link: Arc<Link>,
total: u64,
win: Vec<u8>,
start: u64,
}
impl Io {
pub(super) fn new(total: u64, link: Arc<Link>) -> Self {
Self {
link,
total,
win: Vec::new(),
start: 0,
}
}
pub fn len(&self) -> u64 {
self.total
}
pub fn is_empty(&self) -> bool {
self.total == 0
}
pub fn fork(&self) -> Io {
Io::new(self.total, self.link.clone())
}
#[cfg(feature = "svg")]
pub(crate) fn into_tokio_reader(self) -> TokioReader {
TokioReader {
io: self,
pos: 0,
asked: false,
}
}
fn covers(&self, offset: u64, len: usize) -> bool {
offset >= self.start
&& offset
.checked_add(len as u64)
.is_some_and(|end| end <= self.start + self.win.len() as u64)
}
pub async fn read_at(&mut self, offset: u64, buf: &mut [u8]) -> Result<()> {
if buf.is_empty() {
return Ok(());
}
if self.covers(offset, buf.len()) {
let from = (offset - self.start) as usize;
buf.copy_from_slice(&self.win[from..from + buf.len()]);
return Ok(());
}
let bytes = self.fetch(offset, buf.len()).await?;
buf.copy_from_slice(&bytes[..buf.len()]);
Ok(())
}
pub async fn fetch(&mut self, offset: u64, min: usize) -> Result<&[u8]> {
self.fetch_with(offset, min, DEFAULT_WINDOW).await
}
pub async fn fetch_with(&mut self, offset: u64, min: usize, window: usize) -> Result<&[u8]> {
if min == 0 {
return Ok(&[]);
}
if self.covers(offset, min) {
return Ok(&self.win[(offset - self.start) as usize..]);
}
Fetch {
io: &mut *self,
offset,
min,
window: window.max(min),
asked: false,
}
.await?;
let from = (offset - self.start) as usize;
Ok(&self.win[from..])
}
pub async fn read_vec(&mut self, offset: u64, len: usize) -> Result<Vec<u8>> {
if len == 0 {
return Ok(Vec::new());
}
self.fetch_with(offset, len, len).await?;
let from = (offset - self.start) as usize;
let mut v = std::mem::take(&mut self.win);
v.drain(..from);
v.truncate(len);
self.start = 0;
Ok(v)
}
}
#[cfg(feature = "svg")]
pub(crate) struct TokioReader {
io: Io,
pos: u64,
asked: bool,
}
#[cfg(feature = "svg")]
impl tokio::io::AsyncRead for TokioReader {
fn poll_read(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
let this = self.get_mut();
if buf.remaining() == 0 {
return Poll::Ready(Ok(()));
}
if this.asked {
let mut slot = this.io.link.lock();
this.io.win = std::mem::take(&mut slot.buf);
slot.request = None;
this.io.start = this.pos;
this.asked = false;
if !this.io.covers(this.pos, 1) {
return Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"failed to fill whole buffer",
)));
}
}
if this.io.covers(this.pos, 1) {
let from = (this.pos - this.io.start) as usize;
let count = (this.io.win.len() - from).min(buf.remaining());
buf.put_slice(&this.io.win[from..from + count]);
this.pos += count as u64;
return Poll::Ready(Ok(()));
}
if this.pos == this.io.total {
return Poll::Ready(Ok(()));
}
let window = (DEFAULT_WINDOW as u64).min(this.io.total - this.pos) as usize;
let mut bytes = std::mem::take(&mut this.io.win);
bytes.clear();
let mut slot = this.io.link.lock();
slot.request = Some((this.pos, 1, window));
slot.buf = bytes;
this.asked = true;
Poll::Pending
}
}
impl Io {
pub fn reader(&mut self, at: u64) -> Reader<'_> {
Reader { io: self, pos: at }
}
}
pub struct Reader<'a> {
io: &'a mut Io,
pos: u64,
}
impl Reader<'_> {
pub fn pos(&self) -> u64 {
self.pos
}
pub fn seek(&mut self, to: u64) {
self.pos = to;
}
pub fn skip(&mut self, n: u64) {
self.pos = self.pos.saturating_add(n);
}
pub fn remaining(&self) -> u64 {
self.io.total.saturating_sub(self.pos)
}
pub async fn take(&mut self, n: usize) -> Result<&[u8]> {
let at = self.pos;
self.pos = at.saturating_add(n as u64);
let bytes = self.io.fetch(at, n).await?;
Ok(&bytes[..n])
}
pub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
let at = self.pos;
self.pos = at.saturating_add(buf.len() as u64);
self.io.read_at(at, buf).await
}
fn held<const N: usize>(&mut self) -> Option<[u8; N]> {
if !self.io.covers(self.pos, N) {
return None;
}
let from = (self.pos - self.io.start) as usize;
self.pos += N as u64;
self.io.win[from..from + N].try_into().ok()
}
pub async fn array<const N: usize>(&mut self) -> Result<[u8; N]> {
if let Some(a) = self.held::<N>() {
return Ok(a);
}
let mut a = [0u8; N];
self.read_exact(&mut a).await?;
Ok(a)
}
pub async fn u8(&mut self) -> Result<u8> {
if let Some([b]) = self.held::<1>() {
return Ok(b);
}
Ok(self.array::<1>().await?[0])
}
pub async fn u16_be(&mut self) -> Result<u16> {
if let Some(a) = self.held() {
return Ok(u16::from_be_bytes(a));
}
Ok(u16::from_be_bytes(self.array().await?))
}
pub async fn u16_le(&mut self) -> Result<u16> {
if let Some(a) = self.held() {
return Ok(u16::from_le_bytes(a));
}
Ok(u16::from_le_bytes(self.array().await?))
}
pub async fn u32_be(&mut self) -> Result<u32> {
if let Some(a) = self.held() {
return Ok(u32::from_be_bytes(a));
}
Ok(u32::from_be_bytes(self.array().await?))
}
pub async fn u32_le(&mut self) -> Result<u32> {
if let Some(a) = self.held() {
return Ok(u32::from_le_bytes(a));
}
Ok(u32::from_le_bytes(self.array().await?))
}
pub async fn u64_be(&mut self) -> Result<u64> {
if let Some(a) = self.held() {
return Ok(u64::from_be_bytes(a));
}
Ok(u64::from_be_bytes(self.array().await?))
}
pub async fn u64_le(&mut self) -> Result<u64> {
if let Some(a) = self.held() {
return Ok(u64::from_le_bytes(a));
}
Ok(u64::from_le_bytes(self.array().await?))
}
}
struct Fetch<'a> {
io: &'a mut Io,
offset: u64,
min: usize,
window: usize,
asked: bool,
}
fn eof() -> Error {
Error::Io(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"failed to fill whole buffer",
))
}
impl Future for Fetch<'_> {
type Output = Result<()>;
fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
if this.asked {
let mut slot = this.io.link.lock();
this.io.win = std::mem::take(&mut slot.buf);
slot.request = None;
this.io.start = this.offset;
this.asked = false;
return Poll::Ready(if this.io.covers(this.offset, this.min) {
Ok(())
} else {
Err(eof())
});
}
if this.io.covers(this.offset, this.min) {
return Poll::Ready(Ok(()));
}
let inside = this
.offset
.checked_add(this.min as u64)
.is_some_and(|end| end <= this.io.total);
if !inside {
return Poll::Ready(Err(eof()));
}
let window = (this.window as u64).min(this.io.total - this.offset) as usize;
let mut buf = std::mem::take(&mut this.io.win);
buf.clear();
let mut slot = this.io.link.lock();
slot.request = Some((this.offset, this.min, window.max(this.min)));
slot.buf = buf;
this.asked = true;
Poll::Pending
}
}