WebAssembly / stringref

Other
37 stars 2 forks source link

Possible addition: number-to-string conversions #51

Open jakobkummerow opened 2 years ago

jakobkummerow commented 2 years ago

It turns out that converting primitive values (i32/i64/f32/f64) to stringref is a fairly common use case in practice. Obviously, this can be done using the existing instruction set (e.g. by assembling the characters in a Wasm i16 array, then calling string.new_wtf16_array on that), but there is room for making that faster by introducing a dedicated instruction for it.

For engines, this is likely easy to implement. They might have such facilities already and could expose them to Wasm without much trouble. (This is definitely true for V8; I'd be very surprised if it wasn't true for other engines.)

A difficulty is that different source languages actually specify float-to-string conversions differently. For example, floating-point "zero" becomes "0" in JavaScript but "0.0" in Java. Wasm could choose to provide its own standard, or could attempt to make this configurable somehow (at potentially great cost to implementation complexity). Considering that many languages have various flexible string conversion routines in addition to whatever their default behavior is, Wasm likely won't want to offer the full set of possible options anyway, so it might be perfectly reasonable to have a built-in "default" fast path, which X-to-Wasm compilers may use when possible and will ignore for X-specific functionality that requires more flexibility or different defaults (e.g. if (f == 0) { return x_specific_zero(f); } else { return stringref.new_f64(f); }).

I wouldn't mind adding such instructions to the MVP; I'm also fine with postponing them to a post-MVP follow-up.