github.com/rjgonzale/pop/v5@v5.1.3-dev/internal/randx/string.go (about)

     1  package randx
     2  
     3  import (
     4  	"math/rand"
     5  	"time"
     6  )
     7  
     8  // source https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go
     9  
    10  const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    11  const (
    12  	letterIdxBits = 6                    // 6 bits to represent a letter index
    13  	letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
    14  	letterIdxMax  = 63 / letterIdxBits   // # of letter indices fitting in 63 bits
    15  )
    16  
    17  var src = newSafeSrc(rand.NewSource(time.Now().UnixNano()))
    18  
    19  // String generates a random string with the given length.
    20  func String(n int) string {
    21  	b := make([]byte, n)
    22  	// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
    23  	for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
    24  		if remain == 0 {
    25  			cache, remain = src.Int63(), letterIdxMax
    26  		}
    27  		if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
    28  			b[i] = letterBytes[idx]
    29  			i--
    30  		}
    31  		cache >>= letterIdxBits
    32  		remain--
    33  	}
    34  
    35  	return string(b)
    36  }