github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/workload/workloadimpl/random.go (about) 1 // Copyright 2019 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package workloadimpl 12 13 import ( 14 "math" 15 16 "golang.org/x/exp/rand" 17 ) 18 19 // RandStringFast is a non-specialized random string generator with an even 20 // distribution of alphabet in the output. 21 func RandStringFast(rng rand.Source, buf []byte, alphabet string) { 22 // We could pull these computations out to be done once per alphabet, but at 23 // that point, you likely should consider PrecomputedRand. 24 alphabetLen := uint64(len(alphabet)) 25 // floor(log(math.MaxUint64)/log(alphabetLen)) 26 lettersCharsPerRand := uint64(math.Log(float64(math.MaxUint64)) / math.Log(float64(alphabetLen))) 27 28 var r, charsLeft uint64 29 for i := 0; i < len(buf); i++ { 30 if charsLeft == 0 { 31 r = rng.Uint64() 32 charsLeft = lettersCharsPerRand 33 } 34 buf[i] = alphabet[r%alphabetLen] 35 r = r / alphabetLen 36 charsLeft-- 37 } 38 }