Heyo! Anyone in here able to advise on how I migh...
# webassembly
m
Heyo! Anyone in here able to advise on how I might go about adding
wasm32
support for a library of mine; secure-random? It's the only platform not supported currently and I've no clue where to start 😢 Issue Ticket
👌 3
👍 1
b
wasm32 is deprecated already, better aim for new gc wasm() target instead
e
in the new WASM target, you will be able to bridge to JS and WASI. at least that's the plan, I haven't played with it to see how much works currently
s
New
wasm()
target is highly experimental and lacks documentation. But in case you want to try it, you can use
@JsFun
to call JS functions. Sharing
ByteArray
with JavaScript is not supported at the moment, so your best bet would be returning random
Int
multiple times and unpack them into bytes:
Copy code
@JsFun("""() => {
  var array = new Uint32Array(1);
  globalThis.crypto.getRandomValues(array);
  return array[0];
}""")
external fun secureNextRandomInt(): Int
In upcoming 1.8.20 you’ll be able to use WebAssembly linear memory to reduce number of calls to JavaScript:
Copy code
@JsFun("""(memoryAddress, sizeInBytes) => {
  var array = new Uint8Array(wasmExports.memory.buffer, memoryAddress, sizeInBytes)
  globalThis.crypto.getRandomValues(array);
}""")
external fun fillLinearMemoryWithSecureRandomData(memoryAddress: Int, sizeInBytes: Int)

@OptIn(UnsafeWasmMemoryApi::class)
fun fillByteArrayWithSecureRandomData(array: ByteArray) {
    withScopedMemoryAllocator { allocator ->
        val ptr = allocator.allocate(array.size)
        fillLinearMemoryWithSecureRandomData(ptr.address.toInt(), array.size)
        for (i in array.indices) {
            array[i] = (ptr + i).loadByte()
        }
    }
}
Running Kotlin in a WASI environment is even more experimental, but in case you are interested, you can find experiments with secure random generation in kowasm project
m
s
What I meant is “sharing ByteArray between Kotlin/Wasm and JavaScript”. Sharing ByteArrays in Kotlin/JS works perfectly fine.
m
oh ok, you had me sweating for a second, lol.
Well thanks so much for your help! Might wait for
1.8.20
until I add support for it. Will look into things this week though!