regen.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. /*
  2. Copyright 2014 Zachary Klippenstein
  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. /*
  14. Package regen is a library for generating random strings from regular expressions.
  15. The generated strings will match the expressions they were generated from. Similar
  16. to Ruby's randexp library.
  17. E.g.
  18. regen.Generate("[a-z0-9]{1,64}")
  19. will return a lowercase alphanumeric string
  20. between 1 and 64 characters long.
  21. Expressions are parsed using the Go standard library's parser: http://golang.org/pkg/regexp/syntax/.
  22. Constraints
  23. "." will generate any character, not necessarily a printable one.
  24. "x{0,}", "x*", and "x+" will generate a random number of x's up to an arbitrary limit.
  25. If you care about the maximum number, specify it explicitly in the expression,
  26. e.g. "x{0,256}".
  27. Flags
  28. Flags can be passed to the parser by setting them in the GeneratorArgs struct.
  29. Newline flags are respected, and newlines won't be generated unless the appropriate flags for
  30. matching them are set.
  31. E.g.
  32. Generate(".|[^a]") will never generate newlines. To generate newlines, create a generator and pass
  33. the flag syntax.MatchNL.
  34. The Perl character class flag is supported, and required if the pattern contains them.
  35. Unicode groups are not supported at this time. Support may be added in the future.
  36. Concurrent Use
  37. A generator can safely be used from multiple goroutines without locking.
  38. A large bottleneck with running generators concurrently is actually the entropy source. Sources returned from
  39. rand.NewSource() are slow to seed, and not safe for concurrent use. Instead, the source passed in GeneratorArgs
  40. is used to seed an XorShift64 source (algorithm from the paper at http://vigna.di.unimi.it/ftp/papers/xorshift.pdf).
  41. This source only uses a single variable internally, and is much faster to seed than the default source. One
  42. source is created per call to NewGenerator. If no source is passed in, the default source is used to seed.
  43. The source is not locked and does not use atomic operations, so there is a chance that multiple goroutines using
  44. the same source may get the same output. While obviously not cryptographically secure, I think the simplicity and performance
  45. benefit outweighs the risk of collisions. If you really care about preventing this, the solution is simple: don't
  46. call a single Generator from multiple goroutines.
  47. Benchmarks
  48. Benchmarks are included for creating and running generators for limited-length,
  49. complex regexes, and simple, highly-repetitive regexes.
  50. go test -bench .
  51. The complex benchmarks generate fake HTTP messages with the following regex:
  52. POST (/[-a-zA-Z0-9_.]{3,12}){3,6}
  53. Content-Length: [0-9]{2,3}
  54. X-Auth-Token: [a-zA-Z0-9+/]{64}
  55. ([A-Za-z0-9+/]{64}
  56. ){3,15}[A-Za-z0-9+/]{60}([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)
  57. The repetitive benchmarks use the regex
  58. a{999}
  59. See regen_benchmarks_test.go for more information.
  60. On my mid-2014 MacBook Pro (2.6GHz Intel Core i5, 8GB 1600MHz DDR3),
  61. the results of running the benchmarks with minimal load are:
  62. BenchmarkComplexCreation-4 200 8322160 ns/op
  63. BenchmarkComplexGeneration-4 10000 153625 ns/op
  64. BenchmarkLargeRepeatCreateSerial-4 3000 411772 ns/op
  65. BenchmarkLargeRepeatGenerateSerial-4 5000 291416 ns/op
  66. */
  67. package regen
  68. import (
  69. "fmt"
  70. "math/rand"
  71. "regexp/syntax"
  72. )
  73. // DefaultMaxUnboundedRepeatCount is default value for MaxUnboundedRepeatCount.
  74. const DefaultMaxUnboundedRepeatCount = 4096
  75. // CaptureGroupHandler is a function that is called for each capture group in a regular expression.
  76. // index and name are the index and name of the group. If unnamed, name is empty. The first capture group has index 0
  77. // (not 1, as when matching).
  78. // group is the regular expression within the group (e.g. for `(\w+)`, group would be `\w+`).
  79. // generator is the generator for group.
  80. // args is the args used to create the generator calling this function.
  81. type CaptureGroupHandler func(index int, name string, group *syntax.Regexp, generator Generator, args *GeneratorArgs) string
  82. // GeneratorArgs are arguments passed to NewGenerator that control how generators
  83. // are created.
  84. type GeneratorArgs struct {
  85. // May be nil.
  86. // Used to seed a custom RNG that is a lot faster than the default implementation.
  87. // See http://vigna.di.unimi.it/ftp/papers/xorshift.pdf.
  88. RngSource rand.Source
  89. // Default is 0 (syntax.POSIX).
  90. Flags syntax.Flags
  91. // Maximum number of instances to generate for unbounded repeat expressions (e.g. ".*" and "{1,}")
  92. // Default is DefaultMaxUnboundedRepeatCount.
  93. MaxUnboundedRepeatCount uint
  94. // Minimum number of instances to generate for unbounded repeat expressions (e.g. ".*")
  95. // Default is 0.
  96. MinUnboundedRepeatCount uint
  97. // Set this to perform special processing of capture groups (e.g. `(\w+)`). The zero value will generate strings
  98. // from the expressions in the group.
  99. CaptureGroupHandler CaptureGroupHandler
  100. // Used by generators.
  101. rng *rand.Rand
  102. }
  103. func (a *GeneratorArgs) initialize() error {
  104. var seed int64
  105. if nil == a.RngSource {
  106. seed = rand.Int63()
  107. } else {
  108. seed = a.RngSource.Int63()
  109. }
  110. rngSource := xorShift64Source(seed)
  111. a.rng = rand.New(&rngSource)
  112. // unicode groups only allowed with Perl
  113. if (a.Flags&syntax.UnicodeGroups) == syntax.UnicodeGroups && (a.Flags&syntax.Perl) != syntax.Perl {
  114. return generatorError(nil, "UnicodeGroups not supported")
  115. }
  116. if a.MaxUnboundedRepeatCount < 1 {
  117. a.MaxUnboundedRepeatCount = DefaultMaxUnboundedRepeatCount
  118. }
  119. if a.MinUnboundedRepeatCount > a.MaxUnboundedRepeatCount {
  120. panic(fmt.Sprintf("MinUnboundedRepeatCount(%d) > MaxUnboundedRepeatCount(%d)",
  121. a.MinUnboundedRepeatCount, a.MaxUnboundedRepeatCount))
  122. }
  123. if a.CaptureGroupHandler == nil {
  124. a.CaptureGroupHandler = defaultCaptureGroupHandler
  125. }
  126. return nil
  127. }
  128. // Rng returns the random number generator used by generators.
  129. // Panics if called before the GeneratorArgs has been initialized by NewGenerator.
  130. func (a *GeneratorArgs) Rng() *rand.Rand {
  131. if a.rng == nil {
  132. panic("GeneratorArgs has not been initialized by NewGenerator yet")
  133. }
  134. return a.rng
  135. }
  136. // Generator generates random strings.
  137. type Generator interface {
  138. Generate() string
  139. String() string
  140. }
  141. /*
  142. Generate a random string that matches the regular expression pattern.
  143. If args is nil, default values are used.
  144. This function does not seed the default RNG, so you must call rand.Seed() if you want
  145. non-deterministic strings.
  146. */
  147. func Generate(pattern string) (string, error) {
  148. generator, err := NewGenerator(pattern, nil)
  149. if err != nil {
  150. return "", err
  151. }
  152. return generator.Generate(), nil
  153. }
  154. // NewGenerator creates a generator that returns random strings that match the regular expression in pattern.
  155. // If args is nil, default values are used.
  156. func NewGenerator(pattern string, inputArgs *GeneratorArgs) (generator Generator, err error) {
  157. args := GeneratorArgs{}
  158. // Copy inputArgs so the caller can't change them.
  159. if inputArgs != nil {
  160. args = *inputArgs
  161. }
  162. if err = args.initialize(); err != nil {
  163. return nil, err
  164. }
  165. var regexp *syntax.Regexp
  166. regexp, err = syntax.Parse(pattern, args.Flags)
  167. if err != nil {
  168. return
  169. }
  170. var gen *internalGenerator
  171. gen, err = newGenerator(regexp, &args)
  172. if err != nil {
  173. return
  174. }
  175. return gen, nil
  176. }