Skip to content

Commit

Permalink
feat(napi): unwrap &'static value from Ref object
Browse files Browse the repository at this point in the history
  • Loading branch information
Brooooooklyn committed Feb 25, 2021
1 parent c75967e commit e622d96
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
30 changes: 29 additions & 1 deletion napi/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
})
}

Expand Down
2 changes: 2 additions & 0 deletions napi/src/js_values/value_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {}
Expand All @@ -30,6 +31,7 @@ impl<T> Ref<T> {
raw_ref,
count: ref_count,
inner,
raw_value: js_value.value,
})
}

Expand Down

0 comments on commit e622d96

Please sign in to comment.