use crate::abortable::{AbortHandle, AbortInner, Aborted};
use futures_core::future::Future;
use futures_core::task::{Context, Poll};
use futures_io::{AsyncBufRead, AsyncWrite};
use pin_project_lite::pin_project;
use std::io;
use std::pin::Pin;
use std::sync::atomic::Ordering;
use std::sync::Arc;
pub fn copy_buf_abortable<R, W>(
reader: R,
writer: &mut W,
) -> (CopyBufAbortable<'_, R, W>, AbortHandle)
where
R: AsyncBufRead,
W: AsyncWrite + Unpin + ?Sized,
{
let (handle, reg) = AbortHandle::new_pair();
(CopyBufAbortable { reader, writer, amt: 0, inner: reg.inner }, handle)
}
pin_project! {
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct CopyBufAbortable<'a, R, W: ?Sized> {
#[pin]
reader: R,
writer: &'a mut W,
amt: u64,
inner: Arc<AbortInner>
}
}
macro_rules! ready_or_break {
($e:expr $(,)?) => {
match $e {
$crate::task::Poll::Ready(t) => t,
$crate::task::Poll::Pending => break,
}
};
}
impl<R, W> Future for CopyBufAbortable<'_, R, W>
where
R: AsyncBufRead,
W: AsyncWrite + Unpin + Sized,
{
type Output = Result<Result<u64, Aborted>, io::Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
loop {
if this.inner.aborted.load(Ordering::Relaxed) {
return Poll::Ready(Ok(Err(Aborted)));
}
let buffer = ready_or_break!(this.reader.as_mut().poll_fill_buf(cx))?;
if buffer.is_empty() {
ready_or_break!(Pin::new(&mut this.writer).poll_flush(cx))?;
return Poll::Ready(Ok(Ok(*this.amt)));
}
let i = ready_or_break!(Pin::new(&mut this.writer).poll_write(cx, buffer))?;
if i == 0 {
return Poll::Ready(Err(io::ErrorKind::WriteZero.into()));
}
*this.amt += i as u64;
this.reader.as_mut().consume(i);
}
this.inner.waker.register(cx.waker());
if this.inner.aborted.load(Ordering::Relaxed) {
return Poll::Ready(Ok(Err(Aborted)));
}
Poll::Pending
}
}