2021-01-17 21:46:25 +08:00
|
|
|
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
2020-05-16 16:05:31 +08:00
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
|
|
|
|
|
|
|
package grand
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
// Buffer size for uint32 random number.
|
2021-03-10 21:19:11 +08:00
|
|
|
bufferChanSize = 10000
|
2020-05-16 16:05:31 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
// bufferChan is the buffer for random bytes,
|
|
|
|
// every item storing 4 bytes.
|
2021-03-10 21:19:11 +08:00
|
|
|
bufferChan = make(chan []byte, bufferChanSize)
|
2020-05-16 16:05:31 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
go asyncProducingRandomBufferBytesLoop()
|
|
|
|
}
|
|
|
|
|
|
|
|
// asyncProducingRandomBufferBytes is a named goroutine, which uses a asynchronous goroutine
|
|
|
|
// to produce the random bytes, and a buffer chan to store the random bytes.
|
|
|
|
// So it has high performance to generate random numbers.
|
|
|
|
func asyncProducingRandomBufferBytesLoop() {
|
2020-05-25 23:39:09 +08:00
|
|
|
var step int
|
2020-05-16 16:05:31 +08:00
|
|
|
for {
|
2020-05-25 23:39:09 +08:00
|
|
|
buffer := make([]byte, 1024)
|
2020-05-16 16:05:31 +08:00
|
|
|
if n, err := rand.Read(buffer); err != nil {
|
|
|
|
panic(err)
|
|
|
|
} else {
|
2020-05-25 23:39:09 +08:00
|
|
|
// The random buffer from system is very expensive,
|
|
|
|
// so fully reuse the random buffer by changing
|
2020-05-27 11:26:05 +08:00
|
|
|
// the step with a different number can
|
2020-05-25 23:39:09 +08:00
|
|
|
// improve the performance a lot.
|
2020-06-04 14:45:56 +08:00
|
|
|
// for _, step = range []int{4, 5, 6, 7} {
|
|
|
|
for _, step = range []int{4} {
|
2020-05-27 11:26:05 +08:00
|
|
|
for i := 0; i <= n-4; i += step {
|
|
|
|
bufferChan <- buffer[i : i+4]
|
|
|
|
}
|
2020-05-16 16:05:31 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|