rand.go 548 Bytes
Newer Older
Jeromy's avatar
Jeromy committed
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
package testutil

import (
	"math/rand"
	"sync"
	"time"
)

var SeededRand *rand.Rand

func init() {
	SeededRand = NewSeededRand(time.Now().UTC().UnixNano())
}

func NewSeededRand(seed int64) *rand.Rand {
	src := rand.NewSource(seed)
	return rand.New(&LockedRandSource{src: src})
}

type LockedRandSource struct {
	lk  sync.Mutex
	src rand.Source
}

func (r *LockedRandSource) Int63() (n int64) {
	r.lk.Lock()
	n = r.src.Int63()
	r.lk.Unlock()
	return
}

func (r *LockedRandSource) Seed(seed int64) {
	r.lk.Lock()
	r.src.Seed(seed)
	r.lk.Unlock()
}