Repository navigation
Expand file tree
/
Copy pathgrand_intn.go
More file actions
64 lines (58 loc) · 1.65 KB
/
Copy pathgrand_intn.go
File metadata and controls
64 lines (58 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// 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"
"encoding/binary"
"os"
)
const (
gBUFFER_SIZE = 10000 // 缓冲区uint32数量大小
)
var (
bufferChan = make(chan uint32, gBUFFER_SIZE)
)
// 使用缓冲区实现快速的随机数生成
func init() {
step := 0
buffer := make([]byte, 1024)
go func() {
for {
if n, err := rand.Read(buffer); err != nil {
panic(err)
os.Exit(1)
} else {
// 使用缓冲区数据进行一次完整的随机数生成
for i := 0; i < n - 4; {
bufferChan <- binary.LittleEndian.Uint32(buffer[i : i + 4])
i ++
}
// 充分利用缓冲区数据,随机索引递增
for i := 0; i < n; i++ {
step = int(buffer[0])%10
if step != 0 {
break
}
}
if step == 0 {
step = 2
}
for i := 0; i < n - 4; {
bufferChan <- binary.BigEndian.Uint32(buffer[i : i + 4])
i += step
}
}
}
}()
}
// 自定义的 rand.Intn ,绝对随机, 返回: [0, max)
func Intn (max int) int {
n := int(<- bufferChan)%max
if (max > 0 && n < 0) || (max < 0 && n > 0) {
return -n
}
return n
}