feat(napi): unwrap &'static value from Ref object

This commit is contained in:
LongYinan 2021-02-25 22:17:21 +08:00
parent c75967e911
commit e622d9693a
No known key found for this signature in database
GPG key ID: C3666B7FC82ADAD7
2 changed files with 31 additions and 1 deletions

View file

@ -673,6 +673,32 @@ impl Env {
}
}
#[inline]
pub fn unwrap_from_ref<T: 'static>(&self, js_ref: &Ref<()>) -> Result<&'static mut T> {
unsafe {
let mut unknown_tagged_object: *mut c_void = ptr::null_mut();
check_status!(sys::napi_unwrap(
self.0,
js_ref.raw_value,
&mut unknown_tagged_object,
))?;
let type_id = unknown_tagged_object as *const TypeId;
if *type_id == TypeId::of::<T>() {
let tagged_object = unknown_tagged_object as *mut TaggedObject<T>;
(*tagged_object).object.as_mut().ok_or(Error {
status: Status::InvalidArg,
reason: "Invalid argument, nothing attach to js_object".to_owned(),
})
} else {
Err(Error {
status: Status::InvalidArg,
reason: "Invalid argument, T on unrwap is not the type of wrapped object".to_owned(),
})
}
}
}
#[inline]
pub fn drop_wrapped<T: 'static>(&self, js_object: JsObject) -> Result<()> {
unsafe {
@ -706,13 +732,15 @@ impl Env {
{
let mut raw_ref = ptr::null_mut();
let initial_ref_count = 1;
let raw_value = unsafe { value.raw() };
check_status!(unsafe {
sys::napi_create_reference(self.0, value.raw(), initial_ref_count, &mut raw_ref)
sys::napi_create_reference(self.0, raw_value, initial_ref_count, &mut raw_ref)
})?;
Ok(Ref {
raw_ref,
count: 1,
inner: (),
raw_value,
})
}

View file

@ -8,6 +8,7 @@ pub struct Ref<T> {
pub(crate) raw_ref: sys::napi_ref,
pub(crate) count: u32,
pub(crate) inner: T,
pub(crate) raw_value: sys::napi_value,
}
unsafe impl<T> Send for Ref<T> {}
@ -30,6 +31,7 @@ impl<T> Ref<T> {
raw_ref,
count: ref_count,
inner,
raw_value: js_value.value,
})
}