napi_h/js_values/
escapable_handle_scope.rs

1use std::ops::Deref;
2use std::ptr;
3
4use crate::check_status;
5use crate::{sys, Env, NapiRaw, Result};
6
7pub struct EscapableHandleScope<T: NapiRaw> {
8  handle_scope: sys::napi_escapable_handle_scope,
9  value: T,
10}
11
12impl<T: NapiRaw> EscapableHandleScope<T> {
13  pub fn open(env: Env, value: T) -> Result<Self> {
14    let mut handle_scope = ptr::null_mut();
15    check_status!(unsafe { sys::napi_open_escapable_handle_scope(env.0, &mut handle_scope) })?;
16    let mut result = ptr::null_mut();
17    check_status!(unsafe {
18      sys::napi_escape_handle(env.0, handle_scope, NapiRaw::raw(&value), &mut result)
19    })?;
20    Ok(Self {
21      handle_scope,
22      value,
23    })
24  }
25
26  pub fn close(self, env: Env) -> Result<()> {
27    check_status!(unsafe { sys::napi_close_escapable_handle_scope(env.0, self.handle_scope) })
28  }
29}
30
31impl<T: NapiRaw> Deref for EscapableHandleScope<T> {
32  type Target = T;
33
34  fn deref(&self) -> &T {
35    &self.value
36  }
37}