github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/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 // import "v2ray.com/core/common/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.Intn(65536))
    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  }