Copy bytes from a reader to a writer.
(mut reader: R, mut writer: W)
| 2 | |
| 3 | /// Copy bytes from a reader to a writer. |
| 4 | pub async fn copy<R, W>(mut reader: R, mut writer: W) -> crate::io::Result<()> |
| 5 | where |
| 6 | R: AsyncRead, |
| 7 | W: AsyncWrite, |
| 8 | { |
| 9 | // Optimized path when we have an `AsyncInputStream` and an |
| 10 | // `AsyncOutputStream`. |
| 11 | if let Some(reader) = reader.as_async_input_stream() |
| 12 | && let Some(writer) = writer.as_async_output_stream() |
| 13 | { |
| 14 | reader.copy_to(writer).await?; |
| 15 | return Ok(()); |
| 16 | } |
| 17 | |
| 18 | // Unoptimized case: read the input and then write it. |
| 19 | let mut buf = [0; 1024]; |
| 20 | 'read: loop { |
| 21 | let bytes_read = reader.read(&mut buf).await?; |
| 22 | if bytes_read == 0 { |
| 23 | break 'read Ok(()); |
| 24 | } |
| 25 | writer.write_all(&buf[0..bytes_read]).await?; |
| 26 | } |
| 27 | } |
no test coverage detected