github.com/15mga/kiwi@v0.0.2-0.20240324021231-b95d5c3ac751/util/rand.go (about)

     1  package util
     2  
     3  import (
     4  	"math/rand"
     5  	"time"
     6  )
     7  
     8  const (
     9  	letters       = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    10  	letterIdxBits = 6
    11  	letterIdxMask = 1<<letterIdxBits - 1
    12  	letterIdxMax  = 63 / letterIdxBits
    13  )
    14  
    15  var (
    16  	randSrc = rand.NewSource(time.Now().UnixNano())
    17  )
    18  
    19  func RandStr(n int) string {
    20  	b := make([]byte, n)
    21  	for i, cache, remain := n-1, randSrc.Int63(), letterIdxMax; i > -1; {
    22  		if remain == 0 {
    23  			cache, remain = randSrc.Int63(), letterIdxMax
    24  		}
    25  		if idx := int(cache & letterIdxMask); idx < len(letters) {
    26  			b[i] = letters[idx]
    27  			i--
    28  		}
    29  		cache >>= letterIdxBits
    30  		remain--
    31  	}
    32  	return BytesToStr(b)
    33  }