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