Skip to content

Commit 0884daf

Browse files
committed
detect EOF earlier
The initial probe-for-empty-source by stack_buffer_copy only detected EOF if the source was empty but not when it was merely small which lead to additional calls to read() after Ok(0) had already been returned in the stack copy routine
1 parent 954ecf5 commit 0884daf

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

library/std/src/io/copy.rs

+8-5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use core::cmp::min;
12
use super::{BorrowedBuf, BufReader, BufWriter, Read, Result, Write, DEFAULT_BUF_SIZE};
23
use crate::alloc::Allocator;
34
use crate::cmp;
@@ -263,11 +264,13 @@ impl<A: Allocator> BufferedWriterSpec for Vec<u8, A> {
263264
fn copy_from<R: Read + ?Sized>(&mut self, reader: &mut R) -> Result<u64> {
264265
let mut bytes = 0;
265266

266-
// avoid allocating before we have determined that there's anything to read
267-
if self.capacity() == 0 {
268-
bytes = stack_buffer_copy(&mut reader.take(DEFAULT_BUF_SIZE as u64), self)?;
269-
if bytes == 0 {
270-
return Ok(0);
267+
// avoid inflating empty/small vecs before we have determined that there's anything to read
268+
if self.capacity() < DEFAULT_BUF_SIZE {
269+
let stack_read_limit = DEFAULT_BUF_SIZE as u64;
270+
bytes = stack_buffer_copy(&mut reader.take(stack_read_limit), self)?;
271+
// fewer bytes than requested -> EOF reached
272+
if bytes < stack_read_limit {
273+
return Ok(bytes);
271274
}
272275
}
273276

0 commit comments

Comments
 (0)