rand.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package internal
  2. import (
  3. "math/rand"
  4. "sync"
  5. "time"
  6. )
  7. var (
  8. seededRand = struct {
  9. sync.Mutex
  10. *rand.Rand
  11. }{
  12. Rand: rand.New(rand.NewSource(int64(time.Now().UnixNano()))),
  13. }
  14. )
  15. // RandUint64 returns a random uint64.
  16. //
  17. // IMPORTANT! The default rand package functions are not used, since we want to
  18. // minimize the chance that different Go processes duplicate the same
  19. // transaction id. (Note that the rand top level functions "use a default
  20. // shared Source that produces a deterministic sequence of values each time a
  21. // program is run" (and we don't seed the shared Source to avoid changing
  22. // customer apps' behavior)).
  23. func RandUint64() uint64 {
  24. seededRand.Lock()
  25. defer seededRand.Unlock()
  26. u1 := seededRand.Uint32()
  27. u2 := seededRand.Uint32()
  28. return (uint64(u1) << 32) | uint64(u2)
  29. }
  30. // RandUint32 returns a random uint32.
  31. func RandUint32() uint32 {
  32. seededRand.Lock()
  33. defer seededRand.Unlock()
  34. return seededRand.Uint32()
  35. }
  36. // RandFloat32 returns a random float32 between 0.0 and 1.0.
  37. func RandFloat32() float32 {
  38. seededRand.Lock()
  39. defer seededRand.Unlock()
  40. for {
  41. if r := seededRand.Float32(); 0.0 != r {
  42. return r
  43. }
  44. }
  45. }
  46. // RandUint64N returns a random int64 that's
  47. // between 0 and the passed in max, non-inclusive
  48. func RandUint64N(max uint64) uint64 {
  49. return RandUint64() % max
  50. }