diff options
| author | Stuart Cook <Zalathar@users.noreply.github.com> | 2025-08-30 20:29:05 +1000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-08-30 20:29:05 +1000 |
| commit | 6421031e5765cf9bae01edb5f0d6c1d2cc25a927 (patch) | |
| tree | 23a8fc12b0f11b4d7c501d314a451fe1a286d98b /library/std/src/fs.rs | |
| parent | b53c72ffaaf10e17fef5deb063f2f3f3bc13c171 (diff) | |
| parent | a3208108b0b2b98004dac023aaeb794c1ec9149a (diff) | |
| download | rust-6421031e5765cf9bae01edb5f0d6c1d2cc25a927.tar.gz rust-6421031e5765cf9bae01edb5f0d6c1d2cc25a927.zip | |
Rollup merge of #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
Diffstat (limited to 'library/std/src/fs.rs')
| -rw-r--r-- | library/std/src/fs.rs | 4 |
1 files changed, 2 insertions, 2 deletions
diff --git a/library/std/src/fs.rs b/library/std/src/fs.rs index d9c9606fc1c..73d70681df1 100644 --- a/library/std/src/fs.rs +++ b/library/std/src/fs.rs @@ -304,7 +304,7 @@ pub struct DirBuilder { 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 size = file.metadata().map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).ok(); let mut bytes = Vec::try_with_capacity(size.unwrap_or(0))?; io::default_read_to_end(&mut file, &mut bytes, size)?; Ok(bytes) @@ -346,7 +346,7 @@ pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> { 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 size = file.metadata().map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).ok(); let mut string = String::new(); string.try_reserve_exact(size.unwrap_or(0))?; io::default_read_to_string(&mut file, &mut string, size)?; |
