nodex_api/
reference.rs

1use crate::{api, prelude::*};
2
3#[derive(Clone, Debug)]
4pub struct NapiRef(NapiEnv, napi_ref);
5
6impl NapiRef {
7    pub(crate) fn from_raw(env: NapiEnv, reference: napi_ref) -> NapiRef {
8        NapiRef(env, reference)
9    }
10
11    /// This API creates a new reference with the specified reference count to the Object passed
12    /// in.
13    pub fn new<T: NapiValueT>(value: T, count: u32) -> NapiResult<NapiRef> {
14        let reference = napi_call!(
15            =napi_create_reference,
16            value.env(),
17            value.raw(),
18            count,
19        );
20
21        Ok(NapiRef(value.env(), reference))
22    }
23
24    /// This API increments the reference count for the reference passed in and returns the
25    /// resulting reference count.
26    pub fn inc(&mut self) -> NapiResult<u32> {
27        Ok(napi_call!(=napi_reference_ref, self.0, self.1))
28    }
29
30    /// This API decrements the reference count for the reference passed in and returns the
31    /// resulting reference count.
32    pub fn dec(&mut self) -> NapiResult<u32> {
33        Ok(napi_call!(=napi_reference_unref, self.0, self.1))
34    }
35
36    /// If still valid, this API returns the napi_value representing the JavaScript Object
37    /// associated with the napi_ref. Otherwise, result will be NULL.
38    pub fn deref<T: NapiValueT>(&self) -> NapiResult<T> {
39        let value = napi_call!(=napi_get_reference_value, self.0, self.1);
40        Ok(T::from_raw(self.0, value))
41    }
42}
43
44impl Drop for NapiRef {
45    fn drop(&mut self) {
46        unsafe {
47            api::napi_delete_reference(self.0, self.1);
48        }
49    }
50}