napi-rs/napi/src/call_context.rs

36 lines
817 B
Rust
Raw Normal View History

use crate::{sys, Any, Env, Error, Result, Status, Value, ValueType};
2020-04-21 01:20:35 +09:00
pub struct CallContext<T: ValueType = Any> {
pub env: Env,
pub this: Value<T>,
2020-04-21 01:20:35 +09:00
args: [sys::napi_value; 8],
arg_len: usize,
}
impl<T: ValueType> CallContext<T> {
pub fn new(
env: Env,
this: sys::napi_value,
args: [sys::napi_value; 8],
arg_len: usize,
) -> Result<Self> {
Ok(Self {
env,
this: Value::<T>::from_raw(env.0, this)?,
args,
arg_len,
})
2020-04-21 01:20:35 +09:00
}
pub fn get<ArgType: ValueType>(&self, index: usize) -> Result<Value<ArgType>> {
2020-04-21 01:20:35 +09:00
if index + 1 > self.arg_len {
Err(Error {
status: Status::GenericFailure,
reason: Some("Arguments index out of range".to_owned()),
})
2020-04-21 01:20:35 +09:00
} else {
Value::<ArgType>::from_raw(self.env.0, self.args[index])
2020-04-21 01:20:35 +09:00
}
}
}