1
0

dice.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. )
  7. // Roll returns a non-negative number between 0 (inclusive) and n (exclusive).
  8. func Roll(n int) int {
  9. if n == 1 {
  10. return 0
  11. }
  12. return rand.Intn(n)
  13. }
  14. // RollInt63n returns a non-negative number between 0 (inclusive) and n (exclusive).
  15. func RollInt63n(n int64) int64 {
  16. if n == 1 {
  17. return 0
  18. }
  19. return rand.Int63n(n)
  20. }
  21. // Roll returns a non-negative number between 0 (inclusive) and n (exclusive).
  22. func RollDeterministic(n int, seed int64) int {
  23. if n == 1 {
  24. return 0
  25. }
  26. return rand.New(rand.NewSource(seed)).Intn(n)
  27. }
  28. // RollUint16 returns a random uint16 value.
  29. func RollUint16() uint16 {
  30. return uint16(rand.Int63() >> 47)
  31. }
  32. func RollUint64() uint64 {
  33. return rand.Uint64()
  34. }
  35. func NewDeterministicDice(seed int64) *DeterministicDice {
  36. return &DeterministicDice{rand.New(rand.NewSource(seed))}
  37. }
  38. type DeterministicDice struct {
  39. *rand.Rand
  40. }
  41. func (dd *DeterministicDice) Roll(n int) int {
  42. if n == 1 {
  43. return 0
  44. }
  45. return dd.Intn(n)
  46. }