mardi 24 octobre 2017

Efficient way to to generate a random Hex string of a fixed length in Golang?

I need to generate a lot of a random hex string of a fixed length. I find this solution How to generate a random string of a fixed length in golang?

I'm doing something like this:

const letterBytes = "abcdef0123456789"
const (
    letterIdxBits = 6                    // 6 bits to represent a letter index
    letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
    letterIdxMax  = 63 / letterIdxBits   // # of letter indices fitting in 63 bits
)

var src = rand.NewSource(time.Now().UnixNano())

// RandStringBytesMaskImprSrc ...
// Src: http://ift.tt/2z2HvoO
func RandStringBytesMaskImprSrc(n int) string {
    b := make([]byte, n)
    // A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
    for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
        if remain == 0 {
            cache, remain = src.Int63(), letterIdxMax
        }
        if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
            b[i] = letterBytes[idx]
            i--
        }
        cache >>= letterIdxBits
        remain--
    }

    return string(b)
}

var tryArr = make([]string, 10000)
for i := 0; i < 10000; i++ {
    tryArr[i] = RandStringBytesMaskImprSrc(8)
}

But I got this panic error

panic: runtime error: index out of range

goroutine 36 [running]:
math/rand.(*rngSource).Int63(0x11bb1300, 0x8, 0x8)
    D:/Applications/Go/src/math/rand/rng.go:231 +0xa0
main.RandStringBytesMaskImprSrc(0x8, 0x11f81be8, 0x8)
    main.go:60 +0x5f

The errror seem to be in for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0;, but I don't find why there is this error.

What is the fastest and simplest way to generate a lot of a random hex string of a fixed length in Go?




Aucun commentaire:

Enregistrer un commentaire