github.com/v2fly/v2ray-core/v4@v4.45.2/common/dice/dice.go (about)

     1  // Package dice contains common functions to generate random number.
     2  // It also initialize math/rand with the time in seconds at launch time.
     3  package dice
     4  
     5  import (
     6  	"math/rand"
     7  	"time"
     8  )
     9  
    10  // Roll returns a non-negative number between 0 (inclusive) and n (exclusive).
    11  func Roll(n int) int {
    12  	if n == 1 {
    13  		return 0
    14  	}
    15  	return rand.Intn(n)
    16  }
    17  
    18  // Roll returns a non-negative number between 0 (inclusive) and n (exclusive).
    19  func RollDeterministic(n int, seed int64) int {
    20  	if n == 1 {
    21  		return 0
    22  	}
    23  	return rand.New(rand.NewSource(seed)).Intn(n)
    24  }
    25  
    26  // RollUint16 returns a random uint16 value.
    27  func RollUint16() uint16 {
    28  	return uint16(rand.Int63() >> 47)
    29  }
    30  
    31  func RollUint64() uint64 {
    32  	return rand.Uint64()
    33  }
    34  
    35  func NewDeterministicDice(seed int64) *DeterministicDice {
    36  	return &DeterministicDice{rand.New(rand.NewSource(seed))}
    37  }
    38  
    39  type DeterministicDice struct {
    40  	*rand.Rand
    41  }
    42  
    43  func (dd *DeterministicDice) Roll(n int) int {
    44  	if n == 1 {
    45  		return 0
    46  	}
    47  	return dd.Intn(n)
    48  }
    49  
    50  func init() {
    51  	rand.Seed(time.Now().Unix())
    52  }