/
rand.go
54 lines (45 loc) · 1.21 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
// Package rand provides utilities to generate random data.
package rand
import (
mr "math/rand"
"sync"
)
var (
globalRand = mr.New(mr.NewSource(1))
globalLock sync.Mutex
)
// Seed uses the provided seed value to initialize the generator to a deterministic state.
func Seed(s int64) {
globalLock.Lock()
defer globalLock.Unlock()
globalRand.Seed(s)
}
// Int31n returns, as an int32, a non-negative pseudo-random number in [0,n). It panics if n <= 0.
func Int31n(n int32) int32 {
globalLock.Lock()
defer globalLock.Unlock()
return globalRand.Int31n(n)
}
// Int63 returns a non-negative pseudo-random 63-bit integer as an int64.
func Int63() int64 {
globalLock.Lock()
defer globalLock.Unlock()
return globalRand.Int63()
}
// Float64 returns, as a float64, a pseudo-random number in [0.0,1.0).
func Float64() float64 {
globalLock.Lock()
defer globalLock.Unlock()
return globalRand.Float64()
}
// String returns a random string of n characters.
func String(n int) string {
globalLock.Lock()
defer globalLock.Unlock()
letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
s := make([]rune, n)
for i := range s {
s[i] = letters[globalRand.Intn(len(letters))]
}
return string(s)
}