hanayo/vendor/zxq.co/x/rs/rs.go

38 lines
951 B
Go
Raw Permalink Normal View History

2019-02-23 13:29:15 +00:00
package rs
import (
"math/rand"
"time"
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
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
)
// String generates a random string.
func String(n int) string {
return StringFromChars(n, letterBytes)
}
// StringFromChars generates a random string from the given characters.
func StringFromChars(n int, chars string) string {
src := rand.NewSource(time.Now().UnixNano())
b := make([]byte, n)
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(chars) {
b[i] = chars[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}