Search code examples
rustwebassemblywasm-bindgen

How do I use nested Vecs with wasm-bindgen?


It doesn't appear that nested Vecs work with wasm-bindgen. Is that correct?

My goal is to have a Game of Life grid in Rust that I can return as rows, rather than a 1D Vec which requires the JavaScript to handle the indexing. Two workarounds I've thought of are:

  1. Implement a sort of custom "iterator" in Rust, which is a method which returns the rows one-by-one.
  2. Hand a 1D array to JavaScript but write a wrapper in JavaScript which handles the indexing and exposes some sort of an iterator to the consumer.

I hesitate to use either of these because I want this library to be usable by JavaScript and native Rust, and I don't think either would be very idiomatic in pure Rust land. Any other suggestions?


Solution

  • You're correct that wasm-bindgen today doesn't support returning types like Vec<Vec<u8>>.

    A good rule of thumb for WebAssembly is that big chunks of data (like vectors) should always live in the same location to avoid losing too much performance. This means that you might want to explore an interface where a JS object wraps a pointer into WASM memory, and all of its methods work with row/column indices but modify WASM memory to keep it as the source of truth.

    If that doesn't work out, then the best way to implement this today is either of the strategies you mentioned as well, although both of those require some level of JS glue code to be written as well.