compio_io\util/
mod.rs

1//! IO related utilities functions for ease of use.
2use crate::{AsyncRead, AsyncWrite, AsyncWriteExt, IoResult};
3
4mod take;
5pub use take::Take;
6
7mod null;
8pub use null::{Null, null};
9
10mod repeat;
11pub use repeat::{Repeat, repeat};
12
13mod internal;
14pub(crate) use internal::*;
15
16pub mod split;
17pub use split::Splittable;
18
19/// Asynchronously copies the entire contents of a reader into a writer.
20///
21/// This function returns a future that will continuously read data from
22/// `reader` and then write it into `writer` in a streaming fashion until
23/// `reader` returns EOF or fails.
24///
25/// On success, the total number of bytes that were copied from `reader` to
26/// `writer` is returned.
27///
28/// This is an asynchronous version of [`std::io::copy`][std].
29///
30/// A heap-allocated copy buffer with 8 KiB is created to take data from the
31/// reader to the writer.
32pub async fn copy<R: AsyncRead, W: AsyncWrite>(reader: &mut R, writer: &mut W) -> IoResult<u64> {
33    let mut buf = Vec::with_capacity(DEFAULT_BUF_SIZE);
34    let mut total = 0u64;
35
36    loop {
37        let res;
38        (res, buf) = reader.read(buf).await.into();
39        match res {
40            Ok(0) => break,
41            Ok(read) => {
42                total += read as u64;
43            }
44            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {
45                continue;
46            }
47            Err(e) => return Err(e),
48        }
49        let res;
50        (res, buf) = writer.write_all(buf).await.into();
51        res?;
52        buf.clear();
53    }
54
55    Ok(total)
56}