1 use futures_core::future::Future;
2 use futures_core::task::{Context, Poll};
3 use futures_io::{AsyncRead, AsyncWrite};
4 use std::io;
5 use std::pin::Pin;
6 use super::{BufReader, copy_buf, CopyBuf};
7 use pin_project_lite::pin_project;
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 `AsyncRead` 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(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 /// ```
copy<R, W>(reader: R, writer: &mut W) -> Copy<'_, R, W> where R: AsyncRead, W: AsyncWrite + Unpin + ?Sized,34 pub fn copy<R, W>(reader: R, writer: &mut W) -> Copy<'_, R, W>
35 where
36     R: AsyncRead,
37     W: AsyncWrite + Unpin + ?Sized,
38 {
39     Copy {
40         inner: copy_buf(BufReader::new(reader), writer),
41     }
42 }
43 
44 pin_project! {
45     /// Future for the [`copy()`] function.
46     #[derive(Debug)]
47     #[must_use = "futures do nothing unless you `.await` or poll them"]
48     pub struct Copy<'a, R, W: ?Sized> {
49         #[pin]
50         inner: CopyBuf<'a, BufReader<R>, W>,
51     }
52 }
53 
54 impl<R: AsyncRead, W: AsyncWrite + Unpin + ?Sized> Future for Copy<'_, R, W> {
55     type Output = io::Result<u64>;
56 
poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>57     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
58         self.project().inner.poll(cx)
59     }
60 }
61