feat(napi): allow provide size_hint in create_external

This commit is contained in:
LongYinan 2020-12-22 11:57:26 +08:00
parent c4d3876250
commit 1c4265496e
No known key found for this signature in database
GPG key ID: A3FFE134A3E20881
3 changed files with 15 additions and 3 deletions

View file

@ -677,7 +677,14 @@ impl Env {
} }
#[inline] #[inline]
pub fn create_external<T: 'static>(&self, native_object: T) -> Result<JsExternal> { /// 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<T: 'static>(
&self,
native_object: T,
size_hint: Option<i64>,
) -> Result<JsExternal> {
let mut object_value = ptr::null_mut(); let mut object_value = ptr::null_mut();
check_status!(unsafe { check_status!(unsafe {
sys::napi_create_external( sys::napi_create_external(
@ -688,6 +695,11 @@ impl Env {
&mut object_value, &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) }) Ok(unsafe { JsExternal::from_raw_unchecked(self.0, object_value) })
} }

View file

@ -7,7 +7,7 @@ fn add_cleanup_hook(mut env: Env) -> ContextlessResult<JsExternal> {
let hook = env.add_env_cleanup_hook((), |_| { let hook = env.add_env_cleanup_hook((), |_| {
println!("cleanup hook executed"); println!("cleanup hook executed");
})?; })?;
env.create_external(hook).map(Some) env.create_external(hook, None).map(Some)
} }
#[js_function(1)] #[js_function(1)]

View file

@ -10,7 +10,7 @@ struct NativeObject {
pub fn create_external(ctx: CallContext) -> Result<JsExternal> { pub fn create_external(ctx: CallContext) -> Result<JsExternal> {
let count = ctx.get::<JsNumber>(0)?.try_into()?; let count = ctx.get::<JsNumber>(0)?.try_into()?;
let native = NativeObject { count }; let native = NativeObject { count };
ctx.env.create_external(native) ctx.env.create_external(native, None)
} }
#[js_function(1)] #[js_function(1)]