From 831e050877ea64c9a7c26041ab8678c432aaf3ba Mon Sep 17 00:00:00 2001 From: LongYinan Date: Tue, 7 Dec 2021 21:50:15 +0800 Subject: [PATCH] feat(napi): create Array from &Vec --- .../src/bindgen_runtime/js_values/array.rs | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/crates/napi/src/bindgen_runtime/js_values/array.rs b/crates/napi/src/bindgen_runtime/js_values/array.rs index e8c21dbe..1e4b057d 100644 --- a/crates/napi/src/bindgen_runtime/js_values/array.rs +++ b/crates/napi/src/bindgen_runtime/js_values/array.rs @@ -118,6 +118,7 @@ impl FromNapiValue for Array { } impl Array { + /// Create `Array` from `Vec` pub fn from_vec(env: &Env, value: Vec) -> Result where T: ToNapiValue, @@ -129,6 +130,29 @@ impl Array { })?; Ok(arr) } + + /// Create `Array` from `&Vec` + pub fn from_ref_vec_string(env: &Env, value: &[String]) -> Result { + let mut arr = Array::new(env.0, value.len() as u32)?; + value.iter().enumerate().try_for_each(|(index, val)| { + arr.set(index as u32, val.as_str())?; + Ok::<(), Error>(()) + })?; + Ok(arr) + } + + /// Create `Array` from `&Vec` + pub fn from_ref_vec(env: &Env, value: &[T]) -> Result + where + T: ToNapiValue + Copy, + { + let mut arr = Array::new(env.0, value.len() as u32)?; + value.iter().enumerate().try_for_each(|(index, val)| { + arr.set(index as u32, *val)?; + Ok::<(), Error>(()) + })?; + Ok(arr) + } } impl ValidateNapiValue for Array { @@ -162,6 +186,40 @@ where } } +macro_rules! impl_for_primitive_type { + ($primitive_type:ident) => { + impl ToNapiValue for &Vec<$primitive_type> { + unsafe fn to_napi_value(env: sys::napi_env, val: Self) -> Result { + let mut arr = Array::new(env, val.len() as u32)?; + + for (i, v) in val.iter().enumerate() { + arr.set(i as u32, *v)?; + } + + Array::to_napi_value(env, arr) + } + } + }; +} + +impl_for_primitive_type!(u32); +impl_for_primitive_type!(i32); +impl_for_primitive_type!(i64); +impl_for_primitive_type!(f64); +impl_for_primitive_type!(bool); + +impl ToNapiValue for &Vec { + unsafe fn to_napi_value(env: sys::napi_env, val: Self) -> Result { + let mut arr = Array::new(env, val.len() as u32)?; + + for (i, v) in val.iter().enumerate() { + arr.set(i as u32, v.as_str())?; + } + + Array::to_napi_value(env, arr) + } +} + impl FromNapiValue for Vec where T: FromNapiValue,