sacrificial-socket/rng.go

29 lines
531 B
Go
Raw Permalink Normal View History

2018-05-18 10:48:40 +08:00
package ss
2018-05-18 10:55:13 +08:00
import (
2018-05-18 10:48:40 +08:00
"math/rand"
"sync"
"time"
)
//RNG is a random number generator that is safe for concurrent use by multiple go routines
type RNG struct {
r *rand.Rand
mu *sync.Mutex
}
2018-05-19 03:10:48 +08:00
//Read reads len(b) random bytes into b and always returns a nil error
2018-05-18 10:48:40 +08:00
func (r *RNG) Read(b []byte) (int, error) {
r.mu.Lock()
defer r.mu.Unlock()
return r.r.Read(b)
}
//NewRNG creates a new random number generator
func NewRNG() *RNG {
return &RNG{
r: rand.New(rand.NewSource(time.Now().UnixNano())),
mu: &sync.Mutex{},
}
}