From 50f207f744c16d305984be1d172174034e78bca9 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 11 Mar 2021 19:02:42 +0800 Subject: [PATCH] fix(napi): InvalidArg error when create_external with size hint --- README.md | 4 ++-- napi/src/env.rs | 5 ++++- test_module/__test__/create-external.spec.ts | 6 ++++++ test_module/src/external.rs | 8 ++++++++ 4 files changed, 20 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b8b76ae1..a2c3aab2 100644 --- a/README.md +++ b/README.md @@ -31,8 +31,8 @@ A minimal library for building compiled `NodeJS` add-ons in `Rust`. ## NodeJS | Node10 | Node12 | Node14 | Node15 | -| ------ | ------- | ------ | ------ | -| ✓ | ✓ | ✓ | ✓ | +| ------ | ------ | ------ | ------ | +| ✓ | ✓ | ✓ | ✓ | This library depends on N-API and requires `Node@10.0.0` or later. diff --git a/napi/src/env.rs b/napi/src/env.rs index ecc3713a..e39fff6f 100644 --- a/napi/src/env.rs +++ b/napi/src/env.rs @@ -798,7 +798,10 @@ impl Env { ) })?; if let Some(changed) = size_hint { - check_status!(unsafe { sys::napi_adjust_external_memory(self.0, changed, ptr::null_mut()) })?; + let mut adjusted_value = 0i64; + check_status!(unsafe { + sys::napi_adjust_external_memory(self.0, changed, &mut adjusted_value) + })?; }; Ok(unsafe { JsExternal::from_raw_unchecked(self.0, object_value) }) } diff --git a/test_module/__test__/create-external.spec.ts b/test_module/__test__/create-external.spec.ts index 1e2cc19f..a55c629f 100644 --- a/test_module/__test__/create-external.spec.ts +++ b/test_module/__test__/create-external.spec.ts @@ -7,3 +7,9 @@ test('should create external object and get it back', (t) => { const externalObject = bindings.createExternal(42) t.is(bindings.getExternalCount(externalObject), fixture) }) + +test('should create external with size hint', (t) => { + const fixture = 42 + const externalObject = bindings.createExternalWithHint(42) + t.is(bindings.getExternalCount(externalObject), fixture) +}) diff --git a/test_module/src/external.rs b/test_module/src/external.rs index c401ac4d..b31c698e 100644 --- a/test_module/src/external.rs +++ b/test_module/src/external.rs @@ -13,6 +13,13 @@ pub fn create_external(ctx: CallContext) -> Result { ctx.env.create_external(native, None) } +#[js_function(1)] +pub fn create_external_with_hint(ctx: CallContext) -> Result { + let count = ctx.get::(0)?.try_into()?; + let native = NativeObject { count }; + ctx.env.create_external(native, Some(5)) +} + #[js_function(1)] pub fn get_external_count(ctx: CallContext) -> Result { let attached_obj = ctx.get::(0)?; @@ -22,6 +29,7 @@ pub fn get_external_count(ctx: CallContext) -> Result { pub fn register_js(exports: &mut JsObject) -> Result<()> { exports.create_named_method("createExternal", create_external)?; + exports.create_named_method("createExternalWithHint", create_external_with_hint)?; exports.create_named_method("getExternalCount", get_external_count)?; Ok(()) }