Skip to main content

perspective_js/
typed_array.rs

1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
3// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
4// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
5// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
6// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7// ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
8// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9// ┃ This file is part of the Perspective library, distributed under the terms ┃
10// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
13use 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
31#[wasm_bindgen(inline_js = "
32    export function split_strings(text, ends) {
33        const out = new Array(ends.length);
34        let start = 0;
35        for (let i = 0; i < ends.length; i++) {
36            out[i] = text.substring(start, ends[i]);
37            start = ends[i];
38        }
39
40        return out;
41    }
42")]
43extern "C" {
44    fn split_strings(text: &str, ends: &Uint32Array) -> Array;
45}
46
47/// Calls `callback` with zero-copy JS views of `columns`, awaiting a returned
48/// `Promise` before the views are released.
49pub(crate) async fn call_with_typed_arrays(
50    columns: &[TypedArrayColumn],
51    callback: &Function,
52) -> ApiResult<()> {
53    let names = Array::new();
54    let values = Array::new();
55    let validities = Array::new();
56    let dictionaries = Array::new();
57    for column in columns {
58        names.push(&JsString::from(column.name.as_str()));
59        values.push(&values_view(&column.values));
60        validities.push(&column.validity.as_ref().map_or(JsValue::NULL, |validity| {
61            unsafe { Uint8Array::view(validity.as_slice()) }.into()
62        }));
63
64        dictionaries.push(&dictionary(&column.values));
65    }
66
67    let ret = callback.call4(
68        &JsValue::UNDEFINED,
69        &names,
70        &values,
71        &validities,
72        &dictionaries,
73    )?;
74
75    if let Some(promise) = ret.dyn_ref::<Promise>() {
76        JsFuture::from(promise.clone()).await?;
77    }
78
79    Ok(())
80}
81
82fn values_view(values: &TypedArrayValues) -> JsValue {
83    unsafe {
84        match values {
85            TypedArrayValues::Int32(values) => Int32Array::view(values).into(),
86            TypedArrayValues::UInt32(values) => Uint32Array::view(values).into(),
87            TypedArrayValues::Float32(values) => Float32Array::view(values).into(),
88            TypedArrayValues::Float64(values) => Float64Array::view(values).into(),
89            TypedArrayValues::Dictionary { keys, .. } => Int32Array::view(keys).into(),
90        }
91    }
92}
93
94/// The strings of a dictionary column as a JS `Array`, passed to JS as one
95/// string and split there to avoid decoding each separately.
96fn dictionary(values: &TypedArrayValues) -> JsValue {
97    let TypedArrayValues::Dictionary { values, .. } = values else {
98        return JsValue::NULL;
99    };
100
101    let mut text = String::with_capacity(values.iter().map(String::len).sum());
102    let mut ends = Vec::with_capacity(values.len());
103    let mut end = 0;
104    for value in values {
105        text.push_str(value);
106        end += if value.is_ascii() {
107            value.len() as u32
108        } else {
109            value.encode_utf16().count() as u32
110        };
111
112        ends.push(end);
113    }
114
115    split_strings(&text, &Uint32Array::from(ends.as_slice())).into()
116}