Skip to content

Commit

Permalink
detect EOF earlier
Browse files Browse the repository at this point in the history
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
  • Loading branch information
the8472 committed Nov 4, 2023
1 parent 954ecf5 commit 0884daf
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions library/std/src/io/copy.rs
@@ -1,3 +1,4 @@
use core::cmp::min;
use super::{BorrowedBuf, BufReader, BufWriter, Read, Result, Write, DEFAULT_BUF_SIZE};
use crate::alloc::Allocator;
use crate::cmp;
Expand Down Expand Up @@ -263,11 +264,13 @@ impl<A: Allocator> BufferedWriterSpec for Vec<u8, A> {
fn copy_from<R: Read + ?Sized>(&mut self, reader: &mut R) -> Result<u64> {
let mut bytes = 0;

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

Expand Down

0 comments on commit 0884daf

Please sign in to comment.