-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
random.go
104 lines (85 loc) · 2.17 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package utils
import (
crand "crypto/rand"
"math/big"
"math/rand"
"sync"
"time"
)
var (
randor = NewRand()
randorMu sync.Mutex
letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
)
// NewRand new individual random to aviod global mutex
func NewRand() *rand.Rand {
return rand.New(rand.NewSource(time.Now().UnixNano()))
}
// RandomBytesWithLength generate random bytes
func RandomBytesWithLength(n int) ([]byte, error) {
b := make([]byte, n)
randorMu.Lock()
_, err := randor.Read(b)
randorMu.Unlock()
return b, err
}
// SecRandomBytesWithLength generate crypto random bytes
func SecRandomBytesWithLength(n int) ([]byte, error) {
b := make([]byte, n)
_, err := crand.Read(b)
return b, err
}
// RandomStringWithLength generate random string with specific length
func RandomStringWithLength(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
// SecRandomStringWithLength generate random string with specific length
func SecRandomStringWithLength(n int) (string, error) {
b := make([]rune, n)
for i := range b {
idx, err := SecRandInt(len(letterRunes))
if err != nil {
return "", err
}
b[i] = letterRunes[idx]
}
return string(b), nil
}
// SecRandInt generate security int
func SecRandInt(n int) (int, error) {
bn, err := crand.Int(crand.Reader, big.NewInt(int64(n)))
if err != nil {
return 0, err
}
return int(bn.Int64()), nil
}
// RandomChoice selects a random subset of elements from an input array of any type.
//
// It takes in two parameters: the array and the number of elements to select from the array.
// The function uses a random number generator to select elements from the array and
// returns a new array containing the selected elements.
func RandomChoice[T any](arr []T, n int) (got []T) {
if n >= len(arr) {
return arr
} else if n == 0 {
return got
}
randor := NewRand()
thres := float64(n) / float64(len(arr))
for i := range arr {
if (len(arr) - i) <= (n - len(got)) {
return append(got, arr[i:]...)
}
if randor.Float64() < thres {
got = append(got, arr[i])
}
if len(got) == n {
return got
}
}
return got
}