-
Notifications
You must be signed in to change notification settings - Fork 0
/
random.go
88 lines (71 loc) · 1.67 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
package utils
import (
"encoding/base64"
"math/rand"
"sync"
"time"
"github.com/dayaftereh/discover/server/mathf"
"github.com/pkg/errors"
)
const (
NumbersCharset = "0123456789"
UpperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LowerCaseCharset = "abcdefghijklmnopqrstuvwxyz"
AlphaCharset = NumbersCharset + UpperCaseCharset + LowerCaseCharset
)
var (
random = createRand()
randomLock sync.Mutex
)
func createRand() *rand.Rand {
now := time.Now()
source := rand.NewSource(now.UnixNano())
rand := rand.New(source)
return rand
}
func RandBytes(size int64) ([]byte, error) {
randomLock.Lock()
defer randomLock.Unlock()
bytes := make([]byte, size)
_, err := random.Read(bytes)
if err != nil {
return nil, errors.Wrapf(err, "unable to create random %d bytes", size)
}
return bytes, nil
}
func RandString(size int64) (string, error) {
buffer, err := RandBytes(size)
if err != nil {
return "", err
}
str := base64.StdEncoding.EncodeToString(buffer)
value := str[:size]
return value, nil
}
func RandStringWithCharset(length int, charset string) string {
b := make([]byte, length)
charsetLength := len(charset)
for i := range b {
index := RandIntn(charsetLength)
b[i] = charset[index]
}
return string(b)
}
func RandIntn(n int) int {
randomLock.Lock()
defer randomLock.Unlock()
return random.Intn(n)
}
func RandInt64(min int64, max int64) int64 {
randomLock.Lock()
defer randomLock.Unlock()
return min + random.Int63n(max-min)
}
func RandFloat64(min float64, max float64) float64 {
randomLock.Lock()
defer randomLock.Unlock()
return min + random.Float64()*(max-min)
}
func RandFromRange(r *mathf.Range) float64 {
return RandFloat64(r.Min, r.Max)
}