Add system_random and random_bytes for js target

This commit is contained in:
Damian Tarnawski
2023-10-27 00:05:38 +02:00
parent 0a492acaa1
commit 11a2b2a942
4 changed files with 39 additions and 2 deletions

View File

@@ -1,7 +1,7 @@
package crypto
when ODIN_OS != .Linux && ODIN_OS != .OpenBSD && ODIN_OS != .Windows {
_rand_bytes :: proc (dst: []byte) {
when ODIN_OS != .Linux && ODIN_OS != .OpenBSD && ODIN_OS != .Windows && ODIN_OS != .JS {
_rand_bytes :: proc(dst: []byte) {
unimplemented("crypto: rand_bytes not supported on this OS")
}
}

20
core/crypto/rand_js.odin Normal file
View File

@@ -0,0 +1,20 @@
package crypto
foreign import "odin_env"
foreign odin_env {
@(link_name = "rand_bytes")
env_rand_bytes :: proc "contextless" (buf: []byte) ---
}
_MAX_PER_CALL_BYTES :: 65536
_rand_bytes :: proc(dst: []byte) {
dst := dst
for len(dst) > 0 {
to_read := min(len(dst), _MAX_PER_CALL_BYTES)
env_rand_bytes(dst[:to_read])
dst = dst[to_read:]
}
}

View File

@@ -0,0 +1,11 @@
package rand
foreign import "odin_env"
foreign odin_env {
rand :: proc "contextless" () -> f64 ---
}
@(require_results)
_system_random :: proc() -> u64 {
return u64(rand() * 0x1fffffffffffff)
}

View File

@@ -1349,6 +1349,12 @@ function odinSetupDefaultImports(wasmMemoryInterface, consoleElement) {
ln: Math.log,
exp: Math.exp,
ldexp: (x, exp) => x * Math.pow(2, exp),
rand: Math.random,
rand_bytes: (ptr, len) => {
const view = new Uint8Array(wasm_memory.buffer, ptr, len)
crypto.getRandomValues(view)
},
},
"odin_dom": {
init_event_raw: (ep) => {