* The MIT License (MIT)
* Copyright (C) 2024 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*/
use std::ops::Deref;
use std::ptr;
use crate::check_status;
use crate::{sys, Env, NapiRaw, Result};
pub struct EscapableHandleScope<T: NapiRaw> {
handle_scope: sys::napi_escapable_handle_scope,
value: T,
}
impl<T: NapiRaw> EscapableHandleScope<T> {
pub fn open(env: Env, value: T) -> Result<Self> {
let mut handle_scope = ptr::null_mut();
check_status!(unsafe { sys::napi_open_escapable_handle_scope(env.0, &mut handle_scope) })?;
let mut result = ptr::null_mut();
check_status!(unsafe {
sys::napi_escape_handle(env.0, handle_scope, NapiRaw::raw(&value), &mut result)
})?;
Ok(Self {
handle_scope,
value,
})
}
pub fn close(self, env: Env) -> Result<()> {
check_status!(unsafe { sys::napi_close_escapable_handle_scope(env.0, self.handle_scope) })
}
}
impl<T: NapiRaw> Deref for EscapableHandleScope<T> {
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}