napi-rs/napi/src/call_context.rs

72 lines
1.8 KiB
Rust
Raw Normal View History

use std::ptr;
use crate::error::check_status;
2020-07-18 03:00:48 +09:00
use crate::{sys, Either, Env, Error, JsUndefined, JsUnknown, NapiValue, Result, Status};
2020-04-21 01:20:35 +09:00
pub struct CallContext<'env, T: NapiValue = JsUnknown> {
2020-05-09 16:14:44 +09:00
pub env: &'env Env,
pub this: T,
callback_info: sys::napi_callback_info,
args: &'env [sys::napi_value],
2020-04-21 01:20:35 +09:00
arg_len: usize,
2020-07-18 03:00:48 +09:00
actual_arg_length: usize,
2020-04-21 01:20:35 +09:00
}
impl<'env, T: NapiValue> CallContext<'env, T> {
2020-05-09 16:14:44 +09:00
#[inline]
pub fn new(
2020-05-09 16:14:44 +09:00
env: &'env Env,
callback_info: sys::napi_callback_info,
this: sys::napi_value,
args: &'env [sys::napi_value],
arg_len: usize,
2020-07-18 03:00:48 +09:00
actual_arg_length: usize,
) -> Result<Self> {
Ok(Self {
env,
callback_info,
this: T::from_raw(env.0, this)?,
args,
arg_len,
2020-07-18 03:00:48 +09:00
actual_arg_length,
})
2020-04-21 01:20:35 +09:00
}
2020-05-09 16:14:44 +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 {
ArgType::from_raw(self.env.0, self.args[index])
2020-04-21 01:20:35 +09:00
}
}
2020-07-18 03:00:48 +09:00
#[inline]
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(),
})
} else {
if index < self.actual_arg_length {
ArgType::from_raw(self.env.0, self.args[index]).map(Either::A)
} else {
self.env.get_undefined().map(Either::B)
}
}
}
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) })?;
V::from_raw(self.env.0, value)
}
2020-04-21 01:20:35 +09:00
}