Skip to content

Commit 372e366

Browse files
pchickeycalvinrp
andcommitted
add read_to_end to AsyncRead
stole this bit out of Calvin's PR: cbaf050 Co-authored-by: Calvin Prewitt <[email protected]>
1 parent 84519fd commit 372e366

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/io/read.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,27 @@
11
use crate::io;
22

3+
const CHUNK_SIZE: usize = 2048;
4+
35
/// Read bytes from a source.
46
pub trait AsyncRead {
57
async fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
8+
async fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
9+
// total bytes written to buf
10+
let mut n = 0;
11+
12+
loop {
13+
// grow buf if empty
14+
if buf.len() == n {
15+
buf.resize(n + CHUNK_SIZE, 0u8);
16+
}
17+
18+
let len = self.read(&mut buf[n..]).await?;
19+
if len == 0 {
20+
buf.truncate(n);
21+
return Ok(n);
22+
}
23+
24+
n += len;
25+
}
26+
}
627
}

0 commit comments

Comments
 (0)