Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fastrand: optimize Buf #33263

Merged
merged 4 commits into from
Apr 11, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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