Fix the RandString method cause the lag

This commit is contained in:
2024-08-18 17:16:14 +08:00
parent f32803acf4
commit e7f6637398
4 changed files with 40 additions and 57 deletions

View File

@@ -2,30 +2,14 @@ package services
import (
"math/rand"
"strings"
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6
letterIdxMask = 1<<letterIdxBits - 1
letterIdxMax = 63 / letterIdxBits
)
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func RandString(length int) string {
builder := strings.Builder{}
builder.Grow(length)
for idx, cache, remain := length-1, rand.Int63(), letterIdxMax; idx >= 0; {
if remain == 0 {
cache, remain = rand.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
builder.WriteByte(letterBytes[idx])
idx--
}
cache >>= letterIdxBits
remain--
builder := make([]rune, length)
for i := range builder {
builder[i] = letters[rand.Intn(len(letters))]
}
return builder.String()
return string(builder)
}