File tree Expand file tree Collapse file tree 1 file changed +12
-4
lines changed Expand file tree Collapse file tree 1 file changed +12
-4
lines changed Original file line number Diff line number Diff line change @@ -246,8 +246,12 @@ pub struct DirBuilder {
246246/// ```
247247#[ unstable( feature = "fs_read_write" , issue = "46588" ) ]
248248pub 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" ) ]
289293pub 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
You can’t perform that action at this time.
0 commit comments