-
Notifications
You must be signed in to change notification settings - Fork 205
/
rand.go
120 lines (97 loc) · 2.27 KB
/
rand.go
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package rand
import (
"crypto/sha256"
"encoding/binary"
"math/rand"
"sync"
"time"
)
func generateSeed(data []byte) int64 {
sum256 := sha256.Sum256(data)
seed := int64(binary.LittleEndian.Uint64(sum256[0:8]))
return seed
}
// New returns a new RPNG instance properly seeded
func New(data []byte) *rand.Rand {
seed := generateSeed(data)
source := rand.NewSource(seed)
return rand.New(source)
}
// Seed re-seeds an existing RPNG instance
func Seed(rng *rand.Rand, data []byte) {
seed := generateSeed(data)
rng.Seed(seed)
}
// rand wrapper for protocol structs which hosts the same seed for deterministic unified random distribution
// we set the seed once for the entire process.
type threadSafeRand struct {
lock sync.Mutex // we have no reads, just writes, so using a sync.Mutex.
rand *rand.Rand
}
func (t *threadSafeRand) Intn(n int) int {
t.lock.Lock()
defer t.lock.Unlock()
return t.rand.Intn(n)
}
func (t *threadSafeRand) Float64() float64 {
t.lock.Lock()
defer t.lock.Unlock()
return t.rand.Float64()
}
func (t *threadSafeRand) Uint32() uint32 {
t.lock.Lock()
defer t.lock.Unlock()
return t.rand.Uint32()
}
func (t *threadSafeRand) Uint64() uint64 {
t.lock.Lock()
defer t.lock.Unlock()
return t.rand.Uint64()
}
func (t *threadSafeRand) Int63() int64 {
t.lock.Lock()
defer t.lock.Unlock()
return t.rand.Int63()
}
func (t *threadSafeRand) Int63n(n int64) int64 {
t.lock.Lock()
defer t.lock.Unlock()
return t.rand.Int63n(n)
}
func (t *threadSafeRand) NormFloat64() float64 {
t.lock.Lock()
defer t.lock.Unlock()
return t.rand.NormFloat64()
}
var protocolRand *threadSafeRand
func Initialized() bool {
return protocolRand != nil
}
func InitRandomSeed() {
seed := time.Now().UnixNano()
protocolRand = &threadSafeRand{rand: rand.New(rand.NewSource(seed))}
}
func SetSpecificSeed(seed int64) {
protocolRand = &threadSafeRand{rand: rand.New(rand.NewSource(seed))}
}
func Intn(n int) int {
return protocolRand.Intn(n)
}
func Float64() float64 {
return protocolRand.Float64()
}
func Uint32() uint32 {
return protocolRand.Uint32()
}
func Uint64() uint64 {
return protocolRand.Uint64()
}
func Int63() int64 {
return protocolRand.Int63()
}
func Int63n(n int64) int64 {
return protocolRand.Int63n(n)
}
func NormFloat64() float64 {
return protocolRand.NormFloat64()
}