gitee.com/hongliu9527/go-tools@v0.0.8/string_tool/rand.go (about) 1 package string_tool 2 3 import ( 4 "math/rand" 5 "time" 6 "unsafe" 7 ) 8 9 const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 10 const ( 11 letterIdxBits = 6 // 6 bits to represent a letter index 12 letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits 13 letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits 14 ) 15 16 func RandString(n int) string { 17 src := rand.NewSource(time.Now().UnixNano()) 18 19 b := make([]byte, n) 20 // A src.Int63() generates 63 random bits, enough for letterIdxMax characters! 21 for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; { 22 if remain == 0 { 23 cache, remain = src.Int63(), letterIdxMax 24 } 25 if idx := int(cache & letterIdxMask); idx < len(letterBytes) { 26 b[i] = letterBytes[idx] 27 i-- 28 } 29 cache >>= letterIdxBits 30 remain-- 31 } 32 33 return *(*string)(unsafe.Pointer(&b)) 34 }