/
rand.go
36 lines (32 loc) · 1.09 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
package astikit
import (
"math/rand"
"strings"
"time"
)
const (
randLetterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
randLetterIdxBits = 6 // 6 bits to represent a letter index
randLetterIdxMask = 1<<randLetterIdxBits - 1 // All 1-bits, as many as letterIdxBits
randLetterIdxMax = 63 / randLetterIdxBits // # of letter indices fitting in 63 bits
)
var randSrc = rand.NewSource(time.Now().UnixNano())
// RandStr generates a random string of length n
// https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang
func RandStr(n int) string {
sb := strings.Builder{}
sb.Grow(n)
// A randSrc.Int63() generates 63 random bits, enough for randLetterIdxMax characters!
for i, cache, remain := n-1, randSrc.Int63(), randLetterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = randSrc.Int63(), randLetterIdxMax
}
if idx := int(cache & randLetterIdxMask); idx < len(randLetterBytes) {
sb.WriteByte(randLetterBytes[idx])
i--
}
cache >>= randLetterIdxBits
remain--
}
return sb.String()
}