maia_wasm/
array_view.rs

1//! Transformation of Rust arrays to JS.
2
3use js_sys::{Float32Array, Object, Uint8Array, Uint16Array};
4use std::ops::Deref;
5use web_sys::WebGl2RenderingContext;
6
7/// Idiomatic transformation of Rust arrays to JS.
8///
9/// This trait gives an idiomatic way to transform Rust arrays into a JS typed
10/// array (such as [`Float32Array`]) specifically for the use case of filling
11/// WebGL2 buffers and textures.
12///
13/// For this, each Rust numeric type is associated with a JS typed array type
14/// and with a constant that gives the corresponding WebGL2 data type (such as
15/// `WebGL2RenderingContext::FLOAT`).
16pub trait ArrayView: Sized {
17    /// The associated JS typed array.
18    type JS: Deref<Target = Object>;
19    /// The associated WebGL2 data type.
20    const GL_TYPE: u32;
21    /// Creates a JS typed array which is a view into wasm's linear memory at
22    /// the slice specified.
23    ///
24    /// This function uses the `view` method (such as [`Float32Array::view`]) of
25    /// the JS typed array.
26    ///
27    /// # Safety
28    ///
29    /// The same safety considerations as with [`Float32Array::view`] apply.
30    unsafe fn view(rust: &[Self]) -> Self::JS;
31}
32
33macro_rules! impl_array_view {
34    ($rust:ty, $js:ty, $gl:expr) => {
35        impl ArrayView for $rust {
36            type JS = $js;
37            const GL_TYPE: u32 = $gl;
38            unsafe fn view(rust: &[$rust]) -> $js {
39                unsafe { <$js>::view(rust) }
40            }
41        }
42    };
43}
44
45impl_array_view!(f32, Float32Array, WebGl2RenderingContext::FLOAT);
46impl_array_view!(u16, Uint16Array, WebGl2RenderingContext::UNSIGNED_INT);
47impl_array_view!(u8, Uint8Array, WebGl2RenderingContext::UNSIGNED_BYTE);