Skip to content

Make File's specialisation of read_to_end use the length of the file to size the Vec it gets passed #27159

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions src/libstd/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ use core::prelude::*;
use fmt;
use ffi::OsString;
use io::{self, SeekFrom, Seek, Read, Write};
use io::SeekFrom::Current;
use path::{Path, PathBuf};
use sys::fs as fs_imp;
use sys_common::{AsInnerMut, FromInner, AsInner};
use sys_common::io::read_to_end_uninitialized;
use sys_common::io::read_to_end_uninitialized_hint;
use cmp::min;
use vec::Vec;

/// A reference to an open file on the filesystem.
Expand Down Expand Up @@ -330,7 +332,19 @@ impl Read for File {
self.inner.read(buf)
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
unsafe { read_to_end_uninitialized(self, buf) }
let total_size = try!(self.metadata()).len();
let cur_pos = try!(self.seek(Current(0))) as u64;

// size isn't guaranteed to stay static, so we need to check
// we deal with the possibility that cur_pos > size!
let size =
if cur_pos > total_size {
0usize
} else {
min((total_size - cur_pos) as usize, usize::max_value())
};

unsafe { read_to_end_uninitialized_hint(self, buf, size) }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
7 changes: 6 additions & 1 deletion src/libstd/sys/common/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,14 @@ use slice::from_raw_parts_mut;
// * The implementation of read never reads the buffer provided.
// * The implementation of read correctly reports how many bytes were written.
pub unsafe fn read_to_end_uninitialized(r: &mut Read, buf: &mut Vec<u8>) -> io::Result<usize> {
read_to_end_uninitialized_hint(r, buf, 16)
}

pub unsafe fn read_to_end_uninitialized_hint(r: &mut Read, buf: &mut Vec<u8>, size_hint: usize)
-> io::Result<usize> {

let start_len = buf.len();
buf.reserve(16);
buf.reserve(size_hint);

// Always try to read into the empty space of the vector (from the length to the capacity).
// If the vector ever fills up then we reserve an extra byte which should trigger the normal
Expand Down