mirror of
https://github.com/Mezeporta/Erupe.git
synced 2026-03-22 07:32:32 +01:00
fix: resolve data race in token.RNG global
Wrap *rand.Rand in a mutex-protected SafeRand type to make the global RNG safe for concurrent use across goroutines. The previous bare *rand.Rand caused data races detected by go test -race.
This commit is contained in:
@@ -2,10 +2,37 @@ package token
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var RNG = NewRNG()
|
||||
// SafeRand is a concurrency-safe wrapper around *rand.Rand.
|
||||
type SafeRand struct {
|
||||
mu sync.Mutex
|
||||
rng *rand.Rand
|
||||
}
|
||||
|
||||
func NewSafeRand() *SafeRand {
|
||||
return &SafeRand{
|
||||
rng: rand.New(rand.NewSource(time.Now().UnixNano())),
|
||||
}
|
||||
}
|
||||
|
||||
func (sr *SafeRand) Intn(n int) int {
|
||||
sr.mu.Lock()
|
||||
v := sr.rng.Intn(n)
|
||||
sr.mu.Unlock()
|
||||
return v
|
||||
}
|
||||
|
||||
func (sr *SafeRand) Uint32() uint32 {
|
||||
sr.mu.Lock()
|
||||
v := sr.rng.Uint32()
|
||||
sr.mu.Unlock()
|
||||
return v
|
||||
}
|
||||
|
||||
var RNG = NewSafeRand()
|
||||
|
||||
// Generate returns an alphanumeric token of specified length
|
||||
func Generate(length int) string {
|
||||
@@ -16,8 +43,3 @@ func Generate(length int) string {
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// NewRNG returns a new NewRNG generator
|
||||
func NewRNG() *rand.Rand {
|
||||
return rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user