* The MIT License (MIT)
* Copyright (C) 2024 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*/
use std::ptr;
use crate::bindgen_runtime::{FromNapiValue, TypeName};
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],
pub length: usize,
}
impl<'env> CallContext<'env> {
fn arg_len(&self) -> usize {
self.args.len()
}
pub fn new(
env: &'env mut Env,
callback_info: sys::napi_callback_info,
raw_this: sys::napi_value,
args: &'env [sys::napi_value],
length: usize,
) -> Self {
Self {
env,
raw_this,
callback_info,
args,
length,
}
}
pub fn get<ArgType: FromNapiValue>(&self, index: usize) -> Result<ArgType> {
if index >= self.arg_len() {
Err(Error::new(
Status::GenericFailure,
"Arguments index out of range".to_owned(),
))
} else {
unsafe { ArgType::from_napi_value(self.env.0, self.args[index]) }
}
}
pub fn try_get<ArgType: NapiValue + TypeName + FromNapiValue>(
&self,
index: usize,
) -> Result<Either<ArgType, JsUndefined>> {
if index >= self.arg_len() {
Err(Error::new(
Status::GenericFailure,
"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)
}
}
pub fn get_all(&self) -> Vec<crate::JsUnknown> {
self
.args
.iter()
.map(|&raw| unsafe { crate::JsUnknown::from_raw_unchecked(self.env.0, raw) })
.collect()
}
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) }
}
pub fn this<T: NapiValue>(&self) -> Result<T> {
unsafe { T::from_raw(self.env.0, self.raw_this) }
}
pub fn this_unchecked<T: NapiValue>(&self) -> T {
unsafe { T::from_raw_unchecked(self.env.0, self.raw_this) }
}
}