Skip to content

Commit 1745f43

Browse files
committed
Pre-allocate in fs::read and fs::read_string
1 parent f62f774 commit 1745f43

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/libstd/fs.rs

+12-4
Original file line numberDiff line numberDiff line change
@@ -246,8 +246,12 @@ pub struct DirBuilder {
246246
/// ```
247247
#[unstable(feature = "fs_read_write", issue = "46588")]
248248
pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
249-
let mut bytes = Vec::new();
250-
File::open(path)?.read_to_end(&mut bytes)?;
249+
// Allocate one extra byte so the buffer doesn't need to grow before the final `read` call at
250+
// the end of the file. Don't worry about `usize` overflow because this will fail anyway if
251+
// the file doesn't fit into memory.
252+
let mut bytes = Vec::with_capacity(metadata(&path)?.len() as usize + 1);
253+
254+
File::open(&path)?.read_to_end(&mut bytes)?;
251255
Ok(bytes)
252256
}
253257

@@ -287,8 +291,12 @@ pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
287291
/// ```
288292
#[unstable(feature = "fs_read_write", issue = "46588")]
289293
pub fn read_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
290-
let mut string = String::new();
291-
File::open(path)?.read_to_string(&mut string)?;
294+
// Allocate one extra byte so the buffer doesn't need to grow before the final `read` call at
295+
// the end of the file. Don't worry about `usize` overflow because this will fail anyway if
296+
// the file doesn't fit into memory.
297+
let mut string = String::with_capacity(metadata(&path)?.len() as usize + 1);
298+
299+
File::open(&path)?.read_to_string(&mut string)?;
292300
Ok(string)
293301
}
294302

0 commit comments

Comments
 (0)