Skip to content

Commit abd747c

Browse files
committed
Rollup merge of rust-lang#23847 - bcoopers:read_clarification, r=sfackler
This introduces no functional changes except for reducing a few unnecessary operations and variables. Vec has the behavior that, if you request space past the capacity with reserve(), it will round up to the nearest power of 2. What that effectively means is that after the first call to reserve(16), we are doubling our capacity every time. So using the DEFAULT_BUF_SIZE and doubling cap_size() here is meaningless and has no effect on the call to reserve(). Note that with rust-lang#23842 implemented this will hopefully have a clearer API and less of a need for commenting. If rust-lang#23842 is not implemented then the most clear implementation would be to call reserve_exact(buf.capacity()) at every step (and making sure that buf.capacity() is not zero at the beginning of the function of course). Edit- functional change now introduced. We will now zero 16 bytes of the vector first, then double to 32, then 64, etc. until we read 64kB. This stops us from zeroing the entire vector when we double it, some of which may be wasted work. Reallocation still follows the doubling strategy, but the responsibility has been moved to vec.extend(), which calls reserve() and push_back().
2 parents 1d17e6e + 240734c commit abd747c

File tree

1 file changed

+4
-8
lines changed

1 file changed

+4
-8
lines changed

src/libstd/io/mod.rs

+4-8
Original file line numberDiff line numberDiff line change
@@ -101,18 +101,14 @@ fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
101101
fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
102102
let start_len = buf.len();
103103
let mut len = start_len;
104-
let mut cap_bump = 16;
104+
let mut new_write_size = 16;
105105
let ret;
106106
loop {
107107
if len == buf.len() {
108-
if buf.capacity() == buf.len() {
109-
if cap_bump < DEFAULT_BUF_SIZE {
110-
cap_bump *= 2;
111-
}
112-
buf.reserve(cap_bump);
108+
if new_write_size < DEFAULT_BUF_SIZE {
109+
new_write_size *= 2;
113110
}
114-
let new_area = buf.capacity() - buf.len();
115-
buf.extend(iter::repeat(0).take(new_area));
111+
buf.extend(iter::repeat(0).take(new_write_size));
116112
}
117113

118114
match r.read(&mut buf[len..]) {

0 commit comments

Comments
 (0)