Skip to content

Commit

Permalink
read: use Vec::try_reserve_exact for large allocations (#632)
Browse files Browse the repository at this point in the history
  • Loading branch information
philipc committed Feb 13, 2024
1 parent 2669d72 commit 1c618a2
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
12 changes: 10 additions & 2 deletions src/read/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -835,7 +835,11 @@ impl<'data> CompressedData<'data> {
.try_into()
.ok()
.read_error("Uncompressed data size is too large.")?;
let mut decompressed = Vec::with_capacity(size);
let mut decompressed = Vec::new();
decompressed
.try_reserve_exact(size)
.ok()
.read_error("Uncompressed data allocation failed")?;
let mut decompress = flate2::Decompress::new(true);
decompress
.decompress_vec(
Expand All @@ -856,7 +860,11 @@ impl<'data> CompressedData<'data> {
.try_into()
.ok()
.read_error("Uncompressed data size is too large.")?;
let mut decompressed = Vec::with_capacity(size);
let mut decompressed = Vec::new();
decompressed
.try_reserve_exact(size)
.ok()
.read_error("Uncompressed data allocation failed")?;
let mut decoder = ruzstd::StreamingDecoder::new(self.data)
.ok()
.read_error("Invalid zstd compressed data")?;
Expand Down
5 changes: 4 additions & 1 deletion src/read/read_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,10 @@ impl<'a, R: Read + Seek> ReadRef<'a> for &'a ReadCache<R> {
Entry::Vacant(entry) => {
let size = size.try_into().map_err(|_| ())?;
cache.read.seek(SeekFrom::Start(offset)).map_err(|_| ())?;
let mut bytes = vec![0; size].into_boxed_slice();
let mut bytes = Vec::new();
bytes.try_reserve_exact(size).map_err(|_| ())?;
bytes.resize(size, 0);
let mut bytes = bytes.into_boxed_slice();
cache.read.read_exact(&mut bytes).map_err(|_| ())?;
entry.insert(bytes)
}
Expand Down

0 comments on commit 1c618a2

Please sign in to comment.