fix(napi): InvalidArg error when create_external with size hint

This commit is contained in:
LongYinan 2021-03-11 19:02:42 +08:00
parent 66663d129d
commit 50f207f744
No known key found for this signature in database
GPG key ID: C3666B7FC82ADAD7
4 changed files with 20 additions and 3 deletions

View file

@ -31,8 +31,8 @@ A minimal library for building compiled `NodeJS` add-ons in `Rust`.
## NodeJS ## NodeJS
| Node10 | Node12 | Node14 | Node15 | | Node10 | Node12 | Node14 | Node15 |
| ------ | ------- | ------ | ------ | | ------ | ------ | ------ | ------ |
| ✓ | ✓ | ✓ | ✓ | | ✓ | ✓ | ✓ | ✓ |
This library depends on N-API and requires `Node@10.0.0` or later. This library depends on N-API and requires `Node@10.0.0` or later.

View file

@ -798,7 +798,10 @@ impl Env {
) )
})?; })?;
if let Some(changed) = size_hint { 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) }) Ok(unsafe { JsExternal::from_raw_unchecked(self.0, object_value) })
} }

View file

@ -7,3 +7,9 @@ test('should create external object and get it back', (t) => {
const externalObject = bindings.createExternal(42) const externalObject = bindings.createExternal(42)
t.is(bindings.getExternalCount(externalObject), fixture) 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)
})

View file

@ -13,6 +13,13 @@ pub fn create_external(ctx: CallContext) -> Result<JsExternal> {
ctx.env.create_external(native, None) ctx.env.create_external(native, None)
} }
#[js_function(1)]
pub fn create_external_with_hint(ctx: CallContext) -> Result<JsExternal> {
let count = ctx.get::<JsNumber>(0)?.try_into()?;
let native = NativeObject { count };
ctx.env.create_external(native, Some(5))
}
#[js_function(1)] #[js_function(1)]
pub fn get_external_count(ctx: CallContext) -> Result<JsNumber> { pub fn get_external_count(ctx: CallContext) -> Result<JsNumber> {
let attached_obj = ctx.get::<JsExternal>(0)?; let attached_obj = ctx.get::<JsExternal>(0)?;
@ -22,6 +29,7 @@ pub fn get_external_count(ctx: CallContext) -> Result<JsNumber> {
pub fn register_js(exports: &mut JsObject) -> Result<()> { pub fn register_js(exports: &mut JsObject) -> Result<()> {
exports.create_named_method("createExternal", create_external)?; exports.create_named_method("createExternal", create_external)?;
exports.create_named_method("createExternalWithHint", create_external_with_hint)?;
exports.create_named_method("getExternalCount", get_external_count)?; exports.create_named_method("getExternalCount", get_external_count)?;
Ok(()) Ok(())
} }