futures_util/io/
copy_buf.rs
1use futures_core::future::Future;
2use futures_core::ready;
3use futures_core::task::{Context, Poll};
4use futures_io::{AsyncBufRead, AsyncWrite};
5use pin_project_lite::pin_project;
6use std::io;
7use std::pin::Pin;
8
9pub fn copy_buf<R, W>(reader: R, writer: &mut W) -> CopyBuf<'_, R, W>
35where
36 R: AsyncBufRead,
37 W: AsyncWrite + Unpin + ?Sized,
38{
39 CopyBuf { reader, writer, amt: 0 }
40}
41
42pin_project! {
43 #[derive(Debug)]
45 #[must_use = "futures do nothing unless you `.await` or poll them"]
46 pub struct CopyBuf<'a, R, W: ?Sized> {
47 #[pin]
48 reader: R,
49 writer: &'a mut W,
50 amt: u64,
51 }
52}
53
54impl<R, W> Future for CopyBuf<'_, R, W>
55where
56 R: AsyncBufRead,
57 W: AsyncWrite + Unpin + ?Sized,
58{
59 type Output = io::Result<u64>;
60
61 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
62 let mut this = self.project();
63 loop {
64 let buffer = ready!(this.reader.as_mut().poll_fill_buf(cx))?;
65 if buffer.is_empty() {
66 ready!(Pin::new(&mut this.writer).poll_flush(cx))?;
67 return Poll::Ready(Ok(*this.amt));
68 }
69
70 let i = ready!(Pin::new(&mut this.writer).poll_write(cx, buffer))?;
71 if i == 0 {
72 return Poll::Ready(Err(io::ErrorKind::WriteZero.into()));
73 }
74 *this.amt += i as u64;
75 this.reader.as_mut().consume(i);
76 }
77 }
78}