pub struct Env(_);
Expand description
Env
is used to represent a context that the underlying N-API implementation can use to persist VM-specific state.
Specifically, the same Env
that was passed in when the initial native function was called must be passed to any subsequent nested N-API calls.
Caching the Env
for the purpose of general reuse, and passing the Env
between instances of the same addon running on different Worker threads is not allowed.
The Env
becomes invalid when an instance of a native addon is unloaded.
Notification of this event is delivered through the callbacks given to Env::add_env_cleanup_hook
and Env::set_instance_data
.
Implementations§
source§impl Env
impl Env
pub fn create_array(&self, len: u32) -> Result<Array>
sourcepub fn get_undefined(&self) -> Result<JsUndefined>
pub fn get_undefined(&self) -> Result<JsUndefined>
Get JsUndefined value
Examples found in repository?
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
pub fn try_get<ArgType: NapiValue + TypeName + FromNapiValue>(
&self,
index: usize,
) -> Result<Either<ArgType, JsUndefined>> {
if index >= self.arg_len() {
Err(Error::new(
Status::GenericFailure,
"Arguments index out of range".to_owned(),
))
} else if index < self.length {
unsafe { ArgType::from_raw(self.env.0, self.args[index]) }.map(Either::A)
} else {
self.env.get_undefined().map(Either::B)
}
}
More examples
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
pub fn call<V>(&self, this: Option<&JsObject>, args: &[V]) -> Result<JsUnknown>
where
V: NapiRaw,
{
let raw_this = this
.map(|v| unsafe { v.raw() })
.or_else(|| {
unsafe { Env::from_raw(self.0.env) }
.get_undefined()
.ok()
.map(|u| unsafe { u.raw() })
})
.ok_or_else(|| Error::new(Status::GenericFailure, "Get raw this failed".to_owned()))?;
let raw_args = args
.iter()
.map(|arg| unsafe { arg.raw() })
.collect::<Vec<sys::napi_value>>();
let mut return_value = ptr::null_mut();
check_pending_exception!(self.0.env, unsafe {
sys::napi_call_function(
self.0.env,
raw_this,
self.0.value,
args.len(),
raw_args.as_ptr(),
&mut return_value,
)
})?;
unsafe { JsUnknown::from_raw(self.0.env, return_value) }
}
/// [napi_call_function](https://nodejs.org/api/n-api.html#n_api_napi_call_function)
/// The same with `call`, but without arguments
pub fn call_without_args(&self, this: Option<&JsObject>) -> Result<JsUnknown> {
let raw_this = this
.map(|v| unsafe { v.raw() })
.or_else(|| {
unsafe { Env::from_raw(self.0.env) }
.get_undefined()
.ok()
.map(|u| unsafe { u.raw() })
})
.ok_or_else(|| Error::new(Status::GenericFailure, "Get raw this failed".to_owned()))?;
let mut return_value = ptr::null_mut();
check_pending_exception!(self.0.env, unsafe {
sys::napi_call_function(
self.0.env,
raw_this,
self.0.value,
0,
ptr::null_mut(),
&mut return_value,
)
})?;
unsafe { JsUnknown::from_raw(self.0.env, return_value) }
}
sourcepub fn get_null(&self) -> Result<JsNull>
pub fn get_null(&self) -> Result<JsNull>
Examples found in repository?
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
fn serialize_unit(self) -> Result<Self::Ok> {
self.0.get_null().map(|null| null.0)
}
fn serialize_none(self) -> Result<Self::Ok> {
self.0.get_null().map(|null| null.0)
}
fn serialize_str(self, v: &str) -> Result<Self::Ok> {
self.0.create_string(v).map(|string| string.0)
}
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok>
where
T: Serialize,
{
value.serialize(self)
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
let env = self.0;
let key = env.create_string("")?;
let obj = env.create_object()?;
Ok(MapSerializer { key, obj })
}
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
let array = self.0.create_array_with_length(len.unwrap_or(0))?;
Ok(SeqSerializer {
current_index: 0,
array,
})
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeTupleVariant> {
let env = self.0;
let array = env.create_array_with_length(len)?;
let mut object = env.create_object()?;
object.set_named_property(
variant,
JsObject(Value {
value: array.0.value,
env: array.0.env,
value_type: ValueType::Object,
}),
)?;
Ok(SeqSerializer {
current_index: 0,
array,
})
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
self.0.get_null().map(|null| null.0)
}
sourcepub fn get_global(&self) -> Result<JsGlobal>
pub fn get_global(&self) -> Result<JsGlobal>
source§impl Env
impl Env
sourcepub unsafe fn from_raw(env: napi_env) -> Self
pub unsafe fn from_raw(env: napi_env) -> Self
Examples found in repository?
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> StdResult<(), Self::Error>
where
T: Serialize,
{
let env = unsafe { Env::from_raw(self.array.0.env) };
self.array.set_element(
self.current_index as _,
JsUnknown(value.serialize(Ser::new(&env))?),
)?;
self.current_index += 1;
Ok(())
}
fn end(self) -> Result<Self::Ok> {
Ok(self.array.0)
}
}
#[doc(hidden)]
impl ser::SerializeTuple for SeqSerializer {
type Ok = Value;
type Error = Error;
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> StdResult<(), Self::Error>
where
T: Serialize,
{
let env = unsafe { Env::from_raw(self.array.0.env) };
self.array.set_element(
self.current_index as _,
JsUnknown(value.serialize(Ser::new(&env))?),
)?;
self.current_index += 1;
Ok(())
}
fn end(self) -> StdResult<Self::Ok, Self::Error> {
Ok(self.array.0)
}
}
#[doc(hidden)]
impl ser::SerializeTupleStruct for SeqSerializer {
type Ok = Value;
type Error = Error;
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> StdResult<(), Self::Error>
where
T: Serialize,
{
let env = unsafe { Env::from_raw(self.array.0.env) };
self.array.set_element(
self.current_index as _,
JsUnknown(value.serialize(Ser::new(&env))?),
)?;
self.current_index += 1;
Ok(())
}
fn end(self) -> StdResult<Self::Ok, Self::Error> {
Ok(self.array.0)
}
}
#[doc(hidden)]
impl ser::SerializeTupleVariant for SeqSerializer {
type Ok = Value;
type Error = Error;
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> StdResult<(), Self::Error>
where
T: Serialize,
{
let env = unsafe { Env::from_raw(self.array.0.env) };
self.array.set_element(
self.current_index as _,
JsUnknown(value.serialize(Ser::new(&env))?),
)?;
self.current_index += 1;
Ok(())
}
fn end(self) -> Result<Self::Ok> {
Ok(self.array.0)
}
}
pub struct MapSerializer {
key: JsString,
obj: JsObject,
}
#[doc(hidden)]
impl ser::SerializeMap for MapSerializer {
type Ok = Value;
type Error = Error;
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> StdResult<(), Self::Error>
where
T: Serialize,
{
let env = unsafe { Env::from_raw(self.obj.0.env) };
self.key = JsString(key.serialize(Ser::new(&env))?);
Ok(())
}
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> StdResult<(), Self::Error>
where
T: Serialize,
{
let env = unsafe { Env::from_raw(self.obj.0.env) };
self.obj.set_property(
JsString(Value {
env: self.key.0.env,
value: self.key.0.value,
value_type: ValueType::String,
}),
JsUnknown(value.serialize(Ser::new(&env))?),
)?;
Ok(())
}
fn serialize_entry<K: ?Sized, V: ?Sized>(
&mut self,
key: &K,
value: &V,
) -> StdResult<(), Self::Error>
where
K: Serialize,
V: Serialize,
{
let env = unsafe { Env::from_raw(self.obj.0.env) };
self.obj.set_property(
JsString(key.serialize(Ser::new(&env))?),
JsUnknown(value.serialize(Ser::new(&env))?),
)?;
Ok(())
}
fn end(self) -> Result<Self::Ok> {
Ok(self.obj.0)
}
}
pub struct StructSerializer {
obj: JsObject,
}
#[doc(hidden)]
impl ser::SerializeStruct for StructSerializer {
type Ok = Value;
type Error = Error;
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> StdResult<(), Error>
where
T: Serialize,
{
let env = unsafe { Env::from_raw(self.obj.0.env) };
self
.obj
.set_named_property(key, JsUnknown(value.serialize(Ser::new(&env))?))?;
Ok(())
}
fn end(self) -> Result<Self::Ok> {
Ok(self.obj.0)
}
}
#[doc(hidden)]
impl ser::SerializeStructVariant for StructSerializer {
type Ok = Value;
type Error = Error;
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> StdResult<(), Error>
where
T: Serialize,
{
let env = unsafe { Env::from_raw(self.obj.0.env) };
self
.obj
.set_named_property(key, JsUnknown(value.serialize(Ser::new(&env))?))?;
Ok(())
}
More examples
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
pub fn set_interval(&self, handler: JsFunction, interval: f64) -> Result<JsTimeout> {
let func: JsFunction = self.get_named_property_unchecked("setInterval")?;
func
.call(
None,
&[
handler.into_unknown(),
unsafe { Env::from_raw(self.0.env) }
.create_double(interval)?
.into_unknown(),
],
)
.and_then(|ret| ret.try_into())
}
pub fn clear_interval(&self, timer: JsTimeout) -> Result<JsUndefined> {
let func: JsFunction = self.get_named_property_unchecked("clearInterval")?;
func
.call(None, &[timer.into_unknown()])
.and_then(|ret| ret.try_into())
}
pub fn set_timeout(&self, handler: JsFunction, interval: f64) -> Result<JsTimeout> {
let func: JsFunction = self.get_named_property_unchecked("setTimeout")?;
func
.call(
None,
&[
handler.into_unknown(),
unsafe { Env::from_raw(self.0.env) }
.create_double(interval)?
.into_unknown(),
],
)
.and_then(|ret| ret.try_into())
}
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
unsafe extern "C" fn finalize_callback<T, Hint, F>(
raw_env: sys::napi_env,
finalize_data: *mut c_void,
finalize_hint: *mut c_void,
) where
T: 'static,
Hint: 'static,
F: FnOnce(FinalizeContext<T, Hint>),
{
let (value, callback, raw_ref) =
unsafe { *Box::from_raw(finalize_data as *mut (T, F, sys::napi_ref)) };
let hint = unsafe { *Box::from_raw(finalize_hint as *mut Hint) };
let env = unsafe { Env::from_raw(raw_env) };
callback(FinalizeContext { env, value, hint });
if !raw_ref.is_null() {
let status = unsafe { sys::napi_delete_reference(raw_env, raw_ref) };
debug_assert!(
status == sys::Status::napi_ok,
"Delete reference in finalize callback failed"
);
}
}
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
pub fn call<V>(&self, this: Option<&JsObject>, args: &[V]) -> Result<JsUnknown>
where
V: NapiRaw,
{
let raw_this = this
.map(|v| unsafe { v.raw() })
.or_else(|| {
unsafe { Env::from_raw(self.0.env) }
.get_undefined()
.ok()
.map(|u| unsafe { u.raw() })
})
.ok_or_else(|| Error::new(Status::GenericFailure, "Get raw this failed".to_owned()))?;
let raw_args = args
.iter()
.map(|arg| unsafe { arg.raw() })
.collect::<Vec<sys::napi_value>>();
let mut return_value = ptr::null_mut();
check_pending_exception!(self.0.env, unsafe {
sys::napi_call_function(
self.0.env,
raw_this,
self.0.value,
args.len(),
raw_args.as_ptr(),
&mut return_value,
)
})?;
unsafe { JsUnknown::from_raw(self.0.env, return_value) }
}
/// [napi_call_function](https://nodejs.org/api/n-api.html#n_api_napi_call_function)
/// The same with `call`, but without arguments
pub fn call_without_args(&self, this: Option<&JsObject>) -> Result<JsUnknown> {
let raw_this = this
.map(|v| unsafe { v.raw() })
.or_else(|| {
unsafe { Env::from_raw(self.0.env) }
.get_undefined()
.ok()
.map(|u| unsafe { u.raw() })
})
.ok_or_else(|| Error::new(Status::GenericFailure, "Get raw this failed".to_owned()))?;
let mut return_value = ptr::null_mut();
check_pending_exception!(self.0.env, unsafe {
sys::napi_call_function(
self.0.env,
raw_this,
self.0.value,
0,
ptr::null_mut(),
&mut return_value,
)
})?;
unsafe { JsUnknown::from_raw(self.0.env, return_value) }
}
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
extern "C" fn napi_resolve_deferred<Data: ToNapiValue, Resolver: FnOnce(Env) -> Result<Data>>(
env: sys::napi_env,
_js_callback: sys::napi_value,
context: *mut c_void,
data: *mut c_void,
) {
let deferred = context as sys::napi_deferred;
let resolver = unsafe { Box::from_raw(data as *mut Result<Resolver>) };
let result = resolver
.and_then(|resolver| resolver(unsafe { Env::from_raw(env) }))
.and_then(|res| unsafe { ToNapiValue::to_napi_value(env, res) });
match result {
Ok(res) => {
let status = unsafe { sys::napi_resolve_deferred(env, deferred, res) };
debug_assert!(status == sys::Status::napi_ok, "Resolve promise failed");
}
Err(e) => {
let status =
unsafe { sys::napi_reject_deferred(env, deferred, JsError::from(e).into_value(env)) };
debug_assert!(status == sys::Status::napi_ok, "Reject promise failed");
}
}
}
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
unsafe fn from_napi_value(env: sys::napi_env, napi_val: sys::napi_value) -> crate::Result<Self> {
let mut signal = unsafe { JsObject::from_raw_unchecked(env, napi_val) };
let async_work_inner: Rc<AtomicPtr<sys::napi_async_work__>> =
Rc::new(AtomicPtr::new(ptr::null_mut()));
let raw_promise: Rc<AtomicPtr<sys::napi_deferred__>> = Rc::new(AtomicPtr::new(ptr::null_mut()));
let task_status = Rc::new(AtomicU8::new(0));
let abort_controller = AbortSignal {
raw_work: async_work_inner.clone(),
raw_deferred: raw_promise.clone(),
status: task_status.clone(),
};
let js_env = unsafe { Env::from_raw(env) };
check_status!(unsafe {
sys::napi_wrap(
env,
signal.0.value,
Box::into_raw(Box::new(abort_controller)) as *mut _,
Some(async_task_abort_controller_finalize),
ptr::null_mut(),
ptr::null_mut(),
)
})?;
signal.set_named_property("onabort", js_env.create_function("onabort", on_abort)?)?;
Ok(AbortSignal {
raw_work: async_work_inner,
raw_deferred: raw_promise,
status: task_status,
})
}
sourcepub fn get_boolean(&self, value: bool) -> Result<JsBoolean>
pub fn get_boolean(&self, value: bool) -> Result<JsBoolean>
sourcepub fn create_int32(&self, int: i32) -> Result<JsNumber>
pub fn create_int32(&self, int: i32) -> Result<JsNumber>
Examples found in repository?
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
fn serialize_i16(self, v: i16) -> Result<Self::Ok> {
self.0.create_int32(v as _).map(|js_number| js_number.0)
}
fn serialize_i32(self, v: i32) -> Result<Self::Ok> {
self.0.create_int32(v).map(|js_number| js_number.0)
}
fn serialize_i64(self, v: i64) -> Result<Self::Ok> {
self.0.create_int64(v).map(|js_number| js_number.0)
}
fn serialize_i8(self, v: i8) -> Result<Self::Ok> {
self.0.create_int32(v as _).map(|js_number| js_number.0)
}
sourcepub fn create_int64(&self, int: i64) -> Result<JsNumber>
pub fn create_int64(&self, int: i64) -> Result<JsNumber>
sourcepub fn create_uint32(&self, number: u32) -> Result<JsNumber>
pub fn create_uint32(&self, number: u32) -> Result<JsNumber>
sourcepub fn create_double(&self, double: f64) -> Result<JsNumber>
pub fn create_double(&self, double: f64) -> Result<JsNumber>
Examples found in repository?
More examples
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
pub fn set_interval(&self, handler: JsFunction, interval: f64) -> Result<JsTimeout> {
let func: JsFunction = self.get_named_property_unchecked("setInterval")?;
func
.call(
None,
&[
handler.into_unknown(),
unsafe { Env::from_raw(self.0.env) }
.create_double(interval)?
.into_unknown(),
],
)
.and_then(|ret| ret.try_into())
}
pub fn clear_interval(&self, timer: JsTimeout) -> Result<JsUndefined> {
let func: JsFunction = self.get_named_property_unchecked("clearInterval")?;
func
.call(None, &[timer.into_unknown()])
.and_then(|ret| ret.try_into())
}
pub fn set_timeout(&self, handler: JsFunction, interval: f64) -> Result<JsTimeout> {
let func: JsFunction = self.get_named_property_unchecked("setTimeout")?;
func
.call(
None,
&[
handler.into_unknown(),
unsafe { Env::from_raw(self.0.env) }
.create_double(interval)?
.into_unknown(),
],
)
.and_then(|ret| ret.try_into())
}
sourcepub fn create_bigint_from_i64(&self, value: i64) -> Result<JsBigInt>
pub fn create_bigint_from_i64(&self, value: i64) -> Result<JsBigInt>
sourcepub fn create_bigint_from_u64(&self, value: u64) -> Result<JsBigInt>
pub fn create_bigint_from_u64(&self, value: u64) -> Result<JsBigInt>
pub fn create_bigint_from_i128(&self, value: i128) -> Result<JsBigInt>
pub fn create_bigint_from_u128(&self, value: u128) -> Result<JsBigInt>
sourcepub fn create_bigint_from_words(
&self,
sign_bit: bool,
words: Vec<u64>
) -> Result<JsBigInt>
pub fn create_bigint_from_words(
&self,
sign_bit: bool,
words: Vec<u64>
) -> Result<JsBigInt>
n_api_napi_create_bigint_words
The resulting BigInt will be negative when sign_bit is true.
Examples found in repository?
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
fn serialize_u128(self, v: u128) -> Result<Self::Ok> {
let words_ref = &v as *const _;
let words = unsafe { slice::from_raw_parts(words_ref as *const u64, 2) };
self
.0
.create_bigint_from_words(false, words.to_vec())
.map(|v| v.raw)
}
#[cfg(all(
any(
feature = "napi2",
feature = "napi3",
feature = "napi4",
feature = "napi5"
),
not(feature = "napi6")
))]
fn serialize_i128(self, v: i128) -> Result<Self::Ok> {
self.0.create_string(v.to_string().as_str()).map(|v| v.0)
}
#[cfg(feature = "napi6")]
fn serialize_i128(self, v: i128) -> Result<Self::Ok> {
let words_ref = &(v as u128) as *const _;
let words = unsafe { slice::from_raw_parts(words_ref as *const u64, 2) };
self
.0
.create_bigint_from_words(v < 0, words.to_vec())
.map(|v| v.raw)
}
sourcepub fn create_string(&self, s: &str) -> Result<JsString>
pub fn create_string(&self, s: &str) -> Result<JsString>
Examples found in repository?
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
fn serialize_char(self, v: char) -> Result<Self::Ok> {
let mut b = [0; 4];
let result = v.encode_utf8(&mut b);
self.0.create_string(result).map(|js_string| js_string.0)
}
fn serialize_f32(self, v: f32) -> Result<Self::Ok> {
self.0.create_double(v as _).map(|js_number| js_number.0)
}
fn serialize_f64(self, v: f64) -> Result<Self::Ok> {
self.0.create_double(v).map(|js_number| js_number.0)
}
fn serialize_i16(self, v: i16) -> Result<Self::Ok> {
self.0.create_int32(v as _).map(|js_number| js_number.0)
}
fn serialize_i32(self, v: i32) -> Result<Self::Ok> {
self.0.create_int32(v).map(|js_number| js_number.0)
}
fn serialize_i64(self, v: i64) -> Result<Self::Ok> {
self.0.create_int64(v).map(|js_number| js_number.0)
}
fn serialize_i8(self, v: i8) -> Result<Self::Ok> {
self.0.create_int32(v as _).map(|js_number| js_number.0)
}
fn serialize_u8(self, v: u8) -> Result<Self::Ok> {
self.0.create_uint32(v as _).map(|js_number| js_number.0)
}
fn serialize_u16(self, v: u16) -> Result<Self::Ok> {
self.0.create_uint32(v as _).map(|js_number| js_number.0)
}
fn serialize_u32(self, v: u32) -> Result<Self::Ok> {
self.0.create_uint32(v).map(|js_number| js_number.0)
}
#[cfg(all(
any(
feature = "napi2",
feature = "napi3",
feature = "napi4",
feature = "napi5"
),
not(feature = "napi6")
))]
fn serialize_u64(self, v: u64) -> Result<Self::Ok> {
self.0.create_int64(v as _).map(|js_number| js_number.0)
}
#[cfg(feature = "napi6")]
fn serialize_u64(self, v: u64) -> Result<Self::Ok> {
self
.0
.create_bigint_from_u64(v)
.map(|js_number| js_number.raw)
}
#[cfg(all(
any(
feature = "napi2",
feature = "napi3",
feature = "napi4",
feature = "napi5"
),
not(feature = "napi6")
))]
fn serialize_u128(self, v: u128) -> Result<Self::Ok> {
self.0.create_string(v.to_string().as_str()).map(|v| v.0)
}
#[cfg(feature = "napi6")]
fn serialize_u128(self, v: u128) -> Result<Self::Ok> {
let words_ref = &v as *const _;
let words = unsafe { slice::from_raw_parts(words_ref as *const u64, 2) };
self
.0
.create_bigint_from_words(false, words.to_vec())
.map(|v| v.raw)
}
#[cfg(all(
any(
feature = "napi2",
feature = "napi3",
feature = "napi4",
feature = "napi5"
),
not(feature = "napi6")
))]
fn serialize_i128(self, v: i128) -> Result<Self::Ok> {
self.0.create_string(v.to_string().as_str()).map(|v| v.0)
}
#[cfg(feature = "napi6")]
fn serialize_i128(self, v: i128) -> Result<Self::Ok> {
let words_ref = &(v as u128) as *const _;
let words = unsafe { slice::from_raw_parts(words_ref as *const u64, 2) };
self
.0
.create_bigint_from_words(v < 0, words.to_vec())
.map(|v| v.raw)
}
fn serialize_unit(self) -> Result<Self::Ok> {
self.0.get_null().map(|null| null.0)
}
fn serialize_none(self) -> Result<Self::Ok> {
self.0.get_null().map(|null| null.0)
}
fn serialize_str(self, v: &str) -> Result<Self::Ok> {
self.0.create_string(v).map(|string| string.0)
}
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok>
where
T: Serialize,
{
value.serialize(self)
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
let env = self.0;
let key = env.create_string("")?;
let obj = env.create_object()?;
Ok(MapSerializer { key, obj })
}
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
let array = self.0.create_array_with_length(len.unwrap_or(0))?;
Ok(SeqSerializer {
current_index: 0,
array,
})
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeTupleVariant> {
let env = self.0;
let array = env.create_array_with_length(len)?;
let mut object = env.create_object()?;
object.set_named_property(
variant,
JsObject(Value {
value: array.0.value,
env: array.0.env,
value_type: ValueType::Object,
}),
)?;
Ok(SeqSerializer {
current_index: 0,
array,
})
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
self.0.get_null().map(|null| null.0)
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok> {
self.0.create_string(variant).map(|string| string.0)
}
More examples
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
pub fn create_symbol(&self, description: Option<&str>) -> Result<JsSymbol> {
let mut result = ptr::null_mut();
check_status!(unsafe {
sys::napi_create_symbol(
self.0,
description
.and_then(|desc| self.create_string(desc).ok())
.map(|string| string.0.value)
.unwrap_or(ptr::null_mut()),
&mut result,
)
})?;
Ok(unsafe { JsSymbol::from_raw_unchecked(self.0, result) })
}
pub fn create_object(&self) -> Result<JsObject> {
let mut raw_value = ptr::null_mut();
check_status!(unsafe { sys::napi_create_object(self.0, &mut raw_value) })?;
Ok(unsafe { JsObject::from_raw_unchecked(self.0, raw_value) })
}
pub fn create_empty_array(&self) -> Result<JsObject> {
let mut raw_value = ptr::null_mut();
check_status!(unsafe { sys::napi_create_array(self.0, &mut raw_value) })?;
Ok(unsafe { JsObject::from_raw_unchecked(self.0, raw_value) })
}
pub fn create_array_with_length(&self, length: usize) -> Result<JsObject> {
let mut raw_value = ptr::null_mut();
check_status!(unsafe { sys::napi_create_array_with_length(self.0, length, &mut raw_value) })?;
Ok(unsafe { JsObject::from_raw_unchecked(self.0, raw_value) })
}
/// This API allocates a node::Buffer object. While this is still a fully-supported data structure, in most cases using a TypedArray will suffice.
pub fn create_buffer(&self, length: usize) -> Result<JsBufferValue> {
let mut raw_value = ptr::null_mut();
let mut data_ptr = ptr::null_mut();
check_status!(unsafe {
sys::napi_create_buffer(self.0, length, &mut data_ptr, &mut raw_value)
})?;
Ok(JsBufferValue::new(
JsBuffer(Value {
env: self.0,
value: raw_value,
value_type: ValueType::Object,
}),
mem::ManuallyDrop::new(unsafe { Vec::from_raw_parts(data_ptr as *mut _, length, length) }),
))
}
/// This API allocates a node::Buffer object and initializes it with data backed by the passed in buffer.
///
/// While this is still a fully-supported data structure, in most cases using a TypedArray will suffice.
pub fn create_buffer_with_data(&self, mut data: Vec<u8>) -> Result<JsBufferValue> {
let length = data.len();
let mut raw_value = ptr::null_mut();
let data_ptr = data.as_mut_ptr();
check_status!(unsafe {
if length == 0 {
// Rust uses 0x1 as the data pointer for empty buffers,
// but NAPI/V8 only allows multiple buffers to have
// the same data pointer if it's 0x0.
sys::napi_create_buffer(self.0, length, ptr::null_mut(), &mut raw_value)
} else {
sys::napi_create_external_buffer(
self.0,
length,
data_ptr as *mut c_void,
Some(drop_buffer),
Box::into_raw(Box::new((length, data.capacity()))) as *mut c_void,
&mut raw_value,
)
}
})?;
Ok(JsBufferValue::new(
JsBuffer(Value {
env: self.0,
value: raw_value,
value_type: ValueType::Object,
}),
mem::ManuallyDrop::new(data),
))
}
/// # Safety
/// Mostly the same with `create_buffer_with_data`
///
/// Provided `finalize_callback` will be called when `Buffer` got dropped.
///
/// You can pass in `noop_finalize` if you have nothing to do in finalize phase.
pub unsafe fn create_buffer_with_borrowed_data<Hint, Finalize>(
&self,
data: *const u8,
length: usize,
hint: Hint,
finalize_callback: Finalize,
) -> Result<JsBufferValue>
where
Finalize: FnOnce(Hint, Env),
{
let mut raw_value = ptr::null_mut();
if data.is_null() || data == EMPTY_VEC.as_ptr() {
return Err(Error::new(
Status::InvalidArg,
"Borrowed data should not be null".to_owned(),
));
}
check_status!(unsafe {
sys::napi_create_external_buffer(
self.0,
length,
data as *mut c_void,
Some(
raw_finalize_with_custom_callback::<Hint, Finalize>
as unsafe extern "C" fn(
env: sys::napi_env,
finalize_data: *mut c_void,
finalize_hint: *mut c_void,
),
),
Box::into_raw(Box::new((hint, finalize_callback))) as *mut c_void,
&mut raw_value,
)
})?;
Ok(JsBufferValue::new(
JsBuffer(Value {
env: self.0,
value: raw_value,
value_type: ValueType::Object,
}),
mem::ManuallyDrop::new(unsafe { Vec::from_raw_parts(data as *mut u8, length, length) }),
))
}
/// This function gives V8 an indication of the amount of externally allocated memory that is kept alive by JavaScript objects (i.e. a JavaScript object that points to its own memory allocated by a native module).
///
/// Registering externally allocated memory will trigger global garbage collections more often than it would otherwise.
///
/// ***ATTENTION ⚠️***, do not use this with `create_buffer_with_data/create_arraybuffer_with_data`, since these two functions already called the `adjust_external_memory` internal.
pub fn adjust_external_memory(&mut self, size: i64) -> Result<i64> {
let mut changed = 0i64;
check_status!(unsafe { sys::napi_adjust_external_memory(self.0, size, &mut changed) })?;
Ok(changed)
}
/// This API allocates a node::Buffer object and initializes it with data copied from the passed-in buffer.
///
/// While this is still a fully-supported data structure, in most cases using a TypedArray will suffice.
pub fn create_buffer_copy<D>(&self, data_to_copy: D) -> Result<JsBufferValue>
where
D: AsRef<[u8]>,
{
let length = data_to_copy.as_ref().len();
let data_ptr = data_to_copy.as_ref().as_ptr();
let mut copy_data = ptr::null_mut();
let mut raw_value = ptr::null_mut();
check_status!(unsafe {
sys::napi_create_buffer_copy(
self.0,
length,
data_ptr as *mut c_void,
&mut copy_data,
&mut raw_value,
)
})?;
Ok(JsBufferValue::new(
JsBuffer(Value {
env: self.0,
value: raw_value,
value_type: ValueType::Object,
}),
mem::ManuallyDrop::new(unsafe { Vec::from_raw_parts(copy_data as *mut u8, length, length) }),
))
}
pub fn create_arraybuffer(&self, length: usize) -> Result<JsArrayBufferValue> {
let mut raw_value = ptr::null_mut();
let mut data_ptr = ptr::null_mut();
check_status!(unsafe {
sys::napi_create_arraybuffer(self.0, length, &mut data_ptr, &mut raw_value)
})?;
Ok(JsArrayBufferValue::new(
unsafe { JsArrayBuffer::from_raw_unchecked(self.0, raw_value) },
data_ptr as *mut c_void,
length,
))
}
pub fn create_arraybuffer_with_data(&self, mut data: Vec<u8>) -> Result<JsArrayBufferValue> {
let length = data.len();
let mut raw_value = ptr::null_mut();
let data_ptr = data.as_mut_ptr();
check_status!(unsafe {
if length == 0 {
// Rust uses 0x1 as the data pointer for empty buffers,
// but NAPI/V8 only allows multiple buffers to have
// the same data pointer if it's 0x0.
sys::napi_create_arraybuffer(self.0, length, ptr::null_mut(), &mut raw_value)
} else {
sys::napi_create_external_arraybuffer(
self.0,
data_ptr as *mut c_void,
length,
Some(drop_buffer),
Box::into_raw(Box::new((length, data.capacity()))) as *mut c_void,
&mut raw_value,
)
}
})?;
mem::forget(data);
Ok(JsArrayBufferValue::new(
JsArrayBuffer(Value {
env: self.0,
value: raw_value,
value_type: ValueType::Object,
}),
data_ptr as *mut c_void,
length,
))
}
/// # Safety
/// Mostly the same with `create_arraybuffer_with_data`
///
/// Provided `finalize_callback` will be called when `Buffer` got dropped.
///
/// You can pass in `noop_finalize` if you have nothing to do in finalize phase.
pub unsafe fn create_arraybuffer_with_borrowed_data<Hint, Finalize>(
&self,
data: *const u8,
length: usize,
hint: Hint,
finalize_callback: Finalize,
) -> Result<JsArrayBufferValue>
where
Finalize: FnOnce(Hint, Env),
{
let mut raw_value = ptr::null_mut();
check_status!(unsafe {
sys::napi_create_external_arraybuffer(
self.0,
if length == 0 {
// Rust uses 0x1 as the data pointer for empty buffers,
// but NAPI/V8 only allows multiple buffers to have
// the same data pointer if it's 0x0.
ptr::null_mut()
} else {
data as *mut c_void
},
length,
Some(
raw_finalize_with_custom_callback::<Hint, Finalize>
as unsafe extern "C" fn(
env: sys::napi_env,
finalize_data: *mut c_void,
finalize_hint: *mut c_void,
),
),
Box::into_raw(Box::new((hint, finalize_callback))) as *mut c_void,
&mut raw_value,
)
})?;
Ok(JsArrayBufferValue::new(
JsArrayBuffer(Value {
env: self.0,
value: raw_value,
value_type: ValueType::Object,
}),
data as *mut c_void,
length,
))
}
/// This API allows an add-on author to create a function object in native code.
///
/// This is the primary mechanism to allow calling into the add-on's native code from JavaScript.
///
/// The newly created function is not automatically visible from script after this call.
///
/// Instead, a property must be explicitly set on any object that is visible to JavaScript, in order for the function to be accessible from script.
pub fn create_function(&self, name: &str, callback: Callback) -> Result<JsFunction> {
let mut raw_result = ptr::null_mut();
let len = name.len();
let name = CString::new(name)?;
check_status!(unsafe {
sys::napi_create_function(
self.0,
name.as_ptr(),
len,
Some(callback),
ptr::null_mut(),
&mut raw_result,
)
})?;
Ok(unsafe { JsFunction::from_raw_unchecked(self.0, raw_result) })
}
#[cfg(feature = "napi5")]
pub fn create_function_from_closure<R, F>(&self, name: &str, callback: F) -> Result<JsFunction>
where
F: 'static + Fn(crate::CallContext<'_>) -> Result<R>,
R: NapiRaw,
{
use crate::CallContext;
let boxed_callback = Box::new(callback);
let closure_data_ptr: *mut F = Box::into_raw(boxed_callback);
let mut raw_result = ptr::null_mut();
let len = name.len();
let name = CString::new(name)?;
check_status!(unsafe {
sys::napi_create_function(
self.0,
name.as_ptr(),
len,
Some({
unsafe extern "C" fn trampoline<R: NapiRaw, F: Fn(CallContext<'_>) -> Result<R>>(
raw_env: sys::napi_env,
cb_info: sys::napi_callback_info,
) -> sys::napi_value {
use ::std::panic::{self, AssertUnwindSafe};
panic::catch_unwind(AssertUnwindSafe(|| {
let (raw_this, ref raw_args, closure_data_ptr) = {
let argc = {
let mut argc = 0;
let status = unsafe {
sys::napi_get_cb_info(
raw_env,
cb_info,
&mut argc,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
)
};
debug_assert!(
Status::from(status) == Status::Ok,
"napi_get_cb_info failed"
);
argc
};
let mut raw_args = vec![ptr::null_mut(); argc];
let mut raw_this = ptr::null_mut();
let mut closure_data_ptr = ptr::null_mut();
let status = unsafe {
sys::napi_get_cb_info(
raw_env,
cb_info,
&mut { argc },
raw_args.as_mut_ptr(),
&mut raw_this,
&mut closure_data_ptr,
)
};
debug_assert!(
Status::from(status) == Status::Ok,
"napi_get_cb_info failed"
);
(raw_this, raw_args, closure_data_ptr)
};
let closure: &F = unsafe {
closure_data_ptr
.cast::<F>()
.as_ref()
.expect("`napi_get_cb_info` should have yielded non-`NULL` assoc data")
};
let env = &mut unsafe { Env::from_raw(raw_env) };
let ctx = CallContext::new(env, cb_info, raw_this, raw_args, raw_args.len());
closure(ctx).map(|ret: R| unsafe { ret.raw() })
}))
.map_err(|e| {
Error::from_reason(format!(
"panic from Rust code: {}",
if let Some(s) = e.downcast_ref::<String>() {
s
} else if let Some(s) = e.downcast_ref::<&str>() {
s
} else {
"<no error message>"
},
))
})
.and_then(|v| v)
.unwrap_or_else(|e| {
unsafe { JsError::from(e).throw_into(raw_env) };
ptr::null_mut()
})
}
trampoline::<R, F>
}),
closure_data_ptr.cast(), // We let it borrow the data here
&mut raw_result,
)
})?;
// Note: based on N-API docs, at this point, we have created an effective
// `&'static dyn Fn…` in Rust parlance, in that thanks to `Box::into_raw()`
// we are sure the context won't be freed, and thus the callback may use
// it to call the actual method thanks to the trampoline…
// But we thus have a data leak: there is nothing yet responsible for
// running the `drop(Box::from_raw(…))` cleanup code.
//
// To solve that, according to the docs, we need to attach a finalizer:
check_status!(unsafe {
sys::napi_add_finalizer(
self.0,
raw_result,
closure_data_ptr.cast(),
Some({
unsafe extern "C" fn finalize_box_trampoline<F>(
_raw_env: sys::napi_env,
closure_data_ptr: *mut c_void,
_finalize_hint: *mut c_void,
) {
drop(unsafe { Box::<F>::from_raw(closure_data_ptr.cast()) })
}
finalize_box_trampoline::<F>
}),
ptr::null_mut(),
ptr::null_mut(),
)
})?;
Ok(unsafe { JsFunction::from_raw_unchecked(self.0, raw_result) })
}
/// This API retrieves a napi_extended_error_info structure with information about the last error that occurred.
///
/// The content of the napi_extended_error_info returned is only valid up until an n-api function is called on the same env.
///
/// Do not rely on the content or format of any of the extended information as it is not subject to SemVer and may change at any time. It is intended only for logging purposes.
///
/// This API can be called even if there is a pending JavaScript exception.
pub fn get_last_error_info(&self) -> Result<ExtendedErrorInfo> {
let mut raw_extended_error = ptr::null();
check_status!(unsafe { sys::napi_get_last_error_info(self.0, &mut raw_extended_error) })?;
unsafe { ptr::read(raw_extended_error) }.try_into()
}
/// Throw any JavaScript value
pub fn throw<T: NapiRaw>(&self, value: T) -> Result<()> {
check_status!(unsafe { sys::napi_throw(self.0, value.raw()) })
}
/// This API throws a JavaScript Error with the text provided.
pub fn throw_error(&self, msg: &str, code: Option<&str>) -> Result<()> {
let code = code.and_then(|s| CString::new(s).ok());
let msg = CString::new(msg)?;
check_status!(unsafe {
sys::napi_throw_error(
self.0,
code.map(|s| s.as_ptr()).unwrap_or(ptr::null_mut()),
msg.as_ptr(),
)
})
}
/// This API throws a JavaScript RangeError with the text provided.
pub fn throw_range_error(&self, msg: &str, code: Option<&str>) -> Result<()> {
let code = code.and_then(|s| CString::new(s).ok());
let msg = CString::new(msg)?;
check_status!(unsafe {
sys::napi_throw_range_error(
self.0,
code.map(|s| s.as_ptr()).unwrap_or(ptr::null_mut()),
msg.as_ptr(),
)
})
}
/// This API throws a JavaScript TypeError with the text provided.
pub fn throw_type_error(&self, msg: &str, code: Option<&str>) -> Result<()> {
let code = code.and_then(|s| CString::new(s).ok());
let msg = CString::new(msg)?;
check_status!(unsafe {
sys::napi_throw_type_error(
self.0,
code.map(|s| s.as_ptr()).unwrap_or(ptr::null_mut()),
msg.as_ptr(),
)
})
}
/// This API throws a JavaScript SyntaxError with the text provided.
#[cfg(feature = "experimental")]
pub fn throw_syntax_error(&self, msg: &str, code: Option<&str>) -> Result<()> {
let code = code.and_then(|s| CString::new(s).ok());
let msg = CString::new(msg)?;
check_status!(unsafe {
sys::node_api_throw_syntax_error(
self.0,
code.map(|s| s.as_ptr()).unwrap_or(ptr::null_mut()),
msg.as_ptr(),
)
})
}
#[allow(clippy::expect_fun_call)]
/// In the event of an unrecoverable error in a native module
///
/// A fatal error can be thrown to immediately terminate the process.
pub fn fatal_error(self, location: &str, message: &str) {
let location_len = location.len();
let message_len = message.len();
let location =
CString::new(location).expect(format!("Convert [{}] to CString failed", location).as_str());
let message =
CString::new(message).expect(format!("Convert [{}] to CString failed", message).as_str());
unsafe {
sys::napi_fatal_error(
location.as_ptr(),
location_len,
message.as_ptr(),
message_len,
)
}
}
#[cfg(feature = "napi3")]
/// Trigger an 'uncaughtException' in JavaScript.
///
/// Useful if an async callback throws an exception with no way to recover.
pub fn fatal_exception(&self, err: Error) {
unsafe {
let js_error = JsError::from(err).into_value(self.0);
debug_assert!(sys::napi_fatal_exception(self.0, js_error) == sys::Status::napi_ok);
};
}
/// Create JavaScript class
pub fn define_class(
&self,
name: &str,
constructor_cb: Callback,
properties: &[Property],
) -> Result<JsFunction> {
let mut raw_result = ptr::null_mut();
let raw_properties = properties
.iter()
.map(|prop| prop.raw())
.collect::<Vec<sys::napi_property_descriptor>>();
let c_name = CString::new(name)?;
check_status!(unsafe {
sys::napi_define_class(
self.0,
c_name.as_ptr() as *const c_char,
name.len(),
Some(constructor_cb),
ptr::null_mut(),
raw_properties.len(),
raw_properties.as_ptr(),
&mut raw_result,
)
})?;
Ok(unsafe { JsFunction::from_raw_unchecked(self.0, raw_result) })
}
pub fn wrap<T: 'static>(&self, js_object: &mut JsObject, native_object: T) -> Result<()> {
check_status!(unsafe {
sys::napi_wrap(
self.0,
js_object.0.value,
Box::into_raw(Box::new(TaggedObject::new(native_object))) as *mut c_void,
Some(raw_finalize::<T>),
ptr::null_mut(),
ptr::null_mut(),
)
})
}
pub fn unwrap<T: 'static>(&self, js_object: &JsObject) -> Result<&mut T> {
unsafe {
let mut unknown_tagged_object: *mut c_void = ptr::null_mut();
check_status!(sys::napi_unwrap(
self.0,
js_object.0.value,
&mut unknown_tagged_object,
))?;
let type_id = unknown_tagged_object as *const TypeId;
if *type_id == TypeId::of::<T>() {
let tagged_object = unknown_tagged_object as *mut TaggedObject<T>;
(*tagged_object).object.as_mut().ok_or_else(|| {
Error::new(
Status::InvalidArg,
"Invalid argument, nothing attach to js_object".to_owned(),
)
})
} else {
Err(Error::new(
Status::InvalidArg,
format!(
"Invalid argument, {} on unwrap is not the type of wrapped object",
type_name::<T>()
),
))
}
}
}
pub fn unwrap_from_ref<T: 'static>(&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::<T>() {
let tagged_object = unknown_tagged_object as *mut TaggedObject<T>;
(*tagged_object).object.as_mut().ok_or_else(|| {
Error::new(
Status::InvalidArg,
"Invalid argument, nothing attach to js_object".to_owned(),
)
})
} else {
Err(Error::new(
Status::InvalidArg,
format!(
"Invalid argument, {} on unwrap is not the type of wrapped object",
type_name::<T>()
),
))
}
}
}
pub fn drop_wrapped<T: 'static>(&self, js_object: &mut JsObject) -> Result<()> {
unsafe {
let mut unknown_tagged_object = ptr::null_mut();
check_status!(sys::napi_remove_wrap(
self.0,
js_object.0.value,
&mut unknown_tagged_object,
))?;
let type_id = unknown_tagged_object as *const TypeId;
if *type_id == TypeId::of::<T>() {
drop(Box::from_raw(unknown_tagged_object as *mut TaggedObject<T>));
Ok(())
} else {
Err(Error::new(
Status::InvalidArg,
format!(
"Invalid argument, {} on unwrap is not the type of wrapped object",
type_name::<T>()
),
))
}
}
}
/// This API create a new reference with the initial 1 ref count to the Object passed in.
pub fn create_reference<T>(&self, value: T) -> Result<Ref<()>>
where
T: NapiRaw,
{
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, raw_value, initial_ref_count, &mut raw_ref)
})?;
Ok(Ref {
raw_ref,
count: 1,
inner: (),
raw_value,
})
}
/// This API create a new reference with the specified reference count to the Object passed in.
pub fn create_reference_with_refcount<T>(&self, value: T, ref_count: u32) -> Result<Ref<()>>
where
T: NapiRaw,
{
let mut raw_ref = ptr::null_mut();
let raw_value = unsafe { value.raw() };
check_status!(unsafe {
sys::napi_create_reference(self.0, raw_value, ref_count, &mut raw_ref)
})?;
Ok(Ref {
raw_ref,
count: ref_count,
inner: (),
raw_value,
})
}
/// Get reference value from `Ref` with type check
///
/// Return error if the type of `reference` provided is mismatched with `T`
pub fn get_reference_value<T>(&self, reference: &Ref<()>) -> Result<T>
where
T: NapiValue,
{
let mut js_value = ptr::null_mut();
check_status!(unsafe {
sys::napi_get_reference_value(self.0, reference.raw_ref, &mut js_value)
})?;
unsafe { T::from_raw(self.0, js_value) }
}
/// Get reference value from `Ref` without type check
///
/// Using this API if you are sure the type of `T` is matched with provided `Ref<()>`.
///
/// If type mismatched, calling `T::method` would return `Err`.
pub fn get_reference_value_unchecked<T>(&self, reference: &Ref<()>) -> Result<T>
where
T: NapiValue,
{
let mut js_value = ptr::null_mut();
check_status!(unsafe {
sys::napi_get_reference_value(self.0, reference.raw_ref, &mut js_value)
})?;
Ok(unsafe { T::from_raw_unchecked(self.0, js_value) })
}
/// If `size_hint` provided, `Env::adjust_external_memory` will be called under the hood.
///
/// If no `size_hint` provided, global garbage collections will be triggered less times than expected.
///
/// If getting the exact `native_object` size is difficult, you can provide an approximate value, it's only effect to the GC.
pub fn create_external<T: 'static>(
&self,
native_object: T,
size_hint: Option<i64>,
) -> Result<JsExternal> {
let mut object_value = ptr::null_mut();
check_status!(unsafe {
sys::napi_create_external(
self.0,
Box::into_raw(Box::new(TaggedObject::new(native_object))) as *mut c_void,
Some(raw_finalize::<T>),
Box::into_raw(Box::new(size_hint)) as *mut c_void,
&mut object_value,
)
})?;
if let Some(changed) = size_hint {
if changed != 0 {
let mut adjusted_value = 0i64;
check_status!(unsafe {
sys::napi_adjust_external_memory(self.0, changed, &mut adjusted_value)
})?;
}
};
Ok(unsafe { JsExternal::from_raw_unchecked(self.0, object_value) })
}
pub fn get_value_external<T: 'static>(&self, js_external: &JsExternal) -> Result<&mut T> {
unsafe {
let mut unknown_tagged_object = ptr::null_mut();
check_status!(sys::napi_get_value_external(
self.0,
js_external.0.value,
&mut unknown_tagged_object,
))?;
let type_id = unknown_tagged_object as *const TypeId;
if *type_id == TypeId::of::<T>() {
let tagged_object = unknown_tagged_object as *mut TaggedObject<T>;
(*tagged_object).object.as_mut().ok_or_else(|| {
Error::new(
Status::InvalidArg,
"nothing attach to js_external".to_owned(),
)
})
} else {
Err(Error::new(
Status::InvalidArg,
"T on get_value_external is not the type of wrapped object".to_owned(),
))
}
}
}
pub fn create_error(&self, e: Error) -> Result<JsObject> {
let reason = &e.reason;
let reason_string = self.create_string(reason.as_str())?;
let mut result = ptr::null_mut();
check_status!(unsafe {
sys::napi_create_error(self.0, ptr::null_mut(), reason_string.0.value, &mut result)
})?;
Ok(unsafe { JsObject::from_raw_unchecked(self.0, result) })
}
/// Run [Task](./trait.Task.html) in libuv thread pool, return [AsyncWorkPromise](./struct.AsyncWorkPromise.html)
pub fn spawn<T: 'static + Task>(&self, task: T) -> Result<AsyncWorkPromise> {
async_work::run(self.0, task, None)
}
pub fn run_in_scope<T, F>(&self, executor: F) -> Result<T>
where
F: FnOnce() -> Result<T>,
{
let mut handle_scope = ptr::null_mut();
check_status!(unsafe { sys::napi_open_handle_scope(self.0, &mut handle_scope) })?;
let result = executor();
check_status!(unsafe { sys::napi_close_handle_scope(self.0, handle_scope) })?;
result
}
pub fn run_script<S: AsRef<str>>(&self, script: S) -> Result<JsObject> {
let s = self.create_string(script.as_ref())?;
let mut raw_value = ptr::null_mut();
check_status!(unsafe { sys::napi_run_script(self.0, s.raw(), &mut raw_value) })?;
Ok(unsafe { JsObject::from_raw_unchecked(self.0, raw_value) })
}
pub fn create_string_from_std(&self, s: String) -> Result<JsString>
sourcepub unsafe fn create_string_from_c_char(
&self,
data_ptr: *const c_char,
len: usize
) -> Result<JsString>
pub unsafe fn create_string_from_c_char(
&self,
data_ptr: *const c_char,
len: usize
) -> Result<JsString>
This API is used for C ffi scenario. Convert raw *const c_char into JsString
Safety
Create JsString from known valid utf-8 string
pub fn create_string_utf16(&self, chars: &[u16]) -> Result<JsString>
pub fn create_string_latin1(&self, chars: &[u8]) -> Result<JsString>
pub fn create_symbol_from_js_string(
&self,
description: JsString
) -> Result<JsSymbol>
pub fn create_symbol(&self, description: Option<&str>) -> Result<JsSymbol>
sourcepub fn create_object(&self) -> Result<JsObject>
pub fn create_object(&self) -> Result<JsObject>
Examples found in repository?
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
let env = self.0;
let key = env.create_string("")?;
let obj = env.create_object()?;
Ok(MapSerializer { key, obj })
}
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
let array = self.0.create_array_with_length(len.unwrap_or(0))?;
Ok(SeqSerializer {
current_index: 0,
array,
})
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeTupleVariant> {
let env = self.0;
let array = env.create_array_with_length(len)?;
let mut object = env.create_object()?;
object.set_named_property(
variant,
JsObject(Value {
value: array.0.value,
env: array.0.env,
value_type: ValueType::Object,
}),
)?;
Ok(SeqSerializer {
current_index: 0,
array,
})
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
self.0.get_null().map(|null| null.0)
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok> {
self.0.create_string(variant).map(|string| string.0)
}
fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<Self::Ok>
where
T: Serialize,
{
value.serialize(self)
}
fn serialize_newtype_variant<T: ?Sized>(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok>
where
T: Serialize,
{
let mut obj = self.0.create_object()?;
obj.set_named_property(variant, JsUnknown(value.serialize(self)?))?;
Ok(obj.0)
}
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
Ok(SeqSerializer {
array: self.0.create_array_with_length(len)?,
current_index: 0,
})
}
fn serialize_tuple_struct(
self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeTupleStruct> {
Ok(SeqSerializer {
array: self.0.create_array_with_length(len)?,
current_index: 0,
})
}
fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
Ok(StructSerializer {
obj: self.0.create_object()?,
})
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant> {
let mut outer = self.0.create_object()?;
let inner = self.0.create_object()?;
outer.set_named_property(
variant,
JsObject(Value {
env: inner.0.env,
value: inner.0.value,
value_type: ValueType::Object,
}),
)?;
Ok(StructSerializer {
obj: self.0.create_object()?,
})
}
More examples
pub fn create_empty_array(&self) -> Result<JsObject>
sourcepub fn create_array_with_length(&self, length: usize) -> Result<JsObject>
pub fn create_array_with_length(&self, length: usize) -> Result<JsObject>
Examples found in repository?
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
let array = self.0.create_array_with_length(len.unwrap_or(0))?;
Ok(SeqSerializer {
current_index: 0,
array,
})
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeTupleVariant> {
let env = self.0;
let array = env.create_array_with_length(len)?;
let mut object = env.create_object()?;
object.set_named_property(
variant,
JsObject(Value {
value: array.0.value,
env: array.0.env,
value_type: ValueType::Object,
}),
)?;
Ok(SeqSerializer {
current_index: 0,
array,
})
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
self.0.get_null().map(|null| null.0)
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok> {
self.0.create_string(variant).map(|string| string.0)
}
fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<Self::Ok>
where
T: Serialize,
{
value.serialize(self)
}
fn serialize_newtype_variant<T: ?Sized>(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok>
where
T: Serialize,
{
let mut obj = self.0.create_object()?;
obj.set_named_property(variant, JsUnknown(value.serialize(self)?))?;
Ok(obj.0)
}
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
Ok(SeqSerializer {
array: self.0.create_array_with_length(len)?,
current_index: 0,
})
}
fn serialize_tuple_struct(
self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeTupleStruct> {
Ok(SeqSerializer {
array: self.0.create_array_with_length(len)?,
current_index: 0,
})
}
sourcepub fn create_buffer(&self, length: usize) -> Result<JsBufferValue>
pub fn create_buffer(&self, length: usize) -> Result<JsBufferValue>
This API allocates a node::Buffer object. While this is still a fully-supported data structure, in most cases using a TypedArray will suffice.
sourcepub fn create_buffer_with_data(&self, data: Vec<u8>) -> Result<JsBufferValue>
pub fn create_buffer_with_data(&self, data: Vec<u8>) -> Result<JsBufferValue>
This API allocates a node::Buffer object and initializes it with data backed by the passed in buffer.
While this is still a fully-supported data structure, in most cases using a TypedArray will suffice.
sourcepub unsafe fn create_buffer_with_borrowed_data<Hint, Finalize>(
&self,
data: *const u8,
length: usize,
hint: Hint,
finalize_callback: Finalize
) -> Result<JsBufferValue>where
Finalize: FnOnce(Hint, Env),
pub unsafe fn create_buffer_with_borrowed_data<Hint, Finalize>(
&self,
data: *const u8,
length: usize,
hint: Hint,
finalize_callback: Finalize
) -> Result<JsBufferValue>where
Finalize: FnOnce(Hint, Env),
Safety
Mostly the same with create_buffer_with_data
Provided finalize_callback
will be called when Buffer
got dropped.
You can pass in noop_finalize
if you have nothing to do in finalize phase.
sourcepub fn adjust_external_memory(&mut self, size: i64) -> Result<i64>
pub fn adjust_external_memory(&mut self, size: i64) -> Result<i64>
This function gives V8 an indication of the amount of externally allocated memory that is kept alive by JavaScript objects (i.e. a JavaScript object that points to its own memory allocated by a native module).
Registering externally allocated memory will trigger global garbage collections more often than it would otherwise.
ATTENTION ⚠️, do not use this with create_buffer_with_data/create_arraybuffer_with_data
, since these two functions already called the adjust_external_memory
internal.
sourcepub fn create_buffer_copy<D>(&self, data_to_copy: D) -> Result<JsBufferValue>where
D: AsRef<[u8]>,
pub fn create_buffer_copy<D>(&self, data_to_copy: D) -> Result<JsBufferValue>where
D: AsRef<[u8]>,
This API allocates a node::Buffer object and initializes it with data copied from the passed-in buffer.
While this is still a fully-supported data structure, in most cases using a TypedArray will suffice.
pub fn create_arraybuffer(&self, length: usize) -> Result<JsArrayBufferValue>
pub fn create_arraybuffer_with_data(
&self,
data: Vec<u8>
) -> Result<JsArrayBufferValue>
sourcepub unsafe fn create_arraybuffer_with_borrowed_data<Hint, Finalize>(
&self,
data: *const u8,
length: usize,
hint: Hint,
finalize_callback: Finalize
) -> Result<JsArrayBufferValue>where
Finalize: FnOnce(Hint, Env),
pub unsafe fn create_arraybuffer_with_borrowed_data<Hint, Finalize>(
&self,
data: *const u8,
length: usize,
hint: Hint,
finalize_callback: Finalize
) -> Result<JsArrayBufferValue>where
Finalize: FnOnce(Hint, Env),
Safety
Mostly the same with create_arraybuffer_with_data
Provided finalize_callback
will be called when Buffer
got dropped.
You can pass in noop_finalize
if you have nothing to do in finalize phase.
sourcepub fn create_function(
&self,
name: &str,
callback: Callback
) -> Result<JsFunction>
pub fn create_function(
&self,
name: &str,
callback: Callback
) -> Result<JsFunction>
This API allows an add-on author to create a function object in native code.
This is the primary mechanism to allow calling into the add-on’s native code from JavaScript.
The newly created function is not automatically visible from script after this call.
Instead, a property must be explicitly set on any object that is visible to JavaScript, in order for the function to be accessible from script.
Examples found in repository?
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
unsafe fn from_napi_value(env: sys::napi_env, napi_val: sys::napi_value) -> crate::Result<Self> {
let mut signal = unsafe { JsObject::from_raw_unchecked(env, napi_val) };
let async_work_inner: Rc<AtomicPtr<sys::napi_async_work__>> =
Rc::new(AtomicPtr::new(ptr::null_mut()));
let raw_promise: Rc<AtomicPtr<sys::napi_deferred__>> = Rc::new(AtomicPtr::new(ptr::null_mut()));
let task_status = Rc::new(AtomicU8::new(0));
let abort_controller = AbortSignal {
raw_work: async_work_inner.clone(),
raw_deferred: raw_promise.clone(),
status: task_status.clone(),
};
let js_env = unsafe { Env::from_raw(env) };
check_status!(unsafe {
sys::napi_wrap(
env,
signal.0.value,
Box::into_raw(Box::new(abort_controller)) as *mut _,
Some(async_task_abort_controller_finalize),
ptr::null_mut(),
ptr::null_mut(),
)
})?;
signal.set_named_property("onabort", js_env.create_function("onabort", on_abort)?)?;
Ok(AbortSignal {
raw_work: async_work_inner,
raw_deferred: raw_promise,
status: task_status,
})
}
pub fn create_function_from_closure<R, F>(
&self,
name: &str,
callback: F
) -> Result<JsFunction>where
F: 'static + Fn(CallContext<'_>) -> Result<R>,
R: NapiRaw,
sourcepub fn get_last_error_info(&self) -> Result<ExtendedErrorInfo>
pub fn get_last_error_info(&self) -> Result<ExtendedErrorInfo>
This API retrieves a napi_extended_error_info structure with information about the last error that occurred.
The content of the napi_extended_error_info returned is only valid up until an n-api function is called on the same env.
Do not rely on the content or format of any of the extended information as it is not subject to SemVer and may change at any time. It is intended only for logging purposes.
This API can be called even if there is a pending JavaScript exception.
sourcepub fn throw_error(&self, msg: &str, code: Option<&str>) -> Result<()>
pub fn throw_error(&self, msg: &str, code: Option<&str>) -> Result<()>
This API throws a JavaScript Error with the text provided.
sourcepub fn throw_range_error(&self, msg: &str, code: Option<&str>) -> Result<()>
pub fn throw_range_error(&self, msg: &str, code: Option<&str>) -> Result<()>
This API throws a JavaScript RangeError with the text provided.
sourcepub fn throw_type_error(&self, msg: &str, code: Option<&str>) -> Result<()>
pub fn throw_type_error(&self, msg: &str, code: Option<&str>) -> Result<()>
This API throws a JavaScript TypeError with the text provided.
sourcepub fn throw_syntax_error(&self, msg: &str, code: Option<&str>) -> Result<()>
pub fn throw_syntax_error(&self, msg: &str, code: Option<&str>) -> Result<()>
This API throws a JavaScript SyntaxError with the text provided.
sourcepub fn fatal_error(self, location: &str, message: &str)
pub fn fatal_error(self, location: &str, message: &str)
In the event of an unrecoverable error in a native module
A fatal error can be thrown to immediately terminate the process.
sourcepub fn fatal_exception(&self, err: Error)
pub fn fatal_exception(&self, err: Error)
Trigger an ‘uncaughtException’ in JavaScript.
Useful if an async callback throws an exception with no way to recover.
sourcepub fn define_class(
&self,
name: &str,
constructor_cb: Callback,
properties: &[Property]
) -> Result<JsFunction>
pub fn define_class(
&self,
name: &str,
constructor_cb: Callback,
properties: &[Property]
) -> Result<JsFunction>
Create JavaScript class
pub fn wrap<T: 'static>(
&self,
js_object: &mut JsObject,
native_object: T
) -> Result<()>
pub fn unwrap<T: 'static>(&self, js_object: &JsObject) -> Result<&mut T>
pub fn unwrap_from_ref<T: 'static>(
&self,
js_ref: &Ref<()>
) -> Result<&'static mut T>
pub fn drop_wrapped<T: 'static>(&self, js_object: &mut JsObject) -> Result<()>
sourcepub fn create_reference<T>(&self, value: T) -> Result<Ref<()>>where
T: NapiRaw,
pub fn create_reference<T>(&self, value: T) -> Result<Ref<()>>where
T: NapiRaw,
This API create a new reference with the initial 1 ref count to the Object passed in.
sourcepub fn create_reference_with_refcount<T>(
&self,
value: T,
ref_count: u32
) -> Result<Ref<()>>where
T: NapiRaw,
pub fn create_reference_with_refcount<T>(
&self,
value: T,
ref_count: u32
) -> Result<Ref<()>>where
T: NapiRaw,
This API create a new reference with the specified reference count to the Object passed in.
sourcepub fn get_reference_value<T>(&self, reference: &Ref<()>) -> Result<T>where
T: NapiValue,
pub fn get_reference_value<T>(&self, reference: &Ref<()>) -> Result<T>where
T: NapiValue,
Get reference value from Ref
with type check
Return error if the type of reference
provided is mismatched with T
sourcepub fn get_reference_value_unchecked<T>(&self, reference: &Ref<()>) -> Result<T>where
T: NapiValue,
pub fn get_reference_value_unchecked<T>(&self, reference: &Ref<()>) -> Result<T>where
T: NapiValue,
Get reference value from Ref
without type check
Using this API if you are sure the type of T
is matched with provided Ref<()>
.
If type mismatched, calling T::method
would return Err
.
sourcepub fn create_external<T: 'static>(
&self,
native_object: T,
size_hint: Option<i64>
) -> Result<JsExternal>
pub fn create_external<T: 'static>(
&self,
native_object: T,
size_hint: Option<i64>
) -> Result<JsExternal>
If size_hint
provided, Env::adjust_external_memory
will be called under the hood.
If no size_hint
provided, global garbage collections will be triggered less times than expected.
If getting the exact native_object
size is difficult, you can provide an approximate value, it’s only effect to the GC.
pub fn get_value_external<T: 'static>(
&self,
js_external: &JsExternal
) -> Result<&mut T>
pub fn create_error(&self, e: Error) -> Result<JsObject>
sourcepub fn spawn<T: 'static + Task>(&self, task: T) -> Result<AsyncWorkPromise>
pub fn spawn<T: 'static + Task>(&self, task: T) -> Result<AsyncWorkPromise>
Run Task in libuv thread pool, return AsyncWorkPromise
pub fn run_in_scope<T, F>(&self, executor: F) -> Result<T>where
F: FnOnce() -> Result<T>,
pub fn run_script<S: AsRef<str>>(&self, script: S) -> Result<JsObject>
pub fn get_napi_version(&self) -> Result<u32>
pub fn get_uv_event_loop(&self) -> Result<*mut uv_loop_s>
pub fn add_env_cleanup_hook<T, F>(
&mut self,
cleanup_data: T,
cleanup_fn: F
) -> Result<CleanupEnvHook<T>>where
T: 'static,
F: 'static + FnOnce(T),
pub fn remove_env_cleanup_hook<T>(
&mut self,
hook: CleanupEnvHook<T>
) -> Result<()>where
T: 'static,
pub fn create_threadsafe_function<T: Send, V: ToNapiValue, R: 'static + Send + FnMut(ThreadSafeCallContext<T>) -> Result<Vec<V>>>(
&self,
func: &JsFunction,
max_queue_size: usize,
callback: R
) -> Result<ThreadsafeFunction<T>>
pub fn execute_tokio_future<T: 'static + Send, V: 'static + ToNapiValue, F: 'static + Send + Future<Output = Result<T>>, R: 'static + Send + Sync + FnOnce(&mut Env, T) -> Result<V>>(
&self,
fut: F,
resolver: R
) -> Result<JsObject>
sourcepub fn create_deferred<Data: ToNapiValue, Resolver: FnOnce(Env) -> Result<Data>>(
&self
) -> Result<(JsDeferred<Data, Resolver>, JsObject)>
pub fn create_deferred<Data: ToNapiValue, Resolver: FnOnce(Env) -> Result<Data>>(
&self
) -> Result<(JsDeferred<Data, Resolver>, JsObject)>
Creates a deferred promise, which can be resolved or rejected from a background thread.
sourcepub fn create_date(&self, time: f64) -> Result<JsDate>
pub fn create_date(&self, time: f64) -> Result<JsDate>
This API does not observe leap seconds; they are ignored, as ECMAScript aligns with POSIX time specification.
This API allocates a JavaScript Date object.
JavaScript Date objects are described in Section 20.3 of the ECMAScript Language Specification.
sourcepub fn set_instance_data<T, Hint, F>(
&self,
native: T,
hint: Hint,
finalize_cb: F
) -> Result<()>where
T: 'static,
Hint: 'static,
F: FnOnce(FinalizeContext<T, Hint>),
pub fn set_instance_data<T, Hint, F>(
&self,
native: T,
hint: Hint,
finalize_cb: F
) -> Result<()>where
T: 'static,
Hint: 'static,
F: FnOnce(FinalizeContext<T, Hint>),
This API associates data with the currently running Agent. data can later be retrieved using Env::get_instance_data()
.
Any existing data associated with the currently running Agent which was set by means of a previous call to Env::set_instance_data()
will be overwritten.
If a finalize_cb
was provided by the previous call, it will not be called.
sourcepub fn get_instance_data<T>(&self) -> Result<Option<&'static mut T>>where
T: 'static,
pub fn get_instance_data<T>(&self) -> Result<Option<&'static mut T>>where
T: 'static,
This API retrieves data that was previously associated with the currently running Agent via Env::set_instance_data()
.
If no data is set, the call will succeed and data will be set to NULL.
sourcepub fn add_removable_async_cleanup_hook<Arg, F>(
&self,
arg: Arg,
cleanup_fn: F
) -> Result<AsyncCleanupHook>where
F: FnOnce(Arg),
Arg: 'static,
pub fn add_removable_async_cleanup_hook<Arg, F>(
&self,
arg: Arg,
cleanup_fn: F
) -> Result<AsyncCleanupHook>where
F: FnOnce(Arg),
Arg: 'static,
Registers hook, which is a function of type FnOnce(Arg)
, as a function to be run with the arg
parameter once the current Node.js environment exits.
Unlike add_env_cleanup_hook
, the hook is allowed to be asynchronous.
Otherwise, behavior generally matches that of add_env_cleanup_hook
.
sourcepub fn add_async_cleanup_hook<Arg, F>(
&self,
arg: Arg,
cleanup_fn: F
) -> Result<()>where
F: FnOnce(Arg),
Arg: 'static,
pub fn add_async_cleanup_hook<Arg, F>(
&self,
arg: Arg,
cleanup_fn: F
) -> Result<()>where
F: FnOnce(Arg),
Arg: 'static,
This API is very similar to add_removable_async_cleanup_hook
Use this one if you don’t want remove the cleanup hook anymore.
sourcepub fn to_js_value<T>(&self, node: &T) -> Result<JsUnknown>where
T: Serialize,
pub fn to_js_value<T>(&self, node: &T) -> Result<JsUnknown>where
T: Serialize,
Serialize Rust Struct
into JavaScript Value
#[derive(Serialize, Debug, Deserialize)]
struct AnObject {
a: u32,
b: Vec<f64>,
c: String,
}
#[js_function]
fn serialize(ctx: CallContext) -> Result<JsUnknown> {
let value = AnyObject { a: 1, b: vec![0.1, 2.22], c: "hello" };
ctx.env.to_js_value(&value)
}
sourcepub fn from_js_value<T, V>(&self, value: V) -> Result<T>where
T: DeserializeOwned + ?Sized,
V: NapiRaw,
pub fn from_js_value<T, V>(&self, value: V) -> Result<T>where
T: DeserializeOwned + ?Sized,
V: NapiRaw,
Deserialize data from JsValue
#[derive(Serialize, Debug, Deserialize)]
struct AnObject {
a: u32,
b: Vec<f64>,
c: String,
}
#[js_function(1)]
fn deserialize_from_js(ctx: CallContext) -> Result<JsUndefined> {
let arg0 = ctx.get::<JsUnknown>(0)?;
let de_serialized: AnObject = ctx.env.from_js_value(arg0)?;
...
}
sourcepub fn strict_equals<A: NapiRaw, B: NapiRaw>(&self, a: A, b: B) -> Result<bool>
pub fn strict_equals<A: NapiRaw, B: NapiRaw>(&self, a: A, b: B) -> Result<bool>
This API represents the invocation of the Strict Equality algorithm as defined in Section 7.2.14 of the ECMAScript Language Specification.
pub fn get_node_version(&self) -> Result<NodeVersion>
sourcepub fn raw(&self) -> napi_env
pub fn raw(&self) -> napi_env
get raw env ptr
Examples found in repository?
More examples
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
pub fn execute_tokio_future<
Data: 'static + Send,
Fut: 'static + Send + Future<Output = Result<Data>>,
Resolver: 'static + Send + Sync + FnOnce(sys::napi_env, Data) -> Result<sys::napi_value>,
>(
env: sys::napi_env,
fut: Fut,
resolver: Resolver,
) -> Result<sys::napi_value> {
let mut promise = ptr::null_mut();
let mut deferred = ptr::null_mut();
check_status!(unsafe { sys::napi_create_promise(env, &mut deferred, &mut promise) })?;
let (deferred, promise) = JsDeferred::new(env)?;
spawn(async move {
match fut.await {
Ok(v) => deferred.resolve(|env| {
resolver(env.raw(), v).map(|v| unsafe { JsUnknown::from_raw_unchecked(env.raw(), v) })
}),
Err(e) => deferred.reject(e),
}
});
Ok(promise.0.value)
}