github.com/songzhibin97/gkit@v1.2.13/tools/rand_string/rand_string.go (about)

     1  package rand_string
     2  
     3  import (
     4  	"math/rand"
     5  	"time"
     6  )
     7  
     8  const letterBytes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
     9  const numberBytes = "0123456789"
    10  
    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 = rand.NewSource(time.Now().UnixNano())
    18  
    19  func RandomLetter(n int) string {
    20  	return random(letterBytes, n)
    21  }
    22  
    23  func RandomInt(n int) string {
    24  	return random(numberBytes, n)
    25  }
    26  
    27  func RandomBytes(bytes string, n int) string  {
    28  	return random(bytes, n)
    29  }
    30  
    31  func random(bytes string, n int) string {
    32  	b := make([]byte, n)
    33  	for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
    34  		if remain == 0 {
    35  			cache, remain = src.Int63(), letterIdxMax
    36  		}
    37  		if idx := int(cache & letterIdxMask); idx < len(bytes) {
    38  			b[i] = bytes[idx]
    39  			i--
    40  		}
    41  		cache >>= letterIdxBits
    42  		remain--
    43  	}
    44  
    45  	return string(b)
    46  }