Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wasm bindings: Make Rng interface zero-copy #311

Open
Tracked by #295
matheus23 opened this issue Jul 19, 2023 · 0 comments
Open
Tracked by #295

Wasm bindings: Make Rng interface zero-copy #311

matheus23 opened this issue Jul 19, 2023 · 0 comments

Comments

@matheus23
Copy link
Member

Currently the Rng interface in wnfs-wasm looks like this:

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(typescript_type = "Rng")]
    pub type Rng;

    #[wasm_bindgen(method, js_name = "randomBytes")]
    pub fn get_random_bytes(this: &Rng, count: usize) -> Vec<u8>;
}

So it's implemented like this on the JS side:

/** A pseudo-random number generator */
class Rng {
  /** Returns random bytes of specified length */
  randomBytes(count: number): Uint8Array {
    const array = new Uint8Array(count);
    self.crypto.getRandomValues(array);
    return array;
  }
}

However, that'll copy the array generated inside randomBytes from the JS heap into the Wasm heap.
We can do better, if instead we defined fn get_random_bytes(this: &Rng, buffer: &mut [u8]) or fn get_random_bytes(this: &Rng, buffer: Uint8Array) or something along those lines, where the buffer to write into is provided by the Wasm side.
crypto.getRandomBytes can write into any location in zero copies :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant