2016-02-03 16:49:38 -05:00
|
|
|
// Package dice contains common functions to generate random number.
|
|
|
|
// It also initialize math/rand with the time in seconds at launch time.
|
2021-02-16 15:31:50 -05:00
|
|
|
package dice
|
2016-01-21 16:45:44 -05:00
|
|
|
|
|
|
|
import (
|
2024-03-13 15:23:06 -04:00
|
|
|
crand "crypto/rand"
|
|
|
|
"github.com/v2fly/v2ray-core/v5/common"
|
|
|
|
"io"
|
|
|
|
"math/big"
|
2016-01-21 16:45:44 -05:00
|
|
|
"math/rand"
|
2016-01-25 05:47:22 -05:00
|
|
|
"time"
|
2016-01-21 16:45:44 -05:00
|
|
|
)
|
|
|
|
|
2016-02-03 16:49:38 -05:00
|
|
|
// Roll returns a non-negative number between 0 (inclusive) and n (exclusive).
|
2016-01-21 16:45:44 -05:00
|
|
|
func Roll(n int) int {
|
|
|
|
if n == 1 {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
return rand.Intn(n)
|
|
|
|
}
|
2016-01-25 05:47:22 -05:00
|
|
|
|
2024-03-13 15:23:06 -04:00
|
|
|
// RollWith returns a non-negative number between 0 (inclusive) and n (exclusive).
|
|
|
|
// Use random as the random source, if read fails, it panics.
|
|
|
|
func RollWith(n int, random io.Reader) int {
|
|
|
|
if n == 1 {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
mrand, err := crand.Int(random, big.NewInt(int64(n)))
|
|
|
|
common.Must(err)
|
|
|
|
return int(mrand.Int64())
|
|
|
|
}
|
|
|
|
|
2020-06-01 04:40:54 -04:00
|
|
|
// Roll returns a non-negative number between 0 (inclusive) and n (exclusive).
|
|
|
|
func RollDeterministic(n int, seed int64) int {
|
|
|
|
if n == 1 {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
return rand.New(rand.NewSource(seed)).Intn(n)
|
|
|
|
}
|
|
|
|
|
2017-04-27 05:54:15 -04:00
|
|
|
// RollUint16 returns a random uint16 value.
|
|
|
|
func RollUint16() uint16 {
|
2020-11-14 00:00:25 -05:00
|
|
|
return uint16(rand.Int63() >> 47)
|
2017-02-14 16:29:44 -05:00
|
|
|
}
|
|
|
|
|
2020-06-02 02:47:54 -04:00
|
|
|
func RollUint64() uint64 {
|
|
|
|
return rand.Uint64()
|
|
|
|
}
|
|
|
|
|
2020-10-11 07:22:46 -04:00
|
|
|
func NewDeterministicDice(seed int64) *DeterministicDice {
|
|
|
|
return &DeterministicDice{rand.New(rand.NewSource(seed))}
|
2020-06-02 02:47:54 -04:00
|
|
|
}
|
|
|
|
|
2020-10-11 07:22:46 -04:00
|
|
|
type DeterministicDice struct {
|
2020-06-02 02:47:54 -04:00
|
|
|
*rand.Rand
|
|
|
|
}
|
|
|
|
|
2020-10-11 07:22:46 -04:00
|
|
|
func (dd *DeterministicDice) Roll(n int) int {
|
2020-06-02 02:47:54 -04:00
|
|
|
if n == 1 {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
return dd.Intn(n)
|
|
|
|
}
|
|
|
|
|
2016-01-25 05:47:22 -05:00
|
|
|
func init() {
|
|
|
|
rand.Seed(time.Now().Unix())
|
|
|
|
}
|