napi-rs/napi/src/call_context.rs

38 lines
844 B
Rust
Raw Normal View History

use crate::{sys, Env, Error, 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,
args: &'env [sys::napi_value],
2020-04-21 01:20:35 +09:00
arg_len: usize,
}
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,
this: sys::napi_value,
args: &'env [sys::napi_value],
arg_len: usize,
) -> Result<Self> {
Ok(Self {
env,
this: T::from_raw(env.0, this)?,
args,
arg_len,
})
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
}
}
}