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