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 44 45 46 47
| package RandomUtil
import ( "fmt" "math/rand" "time" "unsafe" )
var random = rand.NewSource(time.Now().UnixNano())
const ( letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" letterIdBits = 6 letterIdMask = 1<<letterIdBits - 1 letterIdMax = letterIdMask / letterIdBits )
func BuildRandomString(length int) string { bytes := make([]byte, length) for i, cache, remain := length-1, random.Int63(), letterIdMax; i >= 0; { if remain == 0 { cache, remain = random.Int63(), letterIdMax } if idx := int(cache & letterIdMask); idx < len(letters) { bytes[i] = letters[idx] i-- } cache >>= letterIdBits remain-- } return *(*string)(unsafe.Pointer(&bytes)) }
|