-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrandom.go
56 lines (44 loc) · 916 Bytes
/
random.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
package tracer
import (
"fmt"
"math/rand"
"sync"
"time"
)
var (
seedGenerator = NewRand(time.Now().UnixNano())
randPool = sync.Pool{
New: func() interface{} {
return rand.NewSource(seedGenerator.Int63())
},
}
)
func MakeRandomNumber() uint64 {
generator := randPool.Get().(rand.Source)
defer randPool.Put(generator)
return uint64(generator.Int63())
}
func MockID() string {
rid := MakeRandomNumber()
return fmt.Sprintf("%016x", rid)
}
type lockedSource struct {
mu sync.Mutex
src rand.Source
}
// NewRand returns a rand.Rand that is threadsafe.
func NewRand(seed int64) *rand.Rand {
return rand.New(&lockedSource{src: rand.NewSource(seed)})
}
func (r *lockedSource) Int63() (n int64) {
r.mu.Lock()
defer r.mu.Unlock()
n = r.src.Int63()
return
}
// Seed implements Seed() of Source
func (r *lockedSource) Seed(seed int64) {
r.mu.Lock()
defer r.mu.Unlock()
r.src.Seed(seed)
}