Merge pull request #1274 from napi-rs/weak-reference
feat(napi): add get and get_mut method on `WeakReference`
This commit is contained in:
commit
c4eb51b509
2 changed files with 27 additions and 2 deletions
|
@ -147,8 +147,8 @@ impl NapiFn {
|
||||||
if let Some(p) = path.path.segments.first() {
|
if let Some(p) = path.path.segments.first() {
|
||||||
if p.ident == *self.parent.as_ref().unwrap() {
|
if p.ident == *self.parent.as_ref().unwrap() {
|
||||||
args.push(
|
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;
|
skipped_arg_count += 1;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
|
@ -180,6 +180,15 @@ impl<T> Clone for WeakReference<T> {
|
||||||
|
|
||||||
impl<T: 'static> ToNapiValue 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> {
|
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();
|
let mut result = std::ptr::null_mut();
|
||||||
check_status!(
|
check_status!(
|
||||||
unsafe { crate::sys::napi_get_reference_value(env, val.napi_ref, &mut result) },
|
unsafe { crate::sys::napi_get_reference_value(env, val.napi_ref, &mut result) },
|
||||||
|
@ -207,6 +216,22 @@ impl<T: 'static> WeakReference<T> {
|
||||||
Ok(None)
|
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
|
/// ### Experimental feature
|
||||||
|
|
Loading…
Reference in a new issue