From 1e2d37bf4a083fe5224bab6da3510846f5171864 Mon Sep 17 00:00:00 2001 From: Kornel Date: Mon, 9 Oct 2023 14:32:15 +0100 Subject: [PATCH] Handle out of memory errors in fs::read/read_to_string --- library/std/src/fs.rs | 6 ++++-- library/std/src/io/mod.rs | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/library/std/src/fs.rs b/library/std/src/fs.rs index 63bf6b0c1ab0..60df6f2ef344 100644 --- a/library/std/src/fs.rs +++ b/library/std/src/fs.rs @@ -254,7 +254,8 @@ pub fn read>(path: P) -> io::Result> { fn inner(path: &Path) -> io::Result> { let mut file = File::open(path)?; let size = file.metadata().map(|m| m.len() as usize).ok(); - let mut bytes = Vec::with_capacity(size.unwrap_or(0)); + let mut bytes = Vec::new(); + bytes.try_reserve(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?; io::default_read_to_end(&mut file, &mut bytes, size)?; Ok(bytes) } @@ -296,7 +297,8 @@ pub fn read_to_string>(path: P) -> io::Result { fn inner(path: &Path) -> io::Result { let mut file = File::open(path)?; let size = file.metadata().map(|m| m.len() as usize).ok(); - let mut string = String::with_capacity(size.unwrap_or(0)); + let mut string = String::new(); + string.try_reserve(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?; io::default_read_to_string(&mut file, &mut string, size)?; Ok(string) } diff --git a/library/std/src/io/mod.rs b/library/std/src/io/mod.rs index 94f2283d5d4f..c6a610cb04b1 100644 --- a/library/std/src/io/mod.rs +++ b/library/std/src/io/mod.rs @@ -430,7 +430,7 @@ pub(crate) fn default_read_to_end( loop { match r.read(&mut probe) { Ok(n) => { - buf.try_reserve(n).map_err(|_| io::ErrorKind::OutOfMemory)?; + buf.try_reserve(n).map_err(|_| ErrorKind::OutOfMemory)?; buf.extend_from_slice(&probe[..n]); return Ok(n); }