51 lines
1003 B
Go
51 lines
1003 B
Go
package util
|
|
|
|
import (
|
|
"github.com/gofrs/uuid"
|
|
"math/rand"
|
|
"time"
|
|
"unsafe"
|
|
)
|
|
|
|
// Ifs 三目运算的函数
|
|
func Ifs[T any](a bool, b, c T) T {
|
|
if a {
|
|
return b
|
|
}
|
|
return c
|
|
}
|
|
|
|
func GetUUID() (string, error) {
|
|
u2, err := uuid.NewV4()
|
|
return u2.String(), err
|
|
}
|
|
|
|
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
|
|
var src = rand.NewSource(time.Now().UnixNano())
|
|
|
|
const (
|
|
// 6 bits to represent a letter index
|
|
letterIdBits = 6
|
|
// All 1-bits as many as letterIdBits
|
|
letterIdMask = 1<<letterIdBits - 1
|
|
letterIdMax = 63 / letterIdBits
|
|
)
|
|
|
|
func RandomStr(n int) string {
|
|
b := make([]byte, n)
|
|
// A rand.Int63() generates 63 random bits, enough for letterIdMax letters!
|
|
for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; {
|
|
if remain == 0 {
|
|
cache, remain = src.Int63(), letterIdMax
|
|
}
|
|
if idx := int(cache & letterIdMask); idx < len(letters) {
|
|
b[i] = letters[idx]
|
|
i--
|
|
}
|
|
cache >>= letterIdBits
|
|
remain--
|
|
}
|
|
return *(*string)(unsafe.Pointer(&b))
|
|
}
|