yawkat
02/19/2025, 9:50 AMyawkat
02/19/2025, 10:24 AM@WasmExport
fun wasmBestEvAndMove(writer: Int): Int {
val request = writers.remove(writer)!!.decodeToString()
println("wasmCalculateEv($request)")
val response = Json.encodeToString(EvProvider.Local.bestEvAndMove(Json.decodeFromString(request)))
println("wasmCalculateEv($request) -> $response")
return allocate(readers, response.encodeToByteArray())
}
private val writers = mutableMapOf<Int, ByteArray>()
private val readers = mutableMapOf<Int, ByteArray>()
private fun allocate(map: MutableMap<Int, ByteArray>, initialValue: ByteArray): Int {
while (true) {
val i = Random.nextInt()
if (map.containsKey(i)) {
continue
}
map[i] = initialValue
return i
}
}
@WasmExport
fun wasmCreateWriter(): Int {
return allocate(writers, ByteArray(0))
}
@WasmExport
fun wasmWrite(writer: Int, b: Byte) {
writers[writer] = writers[writer]!! + b
}
@WasmExport
fun wasmRead(reader: Int): Int {
val arr = readers[reader]!!
if (arr.isEmpty()) {
readers.remove(reader)
return -1
} else {
readers[reader] = arr.copyOfRange(1, arr.size)
return arr[0].toInt() and 0xff
}
}
ugly but it works, it doesnt need to be fast.Alexey Zolotarev
02/19/2025, 3:07 PMmalloc
to allocate memory and store host data upfront. You can only allocate memory using withScopedMemoryAllocator which only allows allocations within a function call scope so you would have to work around that.yawkat
02/19/2025, 4:58 PMMohammed Akram Hussain
02/23/2025, 12:30 AM@JsExport
and @WasmExport
? Both can be called from javascript right?yawkat
02/25/2025, 3:27 PMMohammed Akram Hussain
02/25/2025, 3:28 PM