github.com/moleculer-go/moleculer@v0.3.3/util/randomString.go (about)

     1  package util
     2  
     3  import (
     4  	"math/rand"
     5  	"sync"
     6  	"time"
     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  var randomSource = rand.NewSource(time.Now().UnixNano())
    17  var randomSourceMu = sync.Mutex{}
    18  
    19  func RandomString(size int) string {
    20  	randomSourceMu.Lock()
    21  	defer randomSourceMu.Unlock()
    22  
    23  	buffer := make([]byte, size)
    24  	// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
    25  	for index, cache, remain := size-1, randomSource.Int63(), letterIdxMax; index >= 0; {
    26  		if remain == 0 {
    27  			cache, remain = randomSource.Int63(), letterIdxMax
    28  		}
    29  		if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
    30  			buffer[index] = letterBytes[idx]
    31  			index--
    32  		}
    33  		cache >>= letterIdxBits
    34  		remain--
    35  	}
    36  	return string(buffer)
    37  }