stevendesu
stevendesu

Reputation: 16781

Can a WebAssembly::Memory SharedArrayBuffer be read as a slice without copying?

I wish to write a library in Rust that will compile to both a DLL and to WASM. The library should be able to take a pointer to shared memory and update the contents of the memory. Here's a rough outline for how the JS interface will look:

test.js:

const shared_mem = new WebAssembly.Memory({
  initial: 1, // 1 page = 64k
  maximum: 1,
  shared: true,
});
write_to_shared_memory(shared_mem);
const val = read_from_shared_memory(shared_mem);

In order to support DLL compilation, I want the main implementation methods to use raw Rust types, rather than JsValue or other wasm-bindgen specific types. For example:

lib.rs:

#[wasm_bindgen]
pub fn write_to_shared_memory(mem: &WebAssembly::Memory) -> () {
    let ptr = ???;
    let mut_ref = unsafe { ??? };
    write_impl(mut_ref);
}

pub fn write_impl(mem: &mut [u8]) -> () {
    for i in 0..100 {
        mem[i] = i;
    }
}

#[wasm_bindgen]
pub fn read_from_shared_memory(mem: &WebAssembly::Memory) -> JsValue {
    let ptr = ???;
    let const_ref = unsafe { ??? };
    return read_impl(const_ref).into();
}

pub fn read_impl(arr: &[u8]) -> u8 {
    return arr[0];
}

The question is what would be the implementation of ??? in order to convert a &WebAssembly::Memory into a &mut [u8]? I imagine something like this should be possible (in a very unsafe way) using raw pointers and std::mem::transmute

Note: I know that this is very unsafe (there's no guarantees that the index I'm writing to is valid, there's a risk of data races, etc)... I am doing this for intellectual curiosity. This will not harm any production systems.

Upvotes: 0

Views: 183

Answers (0)

Related Questions