I'm trying to read an array of boolean values directly from wasm memory, but I can't figure out how I can read the array from JavaScript.
The code that I'm trying to bind to JavaScript is similar to the following example:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub struct Data {
pub bits: Vec<bool>,
}
#[wasm_bindgen]
impl Data {
#[wasm_bindgen(constructor)]
pub fn new() -> Data {
Data{bits: Vec::new()}
}
pub fn get_pointer(&self) -> *const bool {
self.bits.as_ptr()
}
}
Then with other data types like u8
, I use the following code to read the data from the array:
...
// Import the memory object
// Calling the get_pointer function from the binded code
const bits_array = new Uint8Array(memory.buffer, pointerVariable, size);
...
But since there is no smaller Array and the memory usage is crucial in my program I can't figure out how I can read my data.
I know the existence of fixedbitset crate, but due to the more extensive data structure used in my actual code I can't use it.
So how can I read an array of bools directly from the wasm memory? Should I work with bit level operations? In this case how can I read portion of memory starting from the pointer address?
bool
is not packed in memory, and therefore Vec<bool>
have the same layout as Vec<u8>
, and Uint8Array
with zeros and ones will work perfectly for it.
Note, however, that you cannot mutate the data via the pointer derived from Vec::as_ptr()
(even though JavaScript will happily do that), you have to use Vec::as_mut_ptr()
. And even with that, JavaScript will allow you to put whatever numbers you want in the array, but you have to be very careful to only put zeroes and ones. Violating these rules will cause Undefined Behavior in the Rust code.
If memory usage is a constraint, you may want to bit-pack your booleans, either by yourself or using some library.