feat(napi): create Array from &Vec

This commit is contained in:
LongYinan 2021-12-07 21:50:15 +08:00
parent ff717df34f
commit 831e050877
No known key found for this signature in database
GPG key ID: C3666B7FC82ADAD7

View file

@ -118,6 +118,7 @@ impl FromNapiValue for Array {
} }
impl Array { impl Array {
/// Create `Array` from `Vec<T>`
pub fn from_vec<T>(env: &Env, value: Vec<T>) -> Result<Self> pub fn from_vec<T>(env: &Env, value: Vec<T>) -> Result<Self>
where where
T: ToNapiValue, T: ToNapiValue,
@ -129,6 +130,29 @@ impl Array {
})?; })?;
Ok(arr) Ok(arr)
} }
/// Create `Array` from `&Vec<String>`
pub fn from_ref_vec_string(env: &Env, value: &[String]) -> Result<Self> {
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<T: Copy + ToNapiValue>`
pub fn from_ref_vec<T>(env: &Env, value: &[T]) -> Result<Self>
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 { 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<sys::napi_value> {
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<String> {
unsafe fn to_napi_value(env: sys::napi_env, val: Self) -> Result<sys::napi_value> {
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<T> FromNapiValue for Vec<T> impl<T> FromNapiValue for Vec<T>
where where
T: FromNapiValue, T: FromNapiValue,