mirror of
https://github.com/mjl-/mox.git
synced 2024-12-26 16:33:47 +03:00
don't expose functions on the prng that aren't mutex-protected
the current Intn calls in queue could be called concurrently, found by the race detector with upcoming new tests. best to just prevent any possible concurrent access.
This commit is contained in:
parent
47ebfa8152
commit
8550a5af45
1 changed files with 17 additions and 5 deletions
22
mox-/rand.go
22
mox-/rand.go
|
@ -9,20 +9,32 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
type rand struct {
|
type rand struct {
|
||||||
*mathrand.Rand
|
rand *mathrand.Rand
|
||||||
sync.Mutex
|
sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewPseudoRand returns a new PRNG seeded with random bytes from crypto/rand.
|
// NewPseudoRand returns a new PRNG seeded with random bytes from crypto/rand. Its
|
||||||
|
// functions can be called concurrently.
|
||||||
func NewPseudoRand() *rand {
|
func NewPseudoRand() *rand {
|
||||||
return &rand{Rand: mathrand.New(mathrand.NewSource(CryptoRandInt()))}
|
return &rand{rand: mathrand.New(mathrand.NewSource(CryptoRandInt()))}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *rand) Float64() float64 {
|
||||||
|
r.Lock()
|
||||||
|
defer r.Unlock()
|
||||||
|
return r.rand.Float64()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *rand) Intn(n int) int {
|
||||||
|
r.Lock()
|
||||||
|
defer r.Unlock()
|
||||||
|
return r.rand.Intn(n)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read can be called concurrently.
|
|
||||||
func (r *rand) Read(buf []byte) (int, error) {
|
func (r *rand) Read(buf []byte) (int, error) {
|
||||||
r.Lock()
|
r.Lock()
|
||||||
defer r.Unlock()
|
defer r.Unlock()
|
||||||
return r.Rand.Read(buf)
|
return r.rand.Read(buf)
|
||||||
}
|
}
|
||||||
|
|
||||||
// CryptoRandInt returns a cryptographically random number.
|
// CryptoRandInt returns a cryptographically random number.
|
||||||
|
|
Loading…
Reference in a new issue