-
Notifications
You must be signed in to change notification settings - Fork 3
/
random.go
44 lines (36 loc) · 922 Bytes
/
random.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package jess
import (
"crypto/rand"
"io"
"github.com/tevino/abool"
)
var (
customRandReader io.Reader
customRandReaderFlag = abool.NewBool(false)
)
// Random returns the io.Reader for reading randomness. By default, it uses crypto/rand.Reader.
func Random() io.Reader {
if customRandReaderFlag.IsSet() {
return customRandReader
}
return rand.Reader
}
// RandomBytes returns the specified amount of random bytes in a []byte slice. By default, it uses crypto/rand.Reader.
func RandomBytes(n int) ([]byte, error) {
rBytes := make([]byte, n)
bytesRead, err := Random().Read(rBytes)
if err != nil {
return nil, err
}
if bytesRead != n {
return nil, ErrInsufficientRandom
}
return rBytes, nil
}
// SetCustomRNG sets a custom RNG to be used with jess.
func SetCustomRNG(randReader io.Reader) {
if !customRandReaderFlag.IsSet() {
customRandReader = randReader
customRandReaderFlag.Set()
}
}