From ce2a29fca7434dfc60258532e826043ce93cc146 Mon Sep 17 00:00:00 2001 From: overlookmotel Date: Mon, 9 Jan 2023 06:47:36 +0000 Subject: [PATCH] fix(napi): arraybuffer memory leak (#1420) --- crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs | 1 + memory-testing/buffer.mjs | 1 + memory-testing/src/lib.rs | 7 +++++++ 3 files changed, 9 insertions(+) diff --git a/crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs b/crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs index c7363b4c..086e585b 100644 --- a/crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs +++ b/crates/napi/src/bindgen_runtime/js_values/arraybuffer.rs @@ -125,6 +125,7 @@ macro_rules! impl_typed_array { fn noop_finalize(_data: *mut $rust_type, _length: usize) {} pub fn new(mut data: Vec<$rust_type>) -> Self { + data.shrink_to_fit(); let ret = $name { data: data.as_mut_ptr(), length: data.len(), diff --git a/memory-testing/buffer.mjs b/memory-testing/buffer.mjs index 24f257f8..a2c37688 100644 --- a/memory-testing/buffer.mjs +++ b/memory-testing/buffer.mjs @@ -17,6 +17,7 @@ while (true) { api.arrayBufferLen() api.bufferConvert(Buffer.from(FIXTURE)) api.arrayBufferConvert(Uint8Array.from(FIXTURE)) + api.arrayBufferCreateFromVecWithSpareCapacity() api.bufferPassThrough(Buffer.from(FIXTURE)) api.arrayBufferPassThrough(Uint8Array.from(FIXTURE)) if (i % 10 === 0) { diff --git a/memory-testing/src/lib.rs b/memory-testing/src/lib.rs index 85c87ef2..ce61119a 100644 --- a/memory-testing/src/lib.rs +++ b/memory-testing/src/lib.rs @@ -157,6 +157,13 @@ pub fn array_buffer_convert(array_buffer: Uint8Array) -> Uint8Array { Uint8Array::new(vec![1; array_buffer.len()]) } +#[napi] +pub fn array_buffer_create_from_vec_with_spare_capacity() -> Uint8Array { + let mut v = vec![1; 1024 * 10240]; + v.truncate(1); + Uint8Array::new(v) +} + #[napi] pub fn array_buffer_len() -> u32 { Uint8Array::new(vec![1; 1024 * 10240]).len() as u32