compio_io/util/
mod.rs

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