github.com/sandwich-go/boost@v1.3.29/xrand/string.go (about) 1 package xrand 2 3 import ( 4 "fmt" 5 "time" 6 "unsafe" 7 ) 8 9 const ( 10 letterBytes = "abcdefghijklmnopqrstuvwxyz" 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 var nowFunc = time.Now 17 18 // StringWithTimestamp 随机 n 个字符的字符串,并以当前时间戳做后缀 19 func StringWithTimestamp(n int) string { 20 return fmt.Sprintf("%s_%d", String(n), nowFunc().Unix()) 21 } 22 23 // String 随机 n 个字符的字符串 24 func String(n int) string { 25 b := make([]byte, n) 26 // A src.Int63() generates 63 random bits, enough for letterIdxMax characters! 27 for i, cache, remain := n-1, FastRand(), letterIdxMax; i >= 0; { 28 if remain == 0 { 29 cache, remain = FastRand(), letterIdxMax 30 } 31 if idx := int(cache & letterIdxMask); idx < len(letterBytes) { 32 b[i] = letterBytes[idx] 33 i-- 34 } 35 cache >>= letterIdxBits 36 remain-- 37 } 38 return *(*string)(unsafe.Pointer(&b)) 39 }