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:
Mechiel Lukkien 2024-03-07 10:05:35 +01:00
parent 47ebfa8152
commit 8550a5af45
No known key found for this signature in database

View file

@ -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.