-
Notifications
You must be signed in to change notification settings - Fork 14
/
random.go
68 lines (59 loc) · 1.27 KB
/
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
* Copyright (c) 2018 QLC Chain Team
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
package random
import (
cryptoRand "crypto/rand"
"encoding/binary"
"encoding/hex"
mathRand "math/rand"
)
type cryptoRandSource struct {
data [8]byte
err error
}
func (s *cryptoRandSource) Int63() int64 {
if _, err := cryptoRand.Read(s.data[:]); err != nil {
s.err = err
return 0
}
return int64(binary.BigEndian.Uint64(s.data[:]) & (1<<63 - 1))
}
func (s *cryptoRandSource) Seed(seed int64) {
panic("the seed function is not supported")
}
// Bytes fills the given byte slice with random bytes.
func Bytes(data []byte) error {
_, err := cryptoRand.Read(data)
return err
}
func RandomHexString(length int) string {
if length == 0 {
return ""
}
b := make([]byte, length)
_ = Bytes(b)
s := hex.EncodeToString(b)
return s
}
// Perm returns a random permutation of the integers [0,n).
func Perm(n int) ([]int, error) {
var src cryptoRandSource
i := mathRand.New(&src).Perm(n)
if src.err != nil {
return nil, src.err
}
return i, nil
}
// Intn returns a random number in [0,n).
func Intn(n int) (int, error) {
var src cryptoRandSource
i := mathRand.New(&src).Intn(n)
if src.err != nil {
return 0, src.err
}
return i, nil
}