napi-rs/napi/src/call_context.rs

83 lines
2 KiB
Rust
Raw Normal View History

use std::ptr;
use crate::check_status;
use crate::{sys, Either, Env, Error, JsUndefined, NapiValue, Result, Status};
2020-04-21 01:20:35 +09:00
/// Function call context
pub struct CallContext<'env> {
2020-10-04 17:02:04 +09:00
pub env: &'env mut Env,
raw_this: sys::napi_value,
callback_info: sys::napi_callback_info,
args: &'env [sys::napi_value],
2020-04-21 01:20:35 +09:00
arg_len: usize,
/// arguments.length
pub length: usize,
2020-04-21 01:20:35 +09:00
}
impl<'env> CallContext<'env> {
#[inline]
pub fn new(
2020-10-04 17:02:04 +09:00
env: &'env mut Env,
callback_info: sys::napi_callback_info,
raw_this: sys::napi_value,
args: &'env [sys::napi_value],
arg_len: usize,
length: usize,
) -> Self {
Self {
env,
callback_info,
raw_this,
args,
arg_len,
length,
}
2020-04-21 01:20:35 +09:00
}
#[inline]
pub fn get<ArgType: NapiValue>(&self, index: usize) -> Result<ArgType> {
2020-04-21 01:20:35 +09:00
if index + 1 > self.arg_len {
Err(Error {
status: Status::GenericFailure,
reason: "Arguments index out of range".to_owned(),
})
2020-04-21 01:20:35 +09:00
} else {
Ok(unsafe { ArgType::from_raw_unchecked(self.env.0, self.args[index]) })
2020-04-21 01:20:35 +09:00
}
}
2020-07-18 03:00:48 +09:00
#[inline]
2020-07-18 03:00:48 +09:00
pub fn try_get<ArgType: NapiValue>(&self, index: usize) -> Result<Either<ArgType, JsUndefined>> {
if index + 1 > self.arg_len {
Err(Error {
status: Status::GenericFailure,
reason: "Arguments index out of range".to_owned(),
})
2020-12-01 15:55:19 +09:00
} else if index < self.length {
unsafe { ArgType::from_raw(self.env.0, self.args[index]) }.map(Either::A)
2020-07-18 03:00:48 +09:00
} else {
2020-12-01 15:55:19 +09:00
self.env.get_undefined().map(Either::B)
2020-07-18 03:00:48 +09:00
}
}
#[inline]
pub fn get_new_target<V>(&self) -> Result<V>
where
V: NapiValue,
{
let mut value = ptr::null_mut();
check_status!(unsafe { sys::napi_get_new_target(self.env.0, self.callback_info, &mut value) })?;
unsafe { V::from_raw(self.env.0, value) }
}
#[inline]
pub fn this<T: NapiValue>(&self) -> Result<T> {
unsafe { T::from_raw(self.env.0, self.raw_this) }
}
#[inline]
pub fn this_unchecked<T: NapiValue>(&self) -> T {
unsafe { T::from_raw_unchecked(self.env.0, self.raw_this) }
}
2020-04-21 01:20:35 +09:00
}