From 1c4265496e550479f40defc45d876172a6e6a6df Mon Sep 17 00:00:00 2001 From: LongYinan Date: Tue, 22 Dec 2020 11:57:26 +0800 Subject: [PATCH] feat(napi): allow provide size_hint in create_external --- napi/src/env.rs | 14 +++++++++++++- test_module/src/cleanup_env.rs | 2 +- test_module/src/external.rs | 2 +- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/napi/src/env.rs b/napi/src/env.rs index ac5f8111..f8474620 100644 --- a/napi/src/env.rs +++ b/napi/src/env.rs @@ -677,7 +677,14 @@ impl Env { } #[inline] - pub fn create_external(&self, native_object: T) -> Result { + /// If `size_hint` provided, `Env::adjust_external_memory` will be called under the hood. + /// If no `size_hint` provided, global garbage collections will be triggered less times than expected. + /// If getting the exact `native_object` size is difficult, you can provide an approximate value, it's only effect to the GC. + pub fn create_external( + &self, + native_object: T, + size_hint: Option, + ) -> Result { let mut object_value = ptr::null_mut(); check_status!(unsafe { sys::napi_create_external( @@ -688,6 +695,11 @@ impl Env { &mut object_value, ) })?; + if let Some(size_hint) = size_hint { + check_status!(unsafe { + sys::napi_adjust_external_memory(self.0, size_hint, ptr::null_mut()) + })?; + }; Ok(unsafe { JsExternal::from_raw_unchecked(self.0, object_value) }) } diff --git a/test_module/src/cleanup_env.rs b/test_module/src/cleanup_env.rs index 13c17858..8d6df891 100644 --- a/test_module/src/cleanup_env.rs +++ b/test_module/src/cleanup_env.rs @@ -7,7 +7,7 @@ fn add_cleanup_hook(mut env: Env) -> ContextlessResult { let hook = env.add_env_cleanup_hook((), |_| { println!("cleanup hook executed"); })?; - env.create_external(hook).map(Some) + env.create_external(hook, None).map(Some) } #[js_function(1)] diff --git a/test_module/src/external.rs b/test_module/src/external.rs index b49df5f6..c401ac4d 100644 --- a/test_module/src/external.rs +++ b/test_module/src/external.rs @@ -10,7 +10,7 @@ struct NativeObject { pub fn create_external(ctx: CallContext) -> Result { let count = ctx.get::(0)?.try_into()?; let native = NativeObject { count }; - ctx.env.create_external(native) + ctx.env.create_external(native, None) } #[js_function(1)]