Merge pull request #1274 from napi-rs/weak-reference

feat(napi): add get and get_mut method on `WeakReference`
This commit is contained in:
LongYinan 2022-08-17 22:12:02 +08:00 committed by GitHub
commit c4eb51b509
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 2 deletions

View file

@ -147,8 +147,8 @@ impl NapiFn {
if let Some(p) = path.path.segments.first() {
if p.ident == *self.parent.as_ref().unwrap() {
args.push(
quote! { napi::bindgen_prelude::Reference::from_value_ptr(this_ptr as *mut std::ffi::c_void, env)? },
);
quote! { napi::bindgen_prelude::Reference::from_value_ptr(this_ptr as *mut std::ffi::c_void, env)? },
);
skipped_arg_count += 1;
continue;
}

View file

@ -180,6 +180,15 @@ impl<T> Clone for WeakReference<T> {
impl<T: 'static> ToNapiValue for WeakReference<T> {
unsafe fn to_napi_value(env: crate::sys::napi_env, val: Self) -> Result<crate::sys::napi_value> {
if Weak::strong_count(&val.finalize_callbacks) == 0 {
return Err(Error::new(
Status::GenericFailure,
format!(
"The original reference that WeakReference<{}> is pointing to is dropped",
std::any::type_name::<T>()
),
));
};
let mut result = std::ptr::null_mut();
check_status!(
unsafe { crate::sys::napi_get_reference_value(env, val.napi_ref, &mut result) },
@ -207,6 +216,22 @@ impl<T: 'static> WeakReference<T> {
Ok(None)
}
}
pub fn get(&self) -> Option<&T> {
if Weak::strong_count(&self.finalize_callbacks) == 0 {
None
} else {
Some(unsafe { Box::leak(Box::from_raw(self.raw)) })
}
}
pub fn get_mut(&mut self) -> Option<&mut T> {
if Weak::strong_count(&self.finalize_callbacks) == 0 {
None
} else {
Some(unsafe { Box::leak(Box::from_raw(self.raw)) })
}
}
}
/// ### Experimental feature