Skip to content

Commit

Permalink
Pre-allocate in Read::read_to_end and read_to_string based on size_hint
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonSapin committed Nov 28, 2017
1 parent 44c93ce commit 6adc9e6
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/libstd/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,17 @@ fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
let start_len = buf.len();
let mut g = Guard { len: buf.len(), buf: buf };

let size_hint = r.size_hint();
if size_hint > 0 {
unsafe {
g.buf.reserve(size_hint);
let capacity = g.buf.capacity();
g.buf.set_len(capacity);
r.initializer().initialize(&mut g.buf[g.len..]);
}
}

loop {
if g.len == g.buf.len() {
unsafe {
Expand Down

0 comments on commit 6adc9e6

Please sign in to comment.