forked from lilith44/gox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_rand.go
53 lines (44 loc) · 1.08 KB
/
string_rand.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
package gox
import (
`math/rand`
`time`
`unsafe`
)
const (
// 随机字符串
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"
letterIdxBits = 6
letterIdxMask = 1<<letterIdxBits - 1
letterIdxMax = 63 / letterIdxBits
// 随机数字
digitBytes = "123456789"
)
var src = rand.NewSource(time.Now().UnixNano())
// RandString 生成随时字符串
func RandString(length int) string {
return randString(length, letterBytes)
}
// RandDigit 生成随机数字字符串
func RandDigit(length int) string {
return randString(length, digitBytes)
}
// RandCode 生成随机验证码
func RandCode() string {
return RandDigit(6)
}
// 生成随时字符串
func randString(length int, letterBytes string) string {
b := make([]byte, length)
for i, cache, remain := length-1, src.Int63(), letterIdxMax; i >= 0; {
if 0 == remain {
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))
}