diff options
| author | Kornel <kornel@geekhood.net> | 2023-10-09 14:32:15 +0100 |
|---|---|---|
| committer | Kornel <kornel@geekhood.net> | 2024-01-29 23:53:45 +0000 |
| commit | 60f46289cf55759dc474d796edbf9d38cbab86d4 (patch) | |
| tree | a6aced8f104d3de17231a85691f99d0a2a75bae7 | |
| parent | 03545161e68c1b8c3fe052243e372ee75e4ec513 (diff) | |
| download | rust-60f46289cf55759dc474d796edbf9d38cbab86d4.tar.gz rust-60f46289cf55759dc474d796edbf9d38cbab86d4.zip | |
Handle out of memory errors in fs::read/read_to_string
| -rw-r--r-- | library/std/src/fs.rs | 10 |
1 files changed, 6 insertions, 4 deletions
diff --git a/library/std/src/fs.rs b/library/std/src/fs.rs index c4a92927937..80d369eb067 100644 --- a/library/std/src/fs.rs +++ b/library/std/src/fs.rs @@ -260,7 +260,8 @@ pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> { fn inner(path: &Path) -> io::Result<Vec<u8>> { 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_exact(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?; io::default_read_to_end(&mut file, &mut bytes, size)?; Ok(bytes) } @@ -302,7 +303,8 @@ pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> { fn inner(path: &Path) -> io::Result<String> { 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_exact(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?; io::default_read_to_string(&mut file, &mut string, size)?; Ok(string) } @@ -774,14 +776,14 @@ impl Read for &File { // Reserves space in the buffer based on the file size when available. fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { let size = buffer_capacity_required(self); - buf.reserve(size.unwrap_or(0)); + buf.try_reserve_exact(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?; io::default_read_to_end(self, buf, size) } // Reserves space in the buffer based on the file size when available. fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> { let size = buffer_capacity_required(self); - buf.reserve(size.unwrap_or(0)); + buf.try_reserve_exact(size.unwrap_or(0)).map_err(|_| io::ErrorKind::OutOfMemory)?; io::default_read_to_string(self, buf, size) } } |
