grpcrand.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //go:build !go1.21
  2. // TODO: when this file is deleted (after Go 1.20 support is dropped), delete
  3. // all of grpcrand and call the rand package directly.
  4. /*
  5. *
  6. * Copyright 2018 gRPC authors.
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. *
  20. */
  21. // Package grpcrand implements math/rand functions in a concurrent-safe way
  22. // with a global random source, independent of math/rand's global source.
  23. package grpcrand
  24. import (
  25. "math/rand"
  26. "sync"
  27. "time"
  28. )
  29. var (
  30. r = rand.New(rand.NewSource(time.Now().UnixNano()))
  31. mu sync.Mutex
  32. )
  33. // Int implements rand.Int on the grpcrand global source.
  34. func Int() int {
  35. mu.Lock()
  36. defer mu.Unlock()
  37. return r.Int()
  38. }
  39. // Int63n implements rand.Int63n on the grpcrand global source.
  40. func Int63n(n int64) int64 {
  41. mu.Lock()
  42. defer mu.Unlock()
  43. return r.Int63n(n)
  44. }
  45. // Intn implements rand.Intn on the grpcrand global source.
  46. func Intn(n int) int {
  47. mu.Lock()
  48. defer mu.Unlock()
  49. return r.Intn(n)
  50. }
  51. // Int31n implements rand.Int31n on the grpcrand global source.
  52. func Int31n(n int32) int32 {
  53. mu.Lock()
  54. defer mu.Unlock()
  55. return r.Int31n(n)
  56. }
  57. // Float64 implements rand.Float64 on the grpcrand global source.
  58. func Float64() float64 {
  59. mu.Lock()
  60. defer mu.Unlock()
  61. return r.Float64()
  62. }
  63. // Uint64 implements rand.Uint64 on the grpcrand global source.
  64. func Uint64() uint64 {
  65. mu.Lock()
  66. defer mu.Unlock()
  67. return r.Uint64()
  68. }
  69. // Uint32 implements rand.Uint32 on the grpcrand global source.
  70. func Uint32() uint32 {
  71. mu.Lock()
  72. defer mu.Unlock()
  73. return r.Uint32()
  74. }
  75. // ExpFloat64 implements rand.ExpFloat64 on the grpcrand global source.
  76. func ExpFloat64() float64 {
  77. mu.Lock()
  78. defer mu.Unlock()
  79. return r.ExpFloat64()
  80. }
  81. // Shuffle implements rand.Shuffle on the grpcrand global source.
  82. var Shuffle = func(n int, f func(int, int)) {
  83. mu.Lock()
  84. defer mu.Unlock()
  85. r.Shuffle(n, f)
  86. }