Alexander Zhirkevich
06/10/2024, 1:27 PMAlexander Zhirkevich
06/10/2024, 1:28 PMstart
method.
For k/JS i have
external interface UnderlyingSource {
fun start(controller: SourceController)
}
external interface SourceController {
fun enqueue(data : ByteArray)
fun close()
}
external class ReadableStream(
source: UnderlyingSource
)
And then i create anonymous object and pass it to the constructor
val source = object : UnderlyingSource {
override fun start(controller: SourceController) {
controller.enqueue(array);
controller.close();
}
}
val stream = ReadableStream(source)
Everything works fine.
How to achive the same result in k/wasm?
I tried the following to create the underlyingSource and used ByteArray.toJsReference()
as a parameter but with no luck. JS says that data is not an array buffer
fun createSource(data : JsAny) : JsAny = js("""
({
start(c){
console.log(data)
c.enqueue(data)
c.close()
}
})
""")
Svyatoslav Kuzmich [JB]
06/10/2024, 1:52 PMInt8Array
type and manually copy the elements like this.
References created by .toJsReference()
are not accessible in JS; they are only useful when they are sent back to Kotlin.Alexander Zhirkevich
06/10/2024, 2:13 PMSvyatoslav Kuzmich [JB]
06/10/2024, 2:28 PMSvyatoslav Kuzmich [JB]
06/10/2024, 2:57 PMimport org.khronos.webgl.Int8Array
@JsExport
fun kotlinArrayGet(a: JsReference<ByteArray>, i: Int): Byte = a.get()[i]
@JsExport
fun kotlinArraySize(a: JsReference<ByteArray>): Int = a.get().size
fun byteArrayToInt8ArrayImpl(a: JsReference<ByteArray>): Int8Array = js("""{
const size = wasmExports.kotlinArraySize(a);
const result = new Int8Array(size);
for (let i = 0; i < size; i++) {
result[i] = wasmExports.kotlinArrayGet(a, i);
}
return result;
}""")
fun ByteArray.toJs(): Int8Array = byteArrayToInt8ArrayImpl(this.toJsReference())
You can also remove this extra copy if you can manage to use exported kotlinArrayGet
and kotlinArraySize
in your JS directly, or with a wrapper layer. Especially great when only a portion of ByteArray is accessed in JS.Alexander Zhirkevich
06/10/2024, 3:04 PMSvyatoslav Kuzmich [JB]
06/10/2024, 3:07 PMAlexander Zhirkevich
06/10/2024, 3:11 PMAlexander Zhirkevich
06/10/2024, 4:44 PMwasmExports
stuff internal? Can i use it for a public library?Svyatoslav Kuzmich [JB]
06/10/2024, 4:59 PMSvyatoslav Kuzmich [JB]
06/10/2024, 5:03 PM