This repository has been archived by the owner on Sep 11, 2021. It is now read-only.
forked from valyala/fastrand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrand.go
82 lines (69 loc) · 2.13 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
// Package rand implements fast pesudorandom number generator
// that should scale well on multi-CPU systems.
//
// Use crypto/rand instead of this package for generating
// cryptographically secure random numbers.
package rand
import (
"crypto/rand"
"encoding/binary"
"math"
"sync"
)
// Pool for the random number generators
var pool32 = sync.Pool{
New: func() interface{} {
return newRand32().Seed(seed(), seed())
},
}
// Pool for the random number generators
var pool64 = sync.Pool{
New: func() interface{} {
return newRand64().Seed(seed(), seed(), seed(), seed())
},
}
// seed generates a crypto-random seed. This is slow but is used to seed the random
// number generators themselves.
func seed() uint64 {
buffer := make([]byte, 8)
rand.Read(buffer)
return binary.LittleEndian.Uint64(buffer[:8])
}
// ----------------------------------------------------------------------------------------------
// Bool returns, as a bool, a pseudo-random number
func Bool() bool {
return Uint32n(2) == 0
}
// Uint32 returns a tread-safe, non-cryptographic pseudorandom uint32.
func Uint32() uint32 {
rng := pool32.Get().(*rand32)
defer pool32.Put(rng)
return rng.Random()
}
// Uint32n returns a tread-safe, non-cryptographic pseudorandom uint32 in the range [0..maxN).
func Uint32n(maxN uint32) uint32 {
rng := pool32.Get().(*rand32)
defer pool32.Put(rng)
return rng.Bounded(maxN)
}
// Float32 returns, as a float32, a pseudo-random number in [0.0,1.0)
func Float32() float32 {
return math.Float32frombits(Uint32()) / (1 << 31)
}
// ----------------------------------------------------------------------------------------------
// Uint64 returns a tread-safe, non-cryptographic pseudorandom uint64.
func Uint64() uint64 {
rng := pool64.Get().(*rand64)
defer pool64.Put(rng)
return rng.Random()
}
// Uint64n returns a tread-safe, non-cryptographic pseudorandom uint64 in the range [0..maxN).
func Uint64n(maxN uint64) uint64 {
rng := pool64.Get().(*rand64)
defer pool64.Put(rng)
return rng.Bounded(maxN)
}
// Float64 returns, as a float64, a pseudo-random number in [0.0,1.0)
func Float64() float64 {
return math.Float64frombits(Uint64()) / (1 << 63)
}