mirror of
https://github.com/mjl-/mox.git
synced 2025-07-10 06:34:40 +03:00
switch to math/rand/v2 in most places
this allows removing some ugly instantiations of an rng based on the current time. Intn is now IntN for our concurrency-safe prng wrapper to match the randv2 api. v2 exists since go1.22, which we already require.
This commit is contained in:
20
mox-/rand.go
20
mox-/rand.go
@ -4,19 +4,23 @@ import (
|
||||
cryptorand "crypto/rand"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
mathrand "math/rand"
|
||||
mathrand2 "math/rand/v2"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type rand struct {
|
||||
rand *mathrand.Rand
|
||||
rand *mathrand2.Rand
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
// NewPseudoRand returns a new PRNG seeded with random bytes from crypto/rand. Its
|
||||
// functions can be called concurrently.
|
||||
func NewPseudoRand() *rand {
|
||||
return &rand{rand: mathrand.New(mathrand.NewSource(CryptoRandInt()))}
|
||||
var seed [32]byte
|
||||
if _, err := cryptorand.Read(seed[:]); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return &rand{rand: mathrand2.New(mathrand2.NewChaCha8(seed))}
|
||||
}
|
||||
|
||||
func (r *rand) Float64() float64 {
|
||||
@ -25,16 +29,10 @@ func (r *rand) Float64() float64 {
|
||||
return r.rand.Float64()
|
||||
}
|
||||
|
||||
func (r *rand) Intn(n int) int {
|
||||
func (r *rand) IntN(n int) int {
|
||||
r.Lock()
|
||||
defer r.Unlock()
|
||||
return r.rand.Intn(n)
|
||||
}
|
||||
|
||||
func (r *rand) Read(buf []byte) (int, error) {
|
||||
r.Lock()
|
||||
defer r.Unlock()
|
||||
return r.rand.Read(buf)
|
||||
return r.rand.IntN(n)
|
||||
}
|
||||
|
||||
// CryptoRandInt returns a cryptographically random number.
|
||||
|
Reference in New Issue
Block a user