wasm_bridge_js/no_bindgen/
memory.rs

1// From this PR https://github.com/kajacx/wasm-bridge/pull/3 by zimond
2
3use js_sys::{Reflect, Uint8Array, WebAssembly};
4
5use crate::{
6    helpers::{map_js_error, static_str_to_js},
7    AsContextMut, Result,
8};
9
10#[derive(Clone, Debug)]
11pub struct Memory {
12    memory: WebAssembly::Memory,
13}
14
15impl Memory {
16    pub(crate) fn new(memory: WebAssembly::Memory) -> Self {
17        Self { memory }
18    }
19
20    // We need this for compatible signature with wasmtime
21    pub fn write(&self, _: impl AsContextMut, offset: usize, buffer: &[u8]) -> Result<()> {
22        self.write_impl(offset, buffer)
23    }
24
25    pub(crate) fn write_impl(&self, offset: usize, buffer: &[u8]) -> Result<()> {
26        let memory = Reflect::get(&self.memory, static_str_to_js("buffer"))
27            .map_err(map_js_error("Memory has no buffer field"))?;
28        let mem = Uint8Array::new_with_byte_offset_and_length(
29            &memory,
30            offset as u32,
31            buffer.len() as u32,
32        );
33        mem.copy_from(buffer);
34        Ok(())
35    }
36
37    // We need this for compatible signature with wasmtime
38    pub fn read(&self, _: impl AsContextMut, offset: usize, buffer: &mut [u8]) -> Result<()> {
39        self.read_impl(offset, buffer)
40    }
41
42    pub(crate) fn read_impl(&self, offset: usize, buffer: &mut [u8]) -> Result<()> {
43        let memory = Reflect::get(&self.memory, static_str_to_js("buffer"))
44            .map_err(map_js_error("Memory has no buffer field"))?;
45        let mem = Uint8Array::new_with_byte_offset_and_length(
46            &memory,
47            offset as u32,
48            buffer.len() as u32,
49        );
50        mem.copy_to(buffer);
51        Ok(())
52    }
53}