Skip to content

Commit b5ed39f

Browse files
committed
Implement custom read_to_end for io::Take
1 parent 8c069ce commit b5ed39f

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

src/libstd/io/mod.rs

+16-3
Original file line numberDiff line numberDiff line change
@@ -354,19 +354,26 @@ fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
354354
// avoid paying to allocate and zero a huge chunk of memory if the reader only
355355
// has 4 bytes while still making large reads if the reader does have a ton
356356
// of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
357-
// time is 4,500 times (!) slower than this if the reader has a very small
358-
// amount of data to return.
357+
// time is 4,500 times (!) slower than a default reservation size of 32 if the
358+
// reader has a very small amount of data to return.
359359
//
360360
// Because we're extending the buffer with uninitialized data for trusted
361361
// readers, we need to make sure to truncate that if any of this panics.
362362
fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
363+
read_to_end_with_reservation(r, buf, 32)
364+
}
365+
366+
fn read_to_end_with_reservation<R: Read + ?Sized>(r: &mut R,
367+
buf: &mut Vec<u8>,
368+
reservation_size: usize) -> Result<usize>
369+
{
363370
let start_len = buf.len();
364371
let mut g = Guard { len: buf.len(), buf: buf };
365372
let ret;
366373
loop {
367374
if g.len == g.buf.len() {
368375
unsafe {
369-
g.buf.reserve(32);
376+
g.buf.reserve(reservation_size);
370377
let capacity = g.buf.capacity();
371378
g.buf.set_len(capacity);
372379
r.initializer().initialize(&mut g.buf[g.len..]);
@@ -1899,6 +1906,12 @@ impl<T: Read> Read for Take<T> {
18991906
unsafe fn initializer(&self) -> Initializer {
19001907
self.inner.initializer()
19011908
}
1909+
1910+
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
1911+
let reservation_size = cmp::min(self.limit, 32) as usize;
1912+
1913+
read_to_end_with_reservation(self, buf, reservation_size)
1914+
}
19021915
}
19031916

19041917
#[stable(feature = "rust1", since = "1.0.0")]

0 commit comments

Comments
 (0)