Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix for #1419.
Problem
Problem is that
Uint8Array::new
only records the length of theVec
it receives, and ignores the capacity.When it recreates the
Vec
later in order to drop it, it is created with capacity equal to the length:napi-rs/crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs
Lines 109 to 110 in 83e157e
So if original
Vec
had a larger capacity,capacity - length
bytes are leaked. The allocator is also called with a different layout from what the originalVec
was created with, which may cause unknown consequences.Solution
This PR just adds
data::shrink_to_fit()
before recording length of the Vec. This is the simplest solution, and sinceUint8Array::new
takes ownership of theVec
, I can't see much benefit of not freeing the excess capacity immediately.Potential complication
As far as I can see,
Vec::shrink_to_fit()
always reduces capacity to exactly length:https://github.com/rust-lang/rust/blob/8ea62f6c30c94778d9146ddc26c8520ed2b50a58/library/alloc/src/raw_vec.rs#L425-L440
However, Rust's docs say "It will drop down as close as possible to the length but the allocator may still inform the vector that there is space for a few more elements."
So can we rely on
shrink_to_fit()
always leavingcapacity == length
?If not, would need to record capacity in the
Uint8Array
, and then use that value when dropping (asBuffer
does).If you think this is a concern, please let me know and I'll amend this PR.