1
2
3
4
5
6
7 package rand
8
9 import "syscall/js"
10
11
12
13 const maxGetRandomRead = 64 << 10
14
15 var batchedGetRandom func([]byte) error
16
17 func init() {
18 Reader = &reader{}
19 batchedGetRandom = batched(getRandom, maxGetRandomRead)
20 }
21
22 var jsCrypto = js.Global().Get("crypto")
23 var uint8Array = js.Global().Get("Uint8Array")
24
25
26
27
28 type reader struct{}
29
30 func (r *reader) Read(b []byte) (int, error) {
31 if err := batchedGetRandom(b); err != nil {
32 return 0, err
33 }
34 return len(b), nil
35 }
36
37 func getRandom(b []byte) error {
38 a := uint8Array.New(len(b))
39 jsCrypto.Call("getRandomValues", a)
40 js.CopyBytesToGo(b, a)
41 return nil
42 }
43
View as plain text