about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorkennytm <kennytm@gmail.com>2018-01-13 02:26:35 +0800
committerGitHub <noreply@github.com>2018-01-13 02:26:35 +0800
commit52770e69ac9521081f950ef553cd6e48b3b87079 (patch)
tree4ad47be875bd08681ebf29f02368c7aee59059fe /src/libstd
parent426036b517c8afd71d6ee6dcb1e4d942f2e2d437 (diff)
parent44912bf77bf1fd2137e5b7d1d31b2e59e2819136 (diff)
downloadrust-52770e69ac9521081f950ef553cd6e48b3b87079.tar.gz
rust-52770e69ac9521081f950ef553cd6e48b3b87079.zip
Rollup merge of #47324 - mbrubeck:len, r=sfackler
Pre-allocate in fs::read and fs::read_string

This is a simpler alternative to #46340 and #45928, as requested by the libs team.
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/fs.rs12
1 files changed, 10 insertions, 2 deletions
diff --git a/src/libstd/fs.rs b/src/libstd/fs.rs
index f40aed2478a..51cb9609120 100644
--- a/src/libstd/fs.rs
+++ b/src/libstd/fs.rs
@@ -211,6 +211,14 @@ 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 {
+    // 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)
+}
+
 /// Read the entire contents of a file into a bytes vector.
 ///
 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
@@ -246,7 +254,7 @@ pub struct DirBuilder {
 /// ```
 #[unstable(feature = "fs_read_write", issue = "46588")]
 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
-    let mut bytes = Vec::new();
+    let mut bytes = Vec::with_capacity(initial_buffer_size(&path));
     File::open(path)?.read_to_end(&mut bytes)?;
     Ok(bytes)
 }
@@ -287,7 +295,7 @@ 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::new();
+    let mut string = String::with_capacity(initial_buffer_size(&path));
     File::open(path)?.read_to_string(&mut string)?;
     Ok(string)
 }