randomstringutils.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. /*
  2. Copyright 2014 Alexander Okoli
  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 goutils
  14. import (
  15. "fmt"
  16. "math"
  17. "math/rand"
  18. "time"
  19. "unicode"
  20. )
  21. // RANDOM provides the time-based seed used to generate random numbers
  22. var RANDOM = rand.New(rand.NewSource(time.Now().UnixNano()))
  23. /*
  24. RandomNonAlphaNumeric creates a random string whose length is the number of characters specified.
  25. Characters will be chosen from the set of all characters (ASCII/Unicode values between 0 to 2,147,483,647 (math.MaxInt32)).
  26. Parameter:
  27. count - the length of random string to create
  28. Returns:
  29. string - the random string
  30. error - an error stemming from an invalid parameter within underlying function, RandomSeed(...)
  31. */
  32. func RandomNonAlphaNumeric(count int) (string, error) {
  33. return RandomAlphaNumericCustom(count, false, false)
  34. }
  35. /*
  36. RandomAscii creates a random string whose length is the number of characters specified.
  37. Characters will be chosen from the set of characters whose ASCII value is between 32 and 126 (inclusive).
  38. Parameter:
  39. count - the length of random string to create
  40. Returns:
  41. string - the random string
  42. error - an error stemming from an invalid parameter within underlying function, RandomSeed(...)
  43. */
  44. func RandomAscii(count int) (string, error) {
  45. return Random(count, 32, 127, false, false)
  46. }
  47. /*
  48. RandomNumeric creates a random string whose length is the number of characters specified.
  49. Characters will be chosen from the set of numeric characters.
  50. Parameter:
  51. count - the length of random string to create
  52. Returns:
  53. string - the random string
  54. error - an error stemming from an invalid parameter within underlying function, RandomSeed(...)
  55. */
  56. func RandomNumeric(count int) (string, error) {
  57. return Random(count, 0, 0, false, true)
  58. }
  59. /*
  60. RandomAlphabetic creates a random string whose length is the number of characters specified.
  61. Characters will be chosen from the set of alphabetic characters.
  62. Parameters:
  63. count - the length of random string to create
  64. Returns:
  65. string - the random string
  66. error - an error stemming from an invalid parameter within underlying function, RandomSeed(...)
  67. */
  68. func RandomAlphabetic(count int) (string, error) {
  69. return Random(count, 0, 0, true, false)
  70. }
  71. /*
  72. RandomAlphaNumeric creates a random string whose length is the number of characters specified.
  73. Characters will be chosen from the set of alpha-numeric characters.
  74. Parameter:
  75. count - the length of random string to create
  76. Returns:
  77. string - the random string
  78. error - an error stemming from an invalid parameter within underlying function, RandomSeed(...)
  79. */
  80. func RandomAlphaNumeric(count int) (string, error) {
  81. return Random(count, 0, 0, true, true)
  82. }
  83. /*
  84. RandomAlphaNumericCustom creates a random string whose length is the number of characters specified.
  85. Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments.
  86. Parameters:
  87. count - the length of random string to create
  88. letters - if true, generated string may include alphabetic characters
  89. numbers - if true, generated string may include numeric characters
  90. Returns:
  91. string - the random string
  92. error - an error stemming from an invalid parameter within underlying function, RandomSeed(...)
  93. */
  94. func RandomAlphaNumericCustom(count int, letters bool, numbers bool) (string, error) {
  95. return Random(count, 0, 0, letters, numbers)
  96. }
  97. /*
  98. Random creates a random string based on a variety of options, using default source of randomness.
  99. This method has exactly the same semantics as RandomSeed(int, int, int, bool, bool, []char, *rand.Rand), but
  100. instead of using an externally supplied source of randomness, it uses the internal *rand.Rand instance.
  101. Parameters:
  102. count - the length of random string to create
  103. start - the position in set of chars (ASCII/Unicode int) to start at
  104. end - the position in set of chars (ASCII/Unicode int) to end before
  105. letters - if true, generated string may include alphabetic characters
  106. numbers - if true, generated string may include numeric characters
  107. chars - the set of chars to choose randoms from. If nil, then it will use the set of all chars.
  108. Returns:
  109. string - the random string
  110. error - an error stemming from an invalid parameter within underlying function, RandomSeed(...)
  111. */
  112. func Random(count int, start int, end int, letters bool, numbers bool, chars ...rune) (string, error) {
  113. return RandomSeed(count, start, end, letters, numbers, chars, RANDOM)
  114. }
  115. /*
  116. RandomSeed creates a random string based on a variety of options, using supplied source of randomness.
  117. If the parameters start and end are both 0, start and end are set to ' ' and 'z', the ASCII printable characters, will be used,
  118. unless letters and numbers are both false, in which case, start and end are set to 0 and math.MaxInt32, respectively.
  119. If chars is not nil, characters stored in chars that are between start and end are chosen.
  120. This method accepts a user-supplied *rand.Rand instance to use as a source of randomness. By seeding a single *rand.Rand instance
  121. with a fixed seed and using it for each call, the same random sequence of strings can be generated repeatedly and predictably.
  122. Parameters:
  123. count - the length of random string to create
  124. start - the position in set of chars (ASCII/Unicode decimals) to start at
  125. end - the position in set of chars (ASCII/Unicode decimals) to end before
  126. letters - if true, generated string may include alphabetic characters
  127. numbers - if true, generated string may include numeric characters
  128. chars - the set of chars to choose randoms from. If nil, then it will use the set of all chars.
  129. random - a source of randomness.
  130. Returns:
  131. string - the random string
  132. error - an error stemming from invalid parameters: if count < 0; or the provided chars array is empty; or end <= start; or end > len(chars)
  133. */
  134. func RandomSeed(count int, start int, end int, letters bool, numbers bool, chars []rune, random *rand.Rand) (string, error) {
  135. if count == 0 {
  136. return "", nil
  137. } else if count < 0 {
  138. err := fmt.Errorf("randomstringutils illegal argument: Requested random string length %v is less than 0.", count) // equiv to err := errors.New("...")
  139. return "", err
  140. }
  141. if chars != nil && len(chars) == 0 {
  142. err := fmt.Errorf("randomstringutils illegal argument: The chars array must not be empty")
  143. return "", err
  144. }
  145. if start == 0 && end == 0 {
  146. if chars != nil {
  147. end = len(chars)
  148. } else {
  149. if !letters && !numbers {
  150. end = math.MaxInt32
  151. } else {
  152. end = 'z' + 1
  153. start = ' '
  154. }
  155. }
  156. } else {
  157. if end <= start {
  158. err := fmt.Errorf("randomstringutils illegal argument: Parameter end (%v) must be greater than start (%v)", end, start)
  159. return "", err
  160. }
  161. if chars != nil && end > len(chars) {
  162. err := fmt.Errorf("randomstringutils illegal argument: Parameter end (%v) cannot be greater than len(chars) (%v)", end, len(chars))
  163. return "", err
  164. }
  165. }
  166. buffer := make([]rune, count)
  167. gap := end - start
  168. // high-surrogates range, (\uD800-\uDBFF) = 55296 - 56319
  169. // low-surrogates range, (\uDC00-\uDFFF) = 56320 - 57343
  170. for count != 0 {
  171. count--
  172. var ch rune
  173. if chars == nil {
  174. ch = rune(random.Intn(gap) + start)
  175. } else {
  176. ch = chars[random.Intn(gap)+start]
  177. }
  178. if letters && unicode.IsLetter(ch) || numbers && unicode.IsDigit(ch) || !letters && !numbers {
  179. if ch >= 56320 && ch <= 57343 { // low surrogate range
  180. if count == 0 {
  181. count++
  182. } else {
  183. // Insert low surrogate
  184. buffer[count] = ch
  185. count--
  186. // Insert high surrogate
  187. buffer[count] = rune(55296 + random.Intn(128))
  188. }
  189. } else if ch >= 55296 && ch <= 56191 { // High surrogates range (Partial)
  190. if count == 0 {
  191. count++
  192. } else {
  193. // Insert low surrogate
  194. buffer[count] = rune(56320 + random.Intn(128))
  195. count--
  196. // Insert high surrogate
  197. buffer[count] = ch
  198. }
  199. } else if ch >= 56192 && ch <= 56319 {
  200. // private high surrogate, skip it
  201. count++
  202. } else {
  203. // not one of the surrogates*
  204. buffer[count] = ch
  205. }
  206. } else {
  207. count++
  208. }
  209. }
  210. return string(buffer), nil
  211. }