Boxed Number Slices - The wasm-bindgen
Guide (original) (raw)
The `wasm-bindgen` Guide
Boxed Number Slices: Box<[u8]>, Box<[i8]>, Box<[u16]>, Box<[i16]>, Box<[u32]>, Box<[i32]>, Box<[u64]>, Box<[i64]>, Box<[f32]>, Box<[f64]>, Box<[MaybeUninit]>, Box<[MaybeUninit]>, Box<[MaybeUninit]>, Box<[MaybeUninit]>, Box<[MaybeUninit]>, Box<[MaybeUninit]>, Box<[MaybeUninit]>, Box<[MaybeUninit]>, Box<[MaybeUninit]>, and Box<[MaybeUninit]>
T parameter | &T parameter | &mut T parameter | T return value | Option parameter | Option return value | JavaScript representation |
---|---|---|---|---|---|---|
Yes | No | No | Yes | Yes | Yes | A JavaScript TypedArray of the appropriate type (Int32Array, Uint8Array, etc...) |
Note: The contents of the slice are copied into a JavaScript TypedArrayfrom the Wasm linear memory when returning a boxed slice to JavaScript, and vice versa when receiving a JavaScript
TypedArray
as a boxed slice in Rust.
Note: Numeric
MaybeUninit<T>
can always be assumed to be initialized upon transmission from Rust to JS and vice-versa. However, uninitialized values coming from Rust might contain unspecified values.
Example Rust Usage
#![allow(unused)]
fn main() {
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn take_boxed_number_slice_by_value(x: Box<[f64]>) {}
#[wasm_bindgen]
pub fn return_boxed_number_slice() -> Box<[u32]> {
(0..42).collect::<Vec<u32>>().into_boxed_slice()
}
#[wasm_bindgen]
pub fn take_option_boxed_number_slice(x: Option<Box<[u8]>>) {}
#[wasm_bindgen]
pub fn return_option_boxed_number_slice() -> Option<Box<[i32]>> {
None
}
}
Example JavaScript Usage
import {
take_boxed_number_slice_by_value,
return_boxed_number_slice,
take_option_boxed_number_slice,
return_option_boxed_number_slice,
} from './guide_supported_types_examples';
take_boxed_number_slice_by_value(new Uint8Array(100));
let x = return_boxed_number_slice();
console.log(x instanceof Uint32Array); // true
take_option_boxed_number_slice(null);
take_option_boxed_number_slice(undefined);
take_option_boxed_number_slice(new Int16Array(256));
let y = return_option_boxed_number_slice();
if (y == null) {
// ...
} else {
console.log(x instanceof Int32Array); // true
}