https://kotlinlang.org logo
#webassembly
Title
# webassembly
m

Matt Nelson

01/31/2023, 8:18 PM
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

Big Chungus

01/31/2023, 10:01 PM
wasm32 is deprecated already, better aim for new gc wasm() target instead
e

ephemient

01/31/2023, 11:15 PM
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

Svyatoslav Kuzmich [JB]

02/01/2023, 9:27 AM
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

Matt Nelson

02/01/2023, 1:46 PM
s

Svyatoslav Kuzmich [JB]

02/01/2023, 1:49 PM
What I meant is “sharing ByteArray between Kotlin/Wasm and JavaScript”. Sharing ByteArrays in Kotlin/JS works perfectly fine.
m

Matt Nelson

02/01/2023, 1:49 PM
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!
23 Views