Skip to content

Commit 4bffb84

Browse files
authored
Rollup merge of rust-lang#143462 - Rudxain:read_to_string_usize, r=joboet
fix(lib-std-fs): handle `usize` overflow in `read*` I assume this is a non-breaking change, as there would be an OOM `panic` anyways. This patch ensures a fast-fail when there's not enough memory to load the file. This only changes behavior on platforms where `usize` is smaller than 64bits
2 parents 2d540a2 + ce1cd24 commit 4bffb84

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

std/src/fs.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ pub struct DirBuilder {
304304
pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
305305
fn inner(path: &Path) -> io::Result<Vec<u8>> {
306306
let mut file = File::open(path)?;
307-
let size = file.metadata().map(|m| m.len() as usize).ok();
307+
let size = file.metadata().map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).ok();
308308
let mut bytes = Vec::try_with_capacity(size.unwrap_or(0))?;
309309
io::default_read_to_end(&mut file, &mut bytes, size)?;
310310
Ok(bytes)
@@ -346,7 +346,7 @@ pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
346346
pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
347347
fn inner(path: &Path) -> io::Result<String> {
348348
let mut file = File::open(path)?;
349-
let size = file.metadata().map(|m| m.len() as usize).ok();
349+
let size = file.metadata().map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).ok();
350350
let mut string = String::new();
351351
string.try_reserve_exact(size.unwrap_or(0))?;
352352
io::default_read_to_string(&mut file, &mut string, size)?;

0 commit comments

Comments
 (0)