[Wasm/WASI] Make std random generator 64bit seeded

Fixed #KT-60962
This commit is contained in:
Igor Yakovlev
2024-01-03 15:12:47 +01:00
committed by Space Team
parent 84727f8d2b
commit 567fc6b140
@@ -17,20 +17,18 @@ import kotlin.wasm.unsafe.withScopedMemoryAllocator
* seed a pseudo-random number generator, rather than to provide the random data directly. * seed a pseudo-random number generator, rather than to provide the random data directly.
*/ */
@WasmImport("wasi_snapshot_preview1", "random_get") @WasmImport("wasi_snapshot_preview1", "random_get")
//TODO: Better to use 64-bit Long as a seed if possible. (KT-60962) private external fun wasiRawRandomGet(address: Int, size: Int): Int
internal external fun wasiRawRandomGet(address: Int, size: Int): Int
private fun wasiRandomGet(): Int { private fun wasiRandomGet(): Long {
withScopedMemoryAllocator { allocator -> withScopedMemoryAllocator { allocator ->
val memory = allocator.allocate(Int.SIZE_BYTES) val memory = allocator.allocate(Long.SIZE_BYTES)
val ret = wasiRawRandomGet(memory.address.toInt(), Int.SIZE_BYTES) val ret = wasiRawRandomGet(memory.address.toInt(), Long.SIZE_BYTES)
return if (ret == 0) { return if (ret == 0) {
memory.loadInt() memory.loadLong()
} else { } else {
throw WasiError(WasiErrorCode.values()[ret]) throw WasiError(WasiErrorCode.values()[ret])
} }
} }
} }
internal actual fun defaultPlatformRandom(): Random = internal actual fun defaultPlatformRandom(): Random = Random(wasiRandomGet())
Random(wasiRandomGet())