1
2
3
4
5
6
7
8
9
10
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
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
use std::ptr;
use crate::check_status;
use crate::{sys, Either, Env, Error, JsUndefined, NapiValue, Result, Status};
pub struct CallContext<'env> {
pub env: &'env mut Env,
raw_this: sys::napi_value,
callback_info: sys::napi_callback_info,
args: &'env [sys::napi_value],
arg_len: usize,
pub length: usize,
}
impl<'env> CallContext<'env> {
#[inline]
pub fn new(
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,
}
}
#[inline]
pub fn get<ArgType: NapiValue>(&self, index: usize) -> Result<ArgType> {
if index + 1 > self.arg_len {
Err(Error {
status: Status::GenericFailure,
reason: "Arguments index out of range".to_owned(),
})
} else {
Ok(unsafe { ArgType::from_raw_unchecked(self.env.0, self.args[index]) })
}
}
#[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.length {
unsafe { ArgType::from_raw(self.env.0, self.args[index]) }.map(Either::A)
} else {
self.env.get_undefined().map(Either::B)
}
}
#[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) }
}
}