-
Notifications
You must be signed in to change notification settings - Fork 1
/
grand.go
60 lines (48 loc) · 1.88 KB
/
grand.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
package grand
import "math/rand"
// Credits to icza of https://stackoverflow.com/a/31832326/1161743 for the original code.
// Character sets for random string generation
const (
CharSetEnglishAlphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
CharSetEnglishAlphabetLowercase = "abcdefghijklmnopqrstuvwxyz"
CharSetEnglishAlphabetUppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
CharSetBase62 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
var defaultLetterBytes = CharSetEnglishAlphabet
const (
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
)
// Generator is the instance that generates random strings from the given charset
type Generator struct {
charset string
}
// NewGenerator returns a new Generator instance
func NewGenerator(charset string) *Generator {
return &Generator{
charset: charset,
}
}
// GenerateRandomString generates a length-n random string from the given character set
func (g *Generator) GenerateRandomString(n int) string {
b := make([]byte, n)
// A rand.Int63() generates 63 random bits, enough for letterIdxMax letters!
for i, cache, remain := n-1, rand.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = rand.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(g.charset) {
b[i] = g.charset[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
// GenerateRandomString generates a length-n random string from the default character set (English alphabets).
// Be sure to seed the random function using rand.Seed to initialize the generator first.
func GenerateRandomString(n int) string {
return NewGenerator(CharSetEnglishAlphabet).GenerateRandomString(n)
}