aboutsummaryrefslogtreecommitdiff
path: root/core
diff options
context:
space:
mode:
authorJeroen van Rijn <Kelimion@users.noreply.github.com>2023-10-27 12:52:27 +0200
committerGitHub <noreply@github.com>2023-10-27 12:52:27 +0200
commit292398dbe2a07ccb46023bca894f7b5f224c2a4e (patch)
tree0efef5dc7200509a88100ab2b5db44cdaa008f0a /core
parent0a492acaa16243d11cc779e7c89942e876c1dea4 (diff)
parent49da19e013cc26abad75b552f06ee2ba925718c9 (diff)
Merge pull request #2896 from thetarnav/js-rand
Add system_random and random_bytes for js target
Diffstat (limited to 'core')
-rw-r--r--core/crypto/rand_generic.odin4
-rw-r--r--core/crypto/rand_js.odin20
-rw-r--r--core/math/rand/system_js.odin14
3 files changed, 36 insertions, 2 deletions
diff --git a/core/crypto/rand_generic.odin b/core/crypto/rand_generic.odin
index 52abfe4d7..fde91f85a 100644
--- a/core/crypto/rand_generic.odin
+++ b/core/crypto/rand_generic.odin
@@ -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")
}
}
diff --git a/core/crypto/rand_js.odin b/core/crypto/rand_js.odin
new file mode 100644
index 000000000..353b1e6b9
--- /dev/null
+++ b/core/crypto/rand_js.odin
@@ -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 // 64kiB
+
+_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:]
+ }
+}
diff --git a/core/math/rand/system_js.odin b/core/math/rand/system_js.odin
new file mode 100644
index 000000000..b9b71c4a6
--- /dev/null
+++ b/core/math/rand/system_js.odin
@@ -0,0 +1,14 @@
+package rand
+
+foreign import "odin_env"
+foreign odin_env {
+ @(link_name = "rand_bytes")
+ env_rand_bytes :: proc "contextless" (buf: []byte) ---
+}
+
+@(require_results)
+_system_random :: proc() -> u64 {
+ buf: [8]u8
+ env_rand_bytes(buf[:])
+ return transmute(u64)buf
+}