-
Notifications
You must be signed in to change notification settings - Fork 41
/
random.go
97 lines (79 loc) · 2.23 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
package util
import (
"math/rand"
"time"
"unsafe"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
)
const (
byteArr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
bytesToLower = "abcdefghijklmnopqrstuvwxyz"
bytesToUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
func rdm(n int, data string) string {
ran := rand.New(rand.NewSource(time.Now().UnixNano()))
b := make([]byte, n)
for i := range b {
b[i] = data[ran.Int63()%int64(len(data))]
}
return string(b)
}
func RandomNum(n, scope int) int {
ran := rand.New(rand.NewSource(time.Now().UnixNano()))
return ran.Intn(n) + scope
}
// RandInt64 generate random int64 between min and max
func RandInt64(min, max int64) int64 {
return min + rand.Int63n(max-min)
}
func RandomString(n int) string {
return rdm(n, byteArr)
}
func RandomStringToLower(n int) string {
return rdm(n, bytesToLower)
}
func RandomStringToUpper(n int) string {
return rdm(n, bytesToUpper)
}
func RandHexKey() string {
key, _ := crypto.GenerateKey()
keyBytes := crypto.FromECDSA(key)
hexKey := hexutil.Encode(keyBytes)[2:]
return hexKey
}
const (
letterBytes = "abcdefghijklmnopqrstuvwxyz0123456789"
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
var src = rand.NewSource(time.Now().UnixNano())
func randString(n int) string {
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return *(*string)(unsafe.Pointer(&b))
}
// GetRandomObjectName generate random object name.
func GetRandomObjectName() string {
return randString(10)
}
// GetRandomBucketName generate random bucket name.
func GetRandomBucketName() string {
return randString(5)
}
// GetRandomGroupName generate random group name.
func GetRandomGroupName() string {
return randString(7)
}