fix(napi): support for env cleanup hooks (#17324)

This commit adds support for "napi_add_env_cleanup_hook" and
"napi_remove_env_cleanup_hook" function for Node-API.
This commit is contained in:
Bartek Iwańczuk 2023-01-10 19:15:10 +01:00 committed by GitHub
parent 71ea4ef274
commit 14ada3dce2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 143 additions and 18 deletions

View file

@ -52,24 +52,49 @@ fn napi_fatal_exception(env: *mut Env, value: napi_value) -> Result {
);
}
// TODO: properly implement
#[napi_sym::napi_sym]
fn napi_add_env_cleanup_hook(
_env: *mut Env,
_hook: extern "C" fn(*const c_void),
_data: *const c_void,
env: *mut Env,
hook: extern "C" fn(*const c_void),
data: *const c_void,
) -> Result {
log::info!("napi_add_env_cleanup_hook is currently not supported");
let env: &mut Env = env.as_mut().ok_or(Error::InvalidArg)?;
{
let mut env_cleanup_hooks = env.cleanup_hooks.borrow_mut();
if env_cleanup_hooks
.iter()
.any(|pair| pair.0 == hook && pair.1 == data)
{
panic!("Cleanup hook with this data already registered");
}
env_cleanup_hooks.push((hook, data));
}
Ok(())
}
#[napi_sym::napi_sym]
fn napi_remove_env_cleanup_hook(
_env: *mut Env,
_hook: extern "C" fn(*const c_void),
_data: *const c_void,
env: *mut Env,
hook: extern "C" fn(*const c_void),
data: *const c_void,
) -> Result {
log::info!("napi_remove_env_cleanup_hook is currently not supported");
let env: &mut Env = env.as_mut().ok_or(Error::InvalidArg)?;
{
let mut env_cleanup_hooks = env.cleanup_hooks.borrow_mut();
// Hooks are supposed to be removed in LIFO order
let maybe_index = env_cleanup_hooks
.iter()
.rposition(|&pair| pair.0 == hook && pair.1 == data);
if let Some(index) = maybe_index {
env_cleanup_hooks.remove(index);
} else {
panic!("Cleanup hook with this data not found");
}
}
Ok(())
}