-
Notifications
You must be signed in to change notification settings - Fork 128
/
rand.go
43 lines (36 loc) · 1 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
package rand
import (
"math/rand"
"time"
"unicode"
"github.com/mickael-menu/zk/internal/core"
)
// NewIDGenerator returns a function generating string IDs using the given options.
// Inspired by https://www.calhoun.io/creating-random-strings-in-go/
func NewIDGenerator(options core.IDOptions) func() string {
if options.Length < 1 {
panic("IDOptions.Length must be at least 1")
}
var charset []rune
for _, char := range options.Charset {
switch options.Case {
case core.CaseLower:
charset = append(charset, unicode.ToLower(char))
case core.CaseUpper:
charset = append(charset, unicode.ToUpper(char))
case core.CaseMixed:
charset = append(charset, unicode.ToLower(char))
charset = append(charset, unicode.ToUpper(char))
default:
panic("unknown zk.Case value")
}
}
rand := rand.New(rand.NewSource(time.Now().UnixNano()))
return func() string {
buf := make([]rune, options.Length)
for i := range buf {
buf[i] = charset[rand.Intn(len(charset))]
}
return string(buf)
}
}