use super::{AsyncBufRead, AsyncWrite};
use core::{
pin::Pin,
task::{Context, Poll},
};
use futures::{ready, Future};
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
struct CopyBuf<'a, R: ?Sized, W: ?Sized> {
reader: &'a mut R,
writer: &'a mut W,
amt: u64,
}
pub async fn copy_buf<'a, R, W>(reader: &'a mut R, writer: &'a mut W) -> Result<u64, R::Error>
where
R: AsyncBufRead + Unpin + ?Sized,
W: AsyncWrite + Unpin + ?Sized,
R::Error: From<W::Error>,
{
CopyBuf {
reader,
writer,
amt: 0,
}
.await
}
impl<R, W> Future for CopyBuf<'_, R, W>
where
R: AsyncBufRead + Unpin + ?Sized,
W: AsyncWrite + Unpin + ?Sized,
R::Error: From<W::Error>,
{
type Output = Result<u64, R::Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
let me = &mut *self;
let buffer = ready!(Pin::new(&mut *me.reader).poll_fill_buf(cx))?;
if buffer.is_empty() {
ready!(Pin::new(&mut *me.writer).poll_flush(cx))?;
return Poll::Ready(Ok(self.amt));
}
let i = ready!(Pin::new(&mut *me.writer).poll_write(cx, buffer))?;
if i == 0 {
todo!()
}
self.amt += i as u64;
Pin::new(&mut *self.reader).consume(i);
}
}
}