Skip to content

Commit 6adc9e6

Browse files
committed
Pre-allocate in Read::read_to_end and read_to_string based on size_hint
1 parent 44c93ce commit 6adc9e6

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

src/libstd/io/mod.rs

+11
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,17 @@ fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
366366
fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
367367
let start_len = buf.len();
368368
let mut g = Guard { len: buf.len(), buf: buf };
369+
370+
let size_hint = r.size_hint();
371+
if size_hint > 0 {
372+
unsafe {
373+
g.buf.reserve(size_hint);
374+
let capacity = g.buf.capacity();
375+
g.buf.set_len(capacity);
376+
r.initializer().initialize(&mut g.buf[g.len..]);
377+
}
378+
}
379+
369380
loop {
370381
if g.len == g.buf.len() {
371382
unsafe {

0 commit comments

Comments
 (0)