diff --git a/src/crypto/rand/rand_js.go b/src/crypto/rand/rand_js.go index 82cc75fb4e7..d45031a039e 100644 --- a/src/crypto/rand/rand_js.go +++ b/src/crypto/rand/rand_js.go @@ -4,41 +4,24 @@ package rand -import "syscall/js" - // The maximum buffer size for crypto.getRandomValues is 65536 bytes. // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#exceptions const maxGetRandomRead = 64 << 10 -// read implements a pseudorandom generator -// using JavaScript crypto.getRandomValues method. +//go:wasmimport gojs runtime.getRandomData +//go:noescape +func getRandomValues(r []byte) + +// read calls the JavaScript Crypto.getRandomValues() method. // See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues. -var read = batched(getRandom, maxGetRandomRead) - -var jsCrypto = js.Global().Get("crypto") -var uint8Array = js.Global().Get("Uint8Array") - -func getRandom(b []byte) error { - a := uint8Array.New(len(b)) - jsCrypto.Call("getRandomValues", a) - js.CopyBytesToGo(b, a) +func read(b []byte) error { + for len(b) > 0 { + size := len(b) + if size > maxGetRandomRead { + size = maxGetRandomRead + } + getRandomValues(b[:size]) + b = b[size:] + } return nil } - -// batched returns a function that calls f to populate a []byte by chunking it -// into subslices of, at most, readMax bytes. -func batched(f func([]byte) error, readMax int) func([]byte) error { - return func(out []byte) error { - for len(out) > 0 { - read := len(out) - if read > readMax { - read = readMax - } - if err := f(out[:read]); err != nil { - return err - } - out = out[read:] - } - return nil - } -} diff --git a/src/crypto/rand/rand_test.go b/src/crypto/rand/rand_test.go index d3040cbe307..003a8de9aee 100644 --- a/src/crypto/rand/rand_test.go +++ b/src/crypto/rand/rand_test.go @@ -160,9 +160,6 @@ func TestAllocations(t *testing.T) { // Might be fixable with https://go.dev/issue/56378. t.Skip("boringcrypto allocates") } - if runtime.GOOS == "js" { - t.Skip("syscall/js allocates") - } if race.Enabled { t.Skip("urandomRead allocates under -race") }