I am trying to convert Javascript object: { attributes: {a: "b", b: "x", x: 700} }
to Polars
DataType::Struct
using the following Rust napi code:
#![deny(clippy::all)]
#[macro_use]
extern crate napi_derive;
use napi::{Env, JsUnknown, Result};
use polars::datatypes::Field;
use polars::prelude::{AnyValue, CompatLevel, DataType};
use polars_core::utils::arrow::array::{Array, StructArray, Utf8Array};
#[napi]
fn create_struct(env: Env, string: String) -> Result<JsUnknown> {
let js_string = env.create_string(&string)?;
let unknown = js_string.into_unknown();
let fields = vec![
Field::new("a".into(), DataType::String),
Field::new("b".into(), DataType::String),
Field::new("x".into(), DataType::Int32),
];
println!("Fields: {:?}", fields);
let number_of_fields: i8 = fields.len().try_into().map_err(
|e| napi::Error::from_reason(format!("the number of `fields` cannot be larger than i8::MAX {e:?}"))
)?;
let mut val_vec = Vec::with_capacity(number_of_fields as usize);
let _inner_val: napi::JsObject = unsafe { unknown.cast() };
fields.iter().for_each(|fld| {
// let single_val = inner_val.get::<_, napi::JsUnknown>(&fld.name).unwrap().unwrap();
let vv = match fld.dtype {
DataType::String =>
{
// Utf8Array::<i32>::from([Some(single_val.coerce_to_string().into_ok())]).boxed()
Utf8Array::<i32>::from([Some("s")]).boxed()
},
_ => Utf8Array::<i32>::from([Some("o")]).boxed()
};
val_vec.push(vv);
});
println!("number_of_fields: {:?} Val vev: {:?}", number_of_fields, val_vec);
let dtype = DataType::Struct(fields);
let arrow_dtype = dtype.to_physical().to_arrow(CompatLevel::newest());
// let arr = unsafe { &*(val_vec.as_slice() as *const dyn Array as *const StructArray) };
// let arr = Box::new(StructArray::new(
// arrow_dtype,
// number_of_fields as usize,
// arr,
// None,
// ));
// let str = AnyValue::Struct(number_of_fields.try_into().unwrap(), &Box::new(&arr), &fields);
Ok(js_string.into_unknown())
}
But unfortunately I am unable to create AnyValue::Struct
object.
Does anyone know the correct syntax? Thx