Skip to content

Commit

Permalink
Optimize random string generator to avoid multiple locks & use int bi…
Browse files Browse the repository at this point in the history
…t-masking
  • Loading branch information
shyamjvs committed Oct 12, 2017
1 parent 0564d52 commit a867f2a
Showing 1 changed file with 33 additions and 8 deletions.
41 changes: 33 additions & 8 deletions staging/src/k8s.io/apimachinery/pkg/util/rand/rand.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,17 +70,42 @@ func Perm(n int) []int {
return rng.rand.Perm(n)
}

// We omit vowels from the set of available characters to reduce the chances
// of "bad words" being formed.
var alphanums = []rune("bcdfghjklmnpqrstvwxz2456789")
const (
// We omit vowels from the set of available characters to reduce the chances
// of "bad words" being formed.
alphanums = "bcdfghjklmnpqrstvwxz2456789"
// No. of bits required to index into alphanums string.
alphanumsIdxBits = 5
// Mask used to extract last alphanumsIdxBits of an int.
alphanumsIdxMask = 1<<alphanumsIdxBits - 1
// No. of random letters we can extract from a single int63.
maxAlphanumsPerInt = 63 / alphanumsIdxBits
)

// String generates a random alphanumeric string, without vowels, which is n
// characters long. This will panic if n is less than zero.
func String(length int) string {
b := make([]rune, length)
for i := range b {
b[i] = alphanums[Intn(len(alphanums))]
}
// How the random string is created:
// - we generate random int63's
// - from each int63, we are extracting multiple random letters by bit-shifting and masking
// - if some index is out of range of alphanums we neglect it (unlikely to happen multiple times in a row)
func String(n int) string {
b := make([]byte, n)
rng.Lock()
defer rng.Unlock()

randomInt63 := rng.rand.Int63()
remaining := maxAlphanumsPerInt
for i := 0; i < n; {
if remaining == 0 {
randomInt63, remaining = rng.rand.Int63(), maxAlphanumsPerInt
}
if idx := int(randomInt63 & alphanumsIdxMask); idx < len(alphanums) {
b[i] = alphanums[idx]
i++
}
randomInt63 >>= alphanumsIdxBits
remaining--
}
return string(b)
}

Expand Down

0 comments on commit a867f2a

Please sign in to comment.