Seed math/rand more efficiently
This commit is contained in:
parent
d0ddca7fe1
commit
4e69e241dd
@ -1,20 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"flag"
|
||||
"fmt"
|
||||
|
||||
//"log"
|
||||
crypto_rand "crypto/rand"
|
||||
|
||||
"math/rand"
|
||||
math_rand "math/rand"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"git.kill0.net/chill9/beepboop/command"
|
||||
"git.kill0.net/chill9/beepboop/lib"
|
||||
|
||||
"github.com/bwmarrin/discordgo"
|
||||
log "github.com/sirupsen/logrus"
|
||||
@ -60,7 +59,7 @@ func main() {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
}
|
||||
|
||||
seedRand()
|
||||
lib.SeedMathRand()
|
||||
|
||||
viper.SetDefault("handler.reaction.emojis", defaultReactions)
|
||||
viper.SetEnvPrefix("BEEPBOOP")
|
||||
@ -178,16 +177,3 @@ func contains[T comparable](s []T, v T) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func seedRand() {
|
||||
var b [8]byte
|
||||
|
||||
_, err := crypto_rand.Read(b[:])
|
||||
if err != nil {
|
||||
log.Panicf("cannot seed math/rand: %s", err)
|
||||
}
|
||||
|
||||
log.Debugf("seeding math/rand %+v %+v", b, binary.LittleEndian.Uint64(b[:]))
|
||||
|
||||
math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))
|
||||
}
|
||||
|
34
lib/rand.go
Normal file
34
lib/rand.go
Normal file
@ -0,0 +1,34 @@
|
||||
package lib
|
||||
|
||||
import (
|
||||
crand "crypto/rand"
|
||||
"math"
|
||||
"math/big"
|
||||
"math/rand"
|
||||
"sync"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var (
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
// SeedMathRand Credit: https://github.com/hashicorp/consul/blob/main/lib/rand.go
|
||||
func SeedMathRand() {
|
||||
var (
|
||||
n *big.Int
|
||||
err error
|
||||
)
|
||||
|
||||
once.Do(func() {
|
||||
n, err = crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
|
||||
if err != nil {
|
||||
log.Errorf("cannot seed math/rand: %s", err)
|
||||
}
|
||||
|
||||
log.Debugf("seeding math/rand %+v", n.Int64())
|
||||
|
||||
rand.Seed(n.Int64())
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue
Block a user