From f7c00c9a90b9174da0d075a82fb530c3dd74dd62 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Tue, 23 Aug 2022 17:02:51 +0800 Subject: [PATCH] feat(napi): implement as_unknown and validate for Either types (#1285) --- .../src/bindgen_runtime/js_values/either.rs | 47 +++++++++++++++++-- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/crates/napi/src/bindgen_runtime/js_values/either.rs b/crates/napi/src/bindgen_runtime/js_values/either.rs index c1ead47f..38fa5064 100644 --- a/crates/napi/src/bindgen_runtime/js_values/either.rs +++ b/crates/napi/src/bindgen_runtime/js_values/either.rs @@ -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 Either { } } +impl ValidateNapiValue for Either { + unsafe fn validate( + env: sys::napi_env, + napi_val: sys::napi_value, + ) -> crate::Result { + unsafe { A::validate(env, napi_val).or_else(|_| B::validate(env, napi_val)) } + } +} + impl TypeName for Either { 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 { + let mut ret: crate::Result; + $( + 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()) } ),+ + } + } + } }; }