Skip to content

Commit 2606537

Browse files
Rollup merge of rust-lang#47520 - mbrubeck:fstat, r=Mark-Simulacrum
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.
2 parents 009bc2a + e9fdee8 commit 2606537

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

src/libstd/fs.rs

+9-7
Original file line numberDiff line numberDiff line change
@@ -211,12 +211,12 @@ pub struct DirBuilder {
211211
recursive: bool,
212212
}
213213

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

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

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

0 commit comments

Comments
 (0)