Skip to content

Commit 60f4628

Browse files
committed
Handle out of memory errors in fs::read/read_to_string
1 parent 0354516 commit 60f4628

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

library/std/src/fs.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,8 @@ pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
260260
fn inner(path: &Path) -> io::Result<Vec<u8>> {
261261
let mut file = File::open(path)?;
262262
let size = file.metadata().map(|m| m.len() as usize).ok();
263-
let mut bytes = Vec::with_capacity(size.unwrap_or(0));
263+
let mut bytes = Vec::new();
264+
bytes.try_reserve_exact(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
264265
io::default_read_to_end(&mut file, &mut bytes, size)?;
265266
Ok(bytes)
266267
}
@@ -302,7 +303,8 @@ pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
302303
fn inner(path: &Path) -> io::Result<String> {
303304
let mut file = File::open(path)?;
304305
let size = file.metadata().map(|m| m.len() as usize).ok();
305-
let mut string = String::with_capacity(size.unwrap_or(0));
306+
let mut string = String::new();
307+
string.try_reserve_exact(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
306308
io::default_read_to_string(&mut file, &mut string, size)?;
307309
Ok(string)
308310
}
@@ -774,14 +776,14 @@ impl Read for &File {
774776
// Reserves space in the buffer based on the file size when available.
775777
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
776778
let size = buffer_capacity_required(self);
777-
buf.reserve(size.unwrap_or(0));
779+
buf.try_reserve_exact(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
778780
io::default_read_to_end(self, buf, size)
779781
}
780782

781783
// Reserves space in the buffer based on the file size when available.
782784
fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
783785
let size = buffer_capacity_required(self);
784-
buf.reserve(size.unwrap_or(0));
786+
buf.try_reserve_exact(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
785787
io::default_read_to_string(self, buf, size)
786788
}
787789
}

0 commit comments

Comments
 (0)