Skip to content

Commit 6218f5e

Browse files
committed
Handle out of memory errors in fs::read/read_to_string
1 parent 96f0ee6 commit 6218f5e

File tree

2 files changed

+5
-3
lines changed

2 files changed

+5
-3
lines changed

library/std/src/fs.rs

Lines changed: 4 additions & 2 deletions
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(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(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
306308
io::default_read_to_string(&mut file, &mut string, size)?;
307309
Ok(string)
308310
}

library/std/src/io/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ pub(crate) fn default_read_to_end<R: Read + ?Sized>(
430430
loop {
431431
match r.read(&mut probe) {
432432
Ok(n) => {
433-
buf.try_reserve(n).map_err(|_| io::ErrorKind::OutOfMemory)?;
433+
buf.try_reserve(n).map_err(|_| ErrorKind::OutOfMemory)?;
434434
buf.extend_from_slice(&probe[..n]);
435435
return Ok(n);
436436
}

0 commit comments

Comments
 (0)