wasm-bindgen: Allow returning fixed-size tuples and arrays
It appears that returning (f32, f32, f32, f32) or [f32; 4] in a #[wasm_bindgen] function does not currently work. Would be great if fixed size arrays and tuples (maybe up to length 32) were supported.
About this issue
- Original URL
- State: open
- Created 9 years ago
- Reactions: 58
- Comments: 21 (6 by maintainers)
This would be great.
In my use case, I wanted to return RGB value as 3 elements tuple or array of
u8. However, they are not yet supported so I needed to create a struct likeBut it is not so efficient since in JavaScript, accessing each field causes interaction between wasm and JS.
For this use case, I could finally use
0xrrggbbformat ofu32values for RGB values. But it’s a solution only for this use case.I also think mapping tuples to JS array is fine and reasonable. TypeScript supports tuples and actually it is transpiled into array.
https://www.typescriptlang.org/docs/handbook/basic-types.html
We currently have fixed size arrays for most numeric primitives working when using the
WASM_BINDGEN_MULTI_VALUE=trueoption! Still a bit of work to be done (testing, clean up, making it work when multi value is disabled, etc), but I think we’re close! I’ve opened a draft PR in the meantime if anyone wants to take a look at what we have so far: #3458.As another use-case, I think tuples support could improve interfaces for js-sys iterators too.
In particular,
.entries()onMap/Set/Arraycould produce an iterator over tuples of(JsValue, JsValue)right away instead of users having to repeat same boilerplate withJsArray+Reflect::get_u32(..., 0)+Reflect::get_u32(..., 1)to extract key and value on each iteration.Has there been any work on this recently? What is still in the way if not?
We’re currently doing the wasm-bindgen work here: https://github.com/staratlasmeta/wasm-bindgen. It’s not in a working state at the moment and there’s still work we’ll need to do, but its getting there.
I think fixed-size-arrays are in theory easy enough (we’d probably pass them through allocated memory), tuples are a bit odder though. You’re mostly looking for homogenous tuples, right? And both of these in JS would pop out as arrays?
From what I’ve read, this feature was put on hold & is dependent on the ECMAScript proposal on tuples & records. If JS adds a new, compound-primitive, it’s worth waiting for that standard. However, it seems the proposal was rejected and withdrawn (https://github.com/tc39/proposal-record-tuple/issues/394). Without that as a blocker, is it worth dusting off the PR & adding this as a feature?
Thank you for the update! 🚀
Sounds good then!
@stegaBOB I’m not entirely sure how easy or hard to implement this really is, but I’m happy to review a PR!
@josephrocca, Tuples refer to Rust tuples, Wasm multi-value tuples return JavaScript arrays, and it would make the most sense to target the Wasm feature so that some cases won’t need a wasm-bindgen shim at all.