@cryptotaxi247 / kubo / commits / cc7a869e3

threadsafe SeededRand

Juan Batiz-Benet committed Dec 19, 2014 at 21:01 UTC cc7a869e3d91180fe4cdc655945c2448e4688948
1 file changed +36
util/testutil/rand.go new
+36
@@ -0,0 +1,36 @@
1 +package testutil
2 +
3 +import (
4 + "math/rand"
5 + "sync"
6 + "time"
7 +)
8 +
9 +var SeededRand *rand.Rand
10 +
11 +func init() {
12 + SeededRand = NewSeededRand(time.Now().UTC().UnixNano())
13 +}
14 +
15 +func NewSeededRand(seed int64) *rand.Rand {
16 + src := rand.NewSource(seed)
17 + return rand.New(&LockedRandSource{src: src})
18 +}
19 +
20 +type LockedRandSource struct {
21 + lk sync.Mutex
22 + src rand.Source
23 +}
24 +
25 +func (r *LockedRandSource) Int63() (n int64) {
26 + r.lk.Lock()
27 + n = r.src.Int63()
28 + r.lk.Unlock()
29 + return
30 +}
31 +
32 +func (r *LockedRandSource) Seed(seed int64) {
33 + r.lk.Lock()
34 + r.src.Seed(seed)
35 + r.lk.Unlock()
36 +}