tokio/io/util/copy_buf.rs
1use crate::io::{AsyncBufRead, AsyncWrite};
2use std::future::Future;
3use std::io;
4use std::pin::Pin;
5use std::task::{ready, Context, Poll};
6
7cfg_io_util! {
8 /// A future that asynchronously copies the entire contents of a reader into a
9 /// writer.
10 ///
11 /// This struct is generally created by calling [`copy_buf`][copy_buf]. Please
12 /// see the documentation of `copy_buf()` for more details.
13 ///
14 /// [copy_buf]: copy_buf()
15 #[derive(Debug)]
16 #[must_use = "futures do nothing unless you `.await` or poll them"]
17 struct CopyBuf<'a, R: ?Sized, W: ?Sized> {
18 reader: &'a mut R,
19 writer: &'a mut W,
20 amt: u64,
21 }
22
23 /// Asynchronously copies the entire contents of a reader into a writer.
24 ///
25 /// This function returns a future that will continuously read data from
26 /// `reader` and then write it into `writer` in a streaming fashion until
27 /// `reader` returns EOF or fails.
28 ///
29 /// On success, the total number of bytes that were copied from `reader` to
30 /// `writer` is returned.
31 ///
32 /// This is a [`tokio::io::copy`] alternative for [`AsyncBufRead`] readers
33 /// with no extra buffer allocation, since [`AsyncBufRead`] allow access
34 /// to the reader's inner buffer.
35 ///
36 /// # When to use async alternatives instead of `SyncIoBridge`
37 ///
38 /// If you are looking to use [`std::io::copy`] with a synchronous consumer
39 /// (like a `hasher` or compressor), consider using async alternatives instead of
40 /// wrapping the reader with [`SyncIoBridge`]. See the [`SyncIoBridge`]
41 /// documentation for detailed examples and guidance on hashing, compression,
42 /// and data parsing.
43 ///
44 /// [`tokio::io::copy`]: crate::io::copy
45 /// [`AsyncBufRead`]: crate::io::AsyncBufRead
46 /// [`SyncIoBridge`]: https://docs.rs/tokio-util/latest/tokio_util/io/struct.SyncIoBridge.html
47 ///
48 /// # Errors
49 ///
50 /// The returned future will finish with an error will return an error
51 /// immediately if any call to `poll_fill_buf` or `poll_write` returns an
52 /// error.
53 ///
54 /// # Examples
55 ///
56 /// ```
57 /// use tokio::io;
58 ///
59 /// # async fn dox() -> std::io::Result<()> {
60 /// let mut reader: &[u8] = b"hello";
61 /// let mut writer: Vec<u8> = vec![];
62 ///
63 /// io::copy_buf(&mut reader, &mut writer).await?;
64 ///
65 /// assert_eq!(b"hello", &writer[..]);
66 /// # Ok(())
67 /// # }
68 /// ```
69 pub async fn copy_buf<'a, R, W>(reader: &'a mut R, writer: &'a mut W) -> io::Result<u64>
70 where
71 R: AsyncBufRead + Unpin + ?Sized,
72 W: AsyncWrite + Unpin + ?Sized,
73 {
74 CopyBuf {
75 reader,
76 writer,
77 amt: 0,
78 }.await
79 }
80}
81
82impl<R, W> Future for CopyBuf<'_, R, W>
83where
84 R: AsyncBufRead + Unpin + ?Sized,
85 W: AsyncWrite + Unpin + ?Sized,
86{
87 type Output = io::Result<u64>;
88
89 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
90 loop {
91 let me = &mut *self;
92 let buffer = ready!(Pin::new(&mut *me.reader).poll_fill_buf(cx))?;
93 if buffer.is_empty() {
94 ready!(Pin::new(&mut self.writer).poll_flush(cx))?;
95 return Poll::Ready(Ok(self.amt));
96 }
97
98 let i = ready!(Pin::new(&mut *me.writer).poll_write(cx, buffer))?;
99 if i == 0 {
100 return Poll::Ready(Err(std::io::ErrorKind::WriteZero.into()));
101 }
102 self.amt += i as u64;
103 Pin::new(&mut *self.reader).consume(i);
104 }
105 }
106}
107
108#[cfg(test)]
109mod tests {
110 use super::*;
111
112 #[test]
113 fn assert_unpin() {
114 use std::marker::PhantomPinned;
115 crate::is_unpin::<CopyBuf<'_, PhantomPinned, PhantomPinned>>();
116 }
117}