Skip to content

Commit 1be2869

Browse files
committed
Reserve exact memory when File size is known
1 parent f8d9c3e commit 1be2869

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

library/std/src/fs.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
261261
let mut file = File::open(path)?;
262262
let size = file.metadata().map(|m| m.len() as usize).ok();
263263
let mut bytes = Vec::new();
264-
bytes.try_reserve(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
264+
bytes.try_reserve_exact(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
265265
io::default_read_to_end(&mut file, &mut bytes, size)?;
266266
Ok(bytes)
267267
}
@@ -304,7 +304,7 @@ pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
304304
let mut file = File::open(path)?;
305305
let size = file.metadata().map(|m| m.len() as usize).ok();
306306
let mut string = String::new();
307-
string.try_reserve(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
307+
string.try_reserve_exact(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
308308
io::default_read_to_string(&mut file, &mut string, size)?;
309309
Ok(string)
310310
}
@@ -776,14 +776,14 @@ impl Read for &File {
776776
// Reserves space in the buffer based on the file size when available.
777777
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
778778
let size = buffer_capacity_required(self);
779-
buf.try_reserve(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
779+
buf.try_reserve_exact(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
780780
io::default_read_to_end(self, buf, size)
781781
}
782782

783783
// Reserves space in the buffer based on the file size when available.
784784
fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
785785
let size = buffer_capacity_required(self);
786-
buf.try_reserve(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
786+
buf.try_reserve_exact(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
787787
io::default_read_to_string(self, buf, size)
788788
}
789789
}

0 commit comments

Comments
 (0)