Skip to main content

napi/bindgen_runtime/
mod.rs

1use std::ffi::c_void;
2use std::rc::Rc;
3
4pub use callback_info::*;
5pub use ctor::ctor;
6pub use env::*;
7pub use iterator::Generator;
8pub use js_values::*;
9pub use module_register::*;
10
11use super::sys;
12use crate::{JsError, Result, Status};
13
14#[cfg(feature = "tokio_rt")]
15pub mod async_iterator;
16#[cfg(feature = "tokio_rt")]
17pub use async_iterator::AsyncGenerator;
18mod callback_info;
19mod env;
20mod error;
21pub mod iterator;
22mod js_values;
23mod module_register;
24
25pub trait ObjectFinalize: Sized {
26  #[allow(unused)]
27  fn finalize(self, env: Env) -> Result<()> {
28    Ok(())
29  }
30}
31
32/// # Safety
33///
34/// called when node wrapper objects destroyed
35#[doc(hidden)]
36pub(crate) unsafe extern "C" fn raw_finalize_unchecked<T: ObjectFinalize>(
37  env: sys::napi_env,
38  finalize_data: *mut c_void,
39  _finalize_hint: *mut c_void,
40) {
41  let data: Box<T> = unsafe { Box::from_raw(finalize_data.cast()) };
42  if let Err(err) = data.finalize(Env::from_raw(env)) {
43    let e: JsError = err.into();
44    unsafe { e.throw_into(env) };
45    return;
46  }
47  if let Some((_, ref_val, finalize_callbacks_ptr)) =
48    REFERENCE_MAP.with(|cell| cell.borrow_mut(|reference_map| reference_map.remove(&finalize_data)))
49  {
50    let finalize_callbacks_rc = unsafe { Rc::from_raw(finalize_callbacks_ptr) };
51
52    #[cfg(all(debug_assertions, not(target_family = "wasm")))]
53    {
54      let rc_strong_count = Rc::strong_count(&finalize_callbacks_rc);
55      // If `Rc` strong count is 2, it means the finalize of referenced `Object` is called before the `fn drop` of the `Reference`
56      // It always happened on exiting process
57      // In general, the `fn drop` would happen first
58      if rc_strong_count != 1 && rc_strong_count != 2 {
59        eprintln!("Rc strong count is: {rc_strong_count}, it should be 1 or 2");
60      }
61    }
62    let finalize = unsafe { Box::from_raw(finalize_callbacks_rc.get()) };
63    finalize();
64    let delete_reference_status = unsafe { sys::napi_delete_reference(env, ref_val) };
65    debug_assert!(
66      delete_reference_status == sys::Status::napi_ok,
67      "Delete reference in finalize callback failed {}",
68      Status::from(delete_reference_status)
69    );
70  }
71}
72
73/// # Safety
74///
75/// called when node buffer is ready for gc
76#[doc(hidden)]
77pub unsafe extern "C" fn drop_buffer(
78  _env: sys::napi_env,
79  #[allow(unused)] finalize_data: *mut c_void,
80  finalize_hint: *mut c_void,
81) {
82  #[cfg(all(debug_assertions, not(windows), not(target_family = "wasm")))]
83  {
84    js_values::BUFFER_DATA.with(|buffer_data| {
85      let mut buffer = buffer_data.lock().expect("Unlock Buffer data failed");
86      buffer.remove(&(finalize_data as *mut u8));
87    });
88  }
89  unsafe {
90    drop(Box::from_raw(finalize_hint as *mut Buffer));
91  }
92}
93
94/// # Safety
95///
96/// called when node buffer slice is ready for gc
97#[doc(hidden)]
98pub unsafe extern "C" fn drop_buffer_slice(
99  _env: sys::napi_env,
100  finalize_data: *mut c_void,
101  finalize_hint: *mut c_void,
102) {
103  let (len, cap): (usize, usize) = *unsafe { Box::from_raw(finalize_hint.cast()) };
104  #[cfg(all(debug_assertions, not(windows), not(target_family = "wasm")))]
105  {
106    js_values::BUFFER_DATA.with(|buffer_data| {
107      let mut buffer = buffer_data.lock().expect("Unlock Buffer data failed");
108      buffer.remove(&(finalize_data as *mut u8));
109    });
110  }
111  if finalize_data.is_null() {
112    return;
113  }
114  unsafe {
115    drop(Vec::from_raw_parts(finalize_data, len, cap));
116  }
117}
118
119/// Create an object with properties
120///
121/// When the `experimental` feature is enabled, uses `napi_create_object_with_properties`
122/// which creates the object with all properties in a single optimized call.
123/// Otherwise falls back to `napi_create_object` + `napi_define_properties`.
124#[doc(hidden)]
125#[cfg(not(feature = "noop"))]
126#[inline]
127pub unsafe fn create_object_with_properties(
128  env: sys::napi_env,
129  properties: &[sys::napi_property_descriptor],
130) -> Result<sys::napi_value> {
131  use crate::check_status;
132
133  let mut obj_ptr = std::ptr::null_mut();
134
135  #[cfg(all(
136    feature = "experimental",
137    feature = "node_version_detect",
138    not(target_family = "wasm")
139  ))]
140  {
141    let node_version = NODE_VERSION.get().unwrap();
142    if !properties.is_empty()
143      && ((node_version.major == 25 && node_version.minor >= 2) || node_version.major > 25)
144    {
145      // Convert property names from C strings to napi_value
146      let mut names: Vec<sys::napi_value> = Vec::with_capacity(properties.len());
147      let mut values: Vec<sys::napi_value> = Vec::with_capacity(properties.len());
148
149      for prop in properties {
150        let mut name_value = std::ptr::null_mut();
151        // utf8name is a null-terminated C string, use -1 to auto-detect length
152        check_status!(
153          sys::napi_create_string_utf8(env, prop.utf8name, -1, &mut name_value),
154          "Failed to create property name string",
155        )?;
156        names.push(name_value);
157        values.push(prop.value);
158      }
159
160      let mut result_obj = std::ptr::null_mut();
161      check_status!(
162        sys::napi_create_object_with_properties(
163          env,
164          std::ptr::null_mut(), // prototype_or_null
165          names.as_ptr(),
166          values.as_ptr(),
167          properties.len(),
168          &mut result_obj,
169        ),
170        "Failed to create object with properties",
171      )?;
172      return Ok(result_obj);
173    }
174  }
175
176  // Fallback: create object then define properties
177  check_status!(
178    sys::napi_create_object(env, &mut obj_ptr),
179    "Failed to create object",
180  )?;
181
182  if !properties.is_empty() {
183    check_status!(
184      sys::napi_define_properties(env, obj_ptr, properties.len(), properties.as_ptr()),
185      "Failed to define properties",
186    )?;
187  }
188
189  Ok(obj_ptr)
190}
191
192#[doc(hidden)]
193#[cfg(feature = "noop")]
194pub unsafe fn create_object_with_properties(
195  _env: sys::napi_env,
196  _properties: &[sys::napi_property_descriptor],
197) -> Result<sys::napi_value> {
198  Ok(std::ptr::null_mut())
199}