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
9/// Creates a future which copies all the bytes from one object to another.
10///
11/// The returned future will copy all the bytes read from this `AsyncBufRead` into the
12/// `writer` specified. This future will only complete once the `reader` has hit
13/// EOF and all bytes have been written to and flushed from the `writer`
14/// provided.
15///
16/// On success the number of bytes is returned.
17///
18/// # Examples
19///
20/// ```
21/// # futures::executor::block_on(async {
22/// use futures::io::{self, AsyncWriteExt, Cursor};
23///
24/// let reader = Cursor::new([1, 2, 3, 4]);
25/// let mut writer = Cursor::new(vec![0u8; 5]);
26///
27/// let bytes = io::copy_buf(reader, &mut writer).await?;
28/// writer.close().await?;
29///
30/// assert_eq!(bytes, 4);
31/// assert_eq!(writer.into_inner(), [1, 2, 3, 4, 0]);
32/// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
33/// ```
34pub 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    /// Future for the [`copy_buf()`] function.
44    #[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}