From e622d9693a1e7f230eb74bc50c00355ef7feb7b3 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 25 Feb 2021 22:17:21 +0800 Subject: [PATCH] feat(napi): unwrap &'static value from Ref object --- napi/src/env.rs | 30 +++++++++++++++++++++++++++++- napi/src/js_values/value_ref.rs | 2 ++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/napi/src/env.rs b/napi/src/env.rs index e5894997..ecc3713a 100644 --- a/napi/src/env.rs +++ b/napi/src/env.rs @@ -673,6 +673,32 @@ impl Env { } } + #[inline] + pub fn unwrap_from_ref(&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::() { + let tagged_object = unknown_tagged_object as *mut TaggedObject; + (*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(&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, }) } diff --git a/napi/src/js_values/value_ref.rs b/napi/src/js_values/value_ref.rs index 908eaa43..1e22c090 100644 --- a/napi/src/js_values/value_ref.rs +++ b/napi/src/js_values/value_ref.rs @@ -8,6 +8,7 @@ pub struct Ref { pub(crate) raw_ref: sys::napi_ref, pub(crate) count: u32, pub(crate) inner: T, + pub(crate) raw_value: sys::napi_value, } unsafe impl Send for Ref {} @@ -30,6 +31,7 @@ impl Ref { raw_ref, count: ref_count, inner, + raw_value: js_value.value, }) }