Skip to content

Commit

Permalink
fastrand: optimize Buf (#33263)
Browse files Browse the repository at this point in the history
close #33240
  • Loading branch information
zhangyunhao116 authored Apr 11, 2022
1 parent 48efcf6 commit 53fc117
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion util/fastrand/random.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,32 @@
package fastrand

import (
"math/bits"
_ "unsafe" // required by go:linkname
)

// wyrand is a fast PRNG. See https://github.com/wangyi-fudan/wyhash
type wyrand uint64

func _wymix(a, b uint64) uint64 {
hi, lo := bits.Mul64(a, b)
return hi ^ lo
}

func (r *wyrand) Next() uint64 {
*r += wyrand(0xa0761d6478bd642f)
return _wymix(uint64(*r), uint64(*r^wyrand(0xe7037ed1a0b428db)))
}

// Buf generates a random string using ASCII characters but avoid separator character.
// See https://github.com/mysql/mysql-server/blob/5.7/mysys_ssl/crypt_genhash_impl.cc#L435
func Buf(size int) []byte {
buf := make([]byte, size)
r := wyrand(Uint32())
for i := 0; i < size; i++ {
buf[i] = byte(Uint32N(127))
// This is similar to Uint32() % n, but faster.
// See https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
buf[i] = byte(uint32(uint64(uint32(r.Next())) * uint64(127) >> 32))
if buf[i] == 0 || buf[i] == byte('$') {
buf[i]++
}
Expand Down

0 comments on commit 53fc117

Please sign in to comment.