When porting JS code to WebAssembly, what strategy...
# webassembly
t
When porting JS code to WebAssembly, what strategy should I follow for functions not exposed by kotlinx.browser? For example, this works for JS but I can't figure out how to do this in WASM.
Copy code
private suspend fun Blob.asByteArray(): ByteArray {
        //<https://developer.mozilla.org/en-US/docs/Web/API/Blob/arrayBuffer>
        val buffer = asDynamic().arrayBuffer() as Promise<ArrayBuffer>
        return Int8Array(buffer.await()).unsafeCast<ByteArray>()
    }
r
You can use
js.reflect.Reflect
for pseudo-dynamic code if you use kotlin-wrappers library instead of stdlib browser apis.
thank you color 1
If you write wasmJs code directly you can also just use
js()
functions for most dynamic things.
t
This is a great resource, thank you.
r
If you write common (or web shared) code - you may need some expect/actuals
t
I rarely touch Js, but have a few cases where it is unavoidable.
Yes, I already have all platform-dependent stuff in expect/actuals.
t
I had very similar code. This is what I ended up with
Copy code
fun Blob.arrayBuffer(): Promise<ArrayBuffer> = arrayBuffer(this)

private fun arrayBuffer(blob: Blob): Promise<ArrayBuffer> = js("blob.arrayBuffer()")

fun ArrayBuffer.toByteArray(): ByteArray =
    Int8Array(buffer = this, 0, byteLength).toByteArray()
Then I was using it like
Copy code
blob.arrayBuffer().await<ArrayBuffer>().toByteArray()
Only problem is it requires a copy from Int8Array toByteArray. There's might be a way to not need the copy but I haven't spent any extra time on it yet.
thank you color 1