dice.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 "github.com/xtls/xray-core/common/dice"
  4. import (
  5. "math/rand"
  6. "time"
  7. )
  8. // Roll returns a non-negative number between 0 (inclusive) and n (exclusive).
  9. func Roll(n int) int {
  10. if n == 1 {
  11. return 0
  12. }
  13. return rand.Intn(n)
  14. }
  15. // Roll returns a non-negative number between 0 (inclusive) and n (exclusive).
  16. func RollDeterministic(n int, seed int64) int {
  17. if n == 1 {
  18. return 0
  19. }
  20. return rand.New(rand.NewSource(seed)).Intn(n)
  21. }
  22. // RollUint16 returns a random uint16 value.
  23. func RollUint16() uint16 {
  24. return uint16(rand.Int63() >> 47)
  25. }
  26. func RollUint64() uint64 {
  27. return rand.Uint64()
  28. }
  29. func NewDeterministicDice(seed int64) *DeterministicDice {
  30. return &DeterministicDice{rand.New(rand.NewSource(seed))}
  31. }
  32. type DeterministicDice struct {
  33. *rand.Rand
  34. }
  35. func (dd *DeterministicDice) Roll(n int) int {
  36. if n == 1 {
  37. return 0
  38. }
  39. return dd.Intn(n)
  40. }
  41. func init() {
  42. rand.Seed(time.Now().Unix())
  43. }