From f83e167bd25c6971d3e4cc8af5cc8785508ee220 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Mon, 22 Nov 2021 18:31:51 +0800 Subject: [PATCH] feat(napi): implement `from_vec` for Array --- crates/backend/src/codegen/const.rs | 3 ++- .../napi/src/bindgen_runtime/js_values/array.rs | 17 ++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/backend/src/codegen/const.rs b/crates/backend/src/codegen/const.rs index cddad455..698abbd5 100644 --- a/crates/backend/src/codegen/const.rs +++ b/crates/backend/src/codegen/const.rs @@ -26,8 +26,9 @@ impl NapiConst { &format!("__register__const__{}_callback__", register_name), self.name.span(), ); - quote! { + #[allow(non_snake_case)] + #[allow(clippy::all)] unsafe fn #cb_name(env: napi::sys::napi_env) -> napi::Result { <#type_name as napi::bindgen_prelude::ToNapiValue>::to_napi_value(env, #name_ident) } diff --git a/crates/napi/src/bindgen_runtime/js_values/array.rs b/crates/napi/src/bindgen_runtime/js_values/array.rs index 3d9587f4..ae9c5c9f 100644 --- a/crates/napi/src/bindgen_runtime/js_values/array.rs +++ b/crates/napi/src/bindgen_runtime/js_values/array.rs @@ -1,6 +1,7 @@ -use crate::{bindgen_prelude::*, check_status, sys, ValueType}; use std::ptr; +use crate::{bindgen_prelude::*, check_status, sys, ValueType}; + pub struct Array { env: sys::napi_env, inner: sys::napi_value, @@ -116,6 +117,20 @@ impl FromNapiValue for Array { } } +impl Array { + pub fn from_vec(env: &Env, value: Vec) -> Result + where + T: ToNapiValue, + { + let mut arr = Array::new(env.0, value.len() as u32)?; + value.into_iter().try_for_each(|val| { + arr.insert(val)?; + Ok::<(), Error>(()) + })?; + Ok(arr) + } +} + impl ValidateNapiValue for Array { fn type_of() -> Vec { vec![ValueType::Object]