Skip to content

Commit 1e2d37b

Browse files
committed
Handle out of memory errors in fs::read/read_to_string
1 parent 561e5b8 commit 1e2d37b

File tree

2 files changed

+5
-3
lines changed

2 files changed

+5
-3
lines changed

Diff for: library/std/src/fs.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,8 @@ pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
254254
fn inner(path: &Path) -> io::Result<Vec<u8>> {
255255
let mut file = File::open(path)?;
256256
let size = file.metadata().map(|m| m.len() as usize).ok();
257-
let mut bytes = Vec::with_capacity(size.unwrap_or(0));
257+
let mut bytes = Vec::new();
258+
bytes.try_reserve(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
258259
io::default_read_to_end(&mut file, &mut bytes, size)?;
259260
Ok(bytes)
260261
}
@@ -296,7 +297,8 @@ pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
296297
fn inner(path: &Path) -> io::Result<String> {
297298
let mut file = File::open(path)?;
298299
let size = file.metadata().map(|m| m.len() as usize).ok();
299-
let mut string = String::with_capacity(size.unwrap_or(0));
300+
let mut string = String::new();
301+
string.try_reserve(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?;
300302
io::default_read_to_string(&mut file, &mut string, size)?;
301303
Ok(string)
302304
}

Diff for: library/std/src/io/mod.rs

+1-1
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)