drone-yaml/yaml/compiler/internal/rand/rand.go
2019-01-22 15:44:17 -08:00

37 lines
659 B
Go

package rand
import (
"crypto/rand"
)
var chars = []byte("abcdefghijklmnopqrstuvwxyz0123456789")
// random string length
const length = 32
// String returns a string value.
func String() string {
clen := len(chars)
maxrb := 255 - (256 % clen)
b := make([]byte, length)
r := make([]byte, length+(length/4)) // storage for random bytes.
i := 0
for {
if _, err := rand.Read(r); err != nil {
panic("rand: error reading random bytes")
}
for _, rb := range r {
c := int(rb)
if c > maxrb {
// Skip this number to avoid modulo bias.
continue
}
b[i] = chars[c%clen]
i++
if i == length {
return string(b)
}
}
}
}