-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrand.go
130 lines (110 loc) · 2.25 KB
/
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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package cryptorandstr
import (
"crypto/rand"
"fmt"
"unsafe"
)
const Chars64 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
var Chars10 = Chars64[:10]
var Chars16 = Chars64[:16]
var Chars32 = Chars64[:32]
// Panic when error.
func MustRand10(strLen int) string {
return MustRand(strLen, Chars10)
}
// Panic when error.
func MustRand16(strLen int) string {
return MustRand(strLen, Chars16)
}
// Panic when error.
func MustRand32(strLen int) string {
return MustRand(strLen, Chars32)
}
// Panic when error.
func MustRand64(strLen int) string {
return MustRand(strLen, Chars64)
}
// Panic when error.
func MustRand(strLen int, chars string) string {
s, err := Rand(strLen, chars)
if err != nil {
panic(err)
}
return s
}
func Rand10(strLen int) (string, error) {
return Rand(strLen, Chars10)
}
func Rand16(strLen int) (string, error) {
return Rand(strLen, Chars16)
}
func Rand32(strLen int) (string, error) {
return Rand(strLen, Chars32)
}
func Rand64(strLen int) (string, error) {
return Rand(strLen, Chars64)
}
func Rand(strLen int, chars string) (string, error) {
if strLen < 1 {
return "", fmt.Errorf("cryptorandstr: strLen %d < 1", strLen)
}
if len(chars) < 2 {
return "", fmt.Errorf("cryptorandstr: chars length %d < 2", len(chars))
}
if len(chars) > 256 {
return "", fmt.Errorf("cryptorandstr: chars length %d > 256", len(chars))
}
var (
out = make([]byte, strLen)
i int
chunk = make([]byte, 1)
n int
err error
cache uint16
cacheBitLen byte
maxB = byte(len(chars) - 1)
outBitLen = bitLen(maxB)
difference = 8 - outBitLen
b byte
)
for {
if cacheBitLen >= outBitLen {
// read cache
b = byte(cache)
cache >>= outBitLen
cacheBitLen -= outBitLen
} else {
// random
for {
n, err = rand.Reader.Read(chunk)
if err != nil {
return "", err
}
if n == 1 {
break
}
}
b = chunk[0]
// write cache
cache <<= difference
cache |= uint16(b >> outBitLen)
cacheBitLen += difference
}
b <<= difference
b >>= difference
if b <= maxB {
out[i] = chars[b]
i++
if i == strLen {
return *(*string)(unsafe.Pointer(&out)), nil
}
}
}
}
func bitLen(b byte) (l byte) {
for b != 0 {
b >>= 1
l++
}
return
}