rand.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. // Copyright 2019 Yunion
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /*
  15. Copyright 2015 The Kubernetes Authors.
  16. Licensed under the Apache License, Version 2.0 (the "License");
  17. you may not use this file except in compliance with the License.
  18. You may obtain a copy of the License at
  19. http://www.apache.org/licenses/LICENSE-2.0
  20. Unless required by applicable law or agreed to in writing, software
  21. distributed under the License is distributed on an "AS IS" BASIS,
  22. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. See the License for the specific language governing permissions and
  24. limitations under the License.
  25. */
  26. // Package rand provides utilities related to randomization.
  27. package rand
  28. import (
  29. "math/rand"
  30. "sync"
  31. "time"
  32. )
  33. var rng = struct {
  34. sync.Mutex
  35. rand *rand.Rand
  36. }{
  37. rand: rand.New(rand.NewSource(time.Now().UTC().UnixNano())),
  38. }
  39. // Intn generates an integer in range [0,max).
  40. // By design this should panic if input is invalid, <= 0.
  41. func Intn(max int) int {
  42. rng.Lock()
  43. defer rng.Unlock()
  44. return rng.rand.Intn(max)
  45. }
  46. // IntnRange generates an integer in range [min,max).
  47. // By design this should panic if input is invalid, <= 0.
  48. func IntnRange(min, max int) int {
  49. rng.Lock()
  50. defer rng.Unlock()
  51. return rng.rand.Intn(max-min) + min
  52. }
  53. // IntnRange generates an int64 integer in range [min,max).
  54. // By design this should panic if input is invalid, <= 0.
  55. func Int63nRange(min, max int64) int64 {
  56. rng.Lock()
  57. defer rng.Unlock()
  58. return rng.rand.Int63n(max-min) + min
  59. }
  60. // Seed seeds the rng with the provided seed.
  61. func Seed(seed int64) {
  62. rng.Lock()
  63. defer rng.Unlock()
  64. rng.rand = rand.New(rand.NewSource(seed))
  65. }
  66. // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n)
  67. // from the default Source.
  68. func Perm(n int) []int {
  69. rng.Lock()
  70. defer rng.Unlock()
  71. return rng.rand.Perm(n)
  72. }
  73. const (
  74. // We omit vowels from the set of available characters to reduce the chances
  75. // of "bad words" being formed.
  76. alphanums = "bcdfghjklmnpqrstvwxz2456789"
  77. // No. of bits required to index into alphanums string.
  78. alphanumsIdxBits = 5
  79. // Mask used to extract last alphanumsIdxBits of an int.
  80. alphanumsIdxMask = 1<<alphanumsIdxBits - 1
  81. // No. of random letters we can extract from a single int63.
  82. maxAlphanumsPerInt = 63 / alphanumsIdxBits
  83. )
  84. // String generates a random alphanumeric string, without vowels, which is n
  85. // characters long. This will panic if n is less than zero.
  86. // How the random string is created:
  87. // - we generate random int63's
  88. // - from each int63, we are extracting multiple random letters by bit-shifting and masking
  89. // - if some index is out of range of alphanums we neglect it (unlikely to happen multiple times in a row)
  90. func String(n int) string {
  91. b := make([]byte, n)
  92. rng.Lock()
  93. defer rng.Unlock()
  94. randomInt63 := rng.rand.Int63()
  95. remaining := maxAlphanumsPerInt
  96. for i := 0; i < n; {
  97. if remaining == 0 {
  98. randomInt63, remaining = rng.rand.Int63(), maxAlphanumsPerInt
  99. }
  100. if idx := int(randomInt63 & alphanumsIdxMask); idx < len(alphanums) {
  101. b[i] = alphanums[idx]
  102. i++
  103. }
  104. randomInt63 >>= alphanumsIdxBits
  105. remaining--
  106. }
  107. return string(b)
  108. }
  109. // SafeEncodeString encodes s using the same characters as rand.String. This reduces the chances of bad words and
  110. // ensures that strings generated from hash functions appear consistent throughout the API.
  111. func SafeEncodeString(s string) string {
  112. r := make([]byte, len(s))
  113. for i, b := range []rune(s) {
  114. r[i] = alphanums[(int(b) % len(alphanums))]
  115. }
  116. return string(r)
  117. }