File tree 1 file changed +12
-4
lines changed
1 file changed +12
-4
lines changed Original file line number Diff line number Diff line change @@ -246,8 +246,12 @@ pub struct DirBuilder {
246
246
/// ```
247
247
#[ unstable( feature = "fs_read_write" , issue = "46588" ) ]
248
248
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) ?;
251
255
Ok ( bytes)
252
256
}
253
257
@@ -287,8 +291,12 @@ pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
287
291
/// ```
288
292
#[ unstable( feature = "fs_read_write" , issue = "46588" ) ]
289
293
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) ?;
292
300
Ok ( string)
293
301
}
294
302
You can’t perform that action at this time.
0 commit comments