rand.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package rand provides utilities related to randomization.
  14. package rand
  15. import (
  16. "math/rand"
  17. "sync"
  18. "time"
  19. )
  20. var letters = []rune("abcdefghijklmnopqrstuvwxyz0123456789")
  21. var numLetters = len(letters)
  22. var rng = struct {
  23. sync.Mutex
  24. rand *rand.Rand
  25. }{
  26. rand: rand.New(rand.NewSource(time.Now().UTC().UnixNano())),
  27. }
  28. // Intn generates an integer in range [0,max).
  29. // By design this should panic if input is invalid, <= 0.
  30. func Intn(max int) int {
  31. rng.Lock()
  32. defer rng.Unlock()
  33. return rng.rand.Intn(max)
  34. }
  35. // IntnRange generates an integer in range [min,max).
  36. // By design this should panic if input is invalid, <= 0.
  37. func IntnRange(min, max int) int {
  38. rng.Lock()
  39. defer rng.Unlock()
  40. return rng.rand.Intn(max-min) + min
  41. }
  42. // IntnRange generates an int64 integer in range [min,max).
  43. // By design this should panic if input is invalid, <= 0.
  44. func Int63nRange(min, max int64) int64 {
  45. rng.Lock()
  46. defer rng.Unlock()
  47. return rng.rand.Int63n(max-min) + min
  48. }
  49. // Seed seeds the rng with the provided seed.
  50. func Seed(seed int64) {
  51. rng.Lock()
  52. defer rng.Unlock()
  53. rng.rand = rand.New(rand.NewSource(seed))
  54. }
  55. // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n)
  56. // from the default Source.
  57. func Perm(n int) []int {
  58. rng.Lock()
  59. defer rng.Unlock()
  60. return rng.rand.Perm(n)
  61. }
  62. // String generates a random alphanumeric string n characters long. This will
  63. // panic if n is less than zero.
  64. func String(length int) string {
  65. b := make([]rune, length)
  66. for i := range b {
  67. b[i] = letters[Intn(numLetters)]
  68. }
  69. return string(b)
  70. }