Skip to content

Commit

Permalink
Rollup merge of rust-lang#47520 - mbrubeck:fstat, r=Mark-Simulacrum
Browse files Browse the repository at this point in the history
Use File::metadata instead of fs::metadata to choose buffer size

This replaces a `stat` syscall with `fstat` or similar, which can be faster.  Fixes rust-lang#47519.
  • Loading branch information
GuillaumeGomez authored Jan 17, 2018
2 parents 009bc2a + e9fdee8 commit 2606537
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/libstd/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,12 +211,12 @@ pub struct DirBuilder {
recursive: bool,
}

/// How large a buffer to pre-allocate before reading the entire file at `path`.
fn initial_buffer_size<P: AsRef<Path>>(path: P) -> usize {
/// How large a buffer to pre-allocate before reading the entire file.
fn initial_buffer_size(file: &File) -> usize {
// Allocate one extra byte so the buffer doesn't need to grow before the
// final `read` call at the end of the file. Don't worry about `usize`
// overflow because reading will fail regardless in that case.
metadata(path).map(|m| m.len() as usize + 1).unwrap_or(0)
file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
}

/// Read the entire contents of a file into a bytes vector.
Expand Down Expand Up @@ -254,8 +254,9 @@ fn initial_buffer_size<P: AsRef<Path>>(path: P) -> usize {
/// ```
#[unstable(feature = "fs_read_write", issue = "46588")]
pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
let mut bytes = Vec::with_capacity(initial_buffer_size(&path));
File::open(path)?.read_to_end(&mut bytes)?;
let mut file = File::open(path)?;
let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
file.read_to_end(&mut bytes)?;
Ok(bytes)
}

Expand Down Expand Up @@ -295,8 +296,9 @@ pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
/// ```
#[unstable(feature = "fs_read_write", issue = "46588")]
pub fn read_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
let mut string = String::with_capacity(initial_buffer_size(&path));
File::open(path)?.read_to_string(&mut string)?;
let mut file = File::open(path)?;
let mut string = String::with_capacity(initial_buffer_size(&file));
file.read_to_string(&mut string)?;
Ok(string)
}

Expand Down

0 comments on commit 2606537

Please sign in to comment.