dice.go 1013 B

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