1// Copyright 2010 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Package rand implements a cryptographically secure
6// random number generator.
7package rand
8
9import "io"
10
11// Reader is a global, shared instance of a cryptographically
12// secure random number generator.
13//
14//   - On Linux, FreeBSD, Dragonfly, and Solaris, Reader uses getrandom(2)
15//     if available, and /dev/urandom otherwise.
16//   - On macOS and iOS, Reader uses arc4random_buf(3).
17//   - On OpenBSD and NetBSD, Reader uses getentropy(2).
18//   - On other Unix-like systems, Reader reads from /dev/urandom.
19//   - On Windows, Reader uses the ProcessPrng API.
20//   - On js/wasm, Reader uses the Web Crypto API.
21//   - On wasip1/wasm, Reader uses random_get from wasi_snapshot_preview1.
22var Reader io.Reader
23
24// Read is a helper function that calls Reader.Read using io.ReadFull.
25// On return, n == len(b) if and only if err == nil.
26func Read(b []byte) (n int, err error) {
27	return io.ReadFull(Reader, b)
28}
29
30// batched returns a function that calls f to populate a []byte by chunking it
31// into subslices of, at most, readMax bytes.
32func batched(f func([]byte) error, readMax int) func([]byte) error {
33	return func(out []byte) error {
34		for len(out) > 0 {
35			read := len(out)
36			if read > readMax {
37				read = readMax
38			}
39			if err := f(out[:read]); err != nil {
40				return err
41			}
42			out = out[read:]
43		}
44		return nil
45	}
46}
47