feat(napi): implement as_unknown and validate for Either types (#1285)

This commit is contained in:
LongYinan 2022-08-23 17:02:51 +08:00 committed by GitHub
parent 49ec8917df
commit f7c00c9a90
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,7 +1,7 @@
use super::{FromNapiValue, ToNapiValue, TypeName, ValidateNapiValue};
use crate::{
bindgen_runtime::{Null, Undefined},
sys, Error, JsUndefined, NapiRaw, Status, ValueType,
bindgen_runtime::{Null, Undefined, Unknown},
sys, Env, Error, JsUndefined, NapiRaw, NapiValue, Status, ValueType,
};
#[derive(Debug, Clone, Copy)]
@ -21,6 +21,15 @@ impl<A: NapiRaw, B: NapiRaw> Either<A, B> {
}
}
impl<A: ValidateNapiValue, B: ValidateNapiValue> ValidateNapiValue for Either<A, B> {
unsafe fn validate(
env: sys::napi_env,
napi_val: sys::napi_value,
) -> crate::Result<sys::napi_value> {
unsafe { A::validate(env, napi_val).or_else(|_| B::validate(env, napi_val)) }
}
}
impl<A: TypeName, B: TypeName> TypeName for Either<A, B> {
fn type_name() -> &'static str {
"Either"
@ -128,7 +137,7 @@ macro_rules! either_n {
Status::InvalidArg,
format!(
concat!("Value is non of these types ", $( "`{", stringify!( $parameter ), "}`, " ),+ ),
$( $parameter = $parameter::value_type(), )+
$( $parameter = $parameter::type_name(), )+
),
))
}
@ -147,6 +156,38 @@ macro_rules! either_n {
}
}
}
impl< $( $parameter ),+ > ValidateNapiValue for $either_name < $( $parameter ),+ >
where $( $parameter: ValidateNapiValue ),+
{
unsafe fn validate(
env: sys::napi_env,
napi_val: sys::napi_value,
) -> crate::Result<sys::napi_value> {
let mut ret: crate::Result<sys::napi_value>;
$(
if unsafe {
ret = $parameter::validate(env, napi_val);
ret.is_ok()
} {
ret
} else
)+
{
ret
}
}
}
impl< $( $parameter ),+ > $either_name < $( $parameter ),+ >
where $( $parameter: NapiRaw ),+
{
pub fn as_unknown(&self, env: Env) -> Unknown {
match &self {
$( Self:: $parameter (v) => unsafe { Unknown::from_raw_unchecked(env.raw(), v.raw()) } ),+
}
}
}
};
}