bb/lib/rand.go

58 lines
907 B
Go
Raw Normal View History

2022-08-04 04:24:27 +00:00
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
2022-08-04 16:14:35 +00:00
func SeedMathRand() error {
2022-08-04 04:24:27 +00:00
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)
2022-08-04 16:14:35 +00:00
} else {
log.Debugf("seeding math/rand %+v", n.Int64())
rand.Seed(n.Int64())
2022-08-04 04:24:27 +00:00
}
})
2022-08-04 16:14:35 +00:00
return err
2022-08-04 04:24:27 +00:00
}
2022-08-24 14:06:00 +00:00
func RandInt(min int, max int) int {
return rand.Intn(max-min+1) + min
}
2022-09-14 13:34:51 +00:00
func MapRand[K comparable, V any](m map[K]V) V {
n := rand.Intn(len(m))
i := 0
for _, v := range m {
if i == n {
return v
}
i++
}
panic("unreachable")
}
2022-09-15 14:32:37 +00:00
func MapRandKey[K comparable, V any](m map[K]V) K {
keys := MapKeys(m)
n := rand.Intn(len(m))
return keys[n]
}