perspective_js/
typed_array.rs1use js_sys::{
14 Array, Float32Array, Float64Array, Function, Int32Array, JsString, Promise, Uint8Array,
15 Uint32Array,
16};
17use perspective_client::{TypedArrayColumn, TypedArrayValues};
18use wasm_bindgen::JsCast;
19use wasm_bindgen::prelude::*;
20use wasm_bindgen_futures::JsFuture;
21
22use crate::utils::ApiResult;
23
24#[wasm_bindgen]
25unsafe extern "C" {
26 #[wasm_bindgen(typescript_type = "TypedArrayWindow")]
27 #[derive(Clone)]
28 pub type JsTypedArrayWindow;
29}
30
31pub(crate) async fn call_with_typed_arrays(
34 columns: &[TypedArrayColumn],
35 callback: &Function,
36) -> ApiResult<()> {
37 let names = Array::new();
38 let values = Array::new();
39 let validities = Array::new();
40 let dictionaries = Array::new();
41 for column in columns {
42 names.push(&JsString::from(column.name.as_str()));
43 values.push(&values_view(&column.values));
44 validities.push(&column.validity.as_ref().map_or(JsValue::NULL, |validity| {
45 unsafe { Uint8Array::view(validity.as_slice()) }.into()
46 }));
47
48 dictionaries.push(&dictionary(&column.values));
49 }
50
51 let ret = callback.call4(
52 &JsValue::UNDEFINED,
53 &names,
54 &values,
55 &validities,
56 &dictionaries,
57 )?;
58
59 if let Some(promise) = ret.dyn_ref::<Promise>() {
60 JsFuture::from(promise.clone()).await?;
61 }
62
63 Ok(())
64}
65
66fn values_view(values: &TypedArrayValues) -> JsValue {
67 unsafe {
68 match values {
69 TypedArrayValues::Int32(values) => Int32Array::view(values).into(),
70 TypedArrayValues::UInt32(values) => Uint32Array::view(values).into(),
71 TypedArrayValues::Float32(values) => Float32Array::view(values).into(),
72 TypedArrayValues::Float64(values) => Float64Array::view(values).into(),
73 TypedArrayValues::Dictionary { keys, .. } => Int32Array::view(keys).into(),
74 }
75 }
76}
77
78fn dictionary(values: &TypedArrayValues) -> JsValue {
79 match values {
80 TypedArrayValues::Dictionary { values, .. } => values
81 .iter()
82 .map(|value| JsValue::from_str(value))
83 .collect::<Array>()
84 .into(),
85 _ => JsValue::NULL,
86 }
87}