2020-12-26 13:49:20 +00:00
|
|
|
package rand
|
|
|
|
|
2020-12-26 14:14:31 +00:00
|
|
|
import (
|
|
|
|
"math/rand"
|
|
|
|
"time"
|
|
|
|
"unicode"
|
2020-12-26 13:49:20 +00:00
|
|
|
|
2020-12-29 17:13:46 +00:00
|
|
|
"github.com/mickael-menu/zk/core/zk"
|
2020-12-26 13:49:20 +00:00
|
|
|
)
|
|
|
|
|
2020-12-29 15:07:12 +00:00
|
|
|
// NewIDGenerator returns a function generating string IDs using the given options.
|
2020-12-26 14:14:31 +00:00
|
|
|
// Inspired by https://www.calhoun.io/creating-random-strings-in-go/
|
2020-12-29 17:13:46 +00:00
|
|
|
func NewIDGenerator(options zk.IDOptions) func() string {
|
2020-12-26 13:49:20 +00:00
|
|
|
if options.Length < 1 {
|
2020-12-29 17:13:46 +00:00
|
|
|
panic("IDOptions.Length must be at least 1")
|
2020-12-26 13:49:20 +00:00
|
|
|
}
|
|
|
|
|
2020-12-26 14:14:31 +00:00
|
|
|
var charset []rune
|
|
|
|
for _, char := range options.Charset {
|
|
|
|
switch options.Case {
|
2020-12-29 17:13:46 +00:00
|
|
|
case zk.CaseLower:
|
2020-12-26 14:14:31 +00:00
|
|
|
charset = append(charset, unicode.ToLower(char))
|
2020-12-29 17:13:46 +00:00
|
|
|
case zk.CaseUpper:
|
2020-12-26 14:14:31 +00:00
|
|
|
charset = append(charset, unicode.ToUpper(char))
|
2020-12-29 17:13:46 +00:00
|
|
|
case zk.CaseMixed:
|
2020-12-26 14:14:31 +00:00
|
|
|
charset = append(charset, unicode.ToLower(char))
|
|
|
|
charset = append(charset, unicode.ToUpper(char))
|
|
|
|
default:
|
2020-12-29 17:13:46 +00:00
|
|
|
panic("unknown zk.Case value")
|
2020-12-26 14:14:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
rand := rand.New(rand.NewSource(time.Now().UnixNano()))
|
|
|
|
|
2020-12-29 15:07:12 +00:00
|
|
|
return func() string {
|
|
|
|
buf := make([]rune, options.Length)
|
|
|
|
for i := range buf {
|
|
|
|
buf[i] = charset[rand.Intn(len(charset))]
|
|
|
|
}
|
|
|
|
|
|
|
|
return string(buf)
|
|
|
|
}
|
2020-12-26 13:49:20 +00:00
|
|
|
}
|