regen

package module
v0.0.0-...-3eca762 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 10, 2023 License: Apache-2.0 Imports: 6 Imported by: 1

README

#goregen GoDoc Build Status

A Golang library for generating random strings from regular expressions.

Checkout https://goregen-demo.herokuapp.com for a live demo.

See the godoc for examples.

Documentation

Overview

Package regen is a library for generating random strings from regular expressions. The generated strings will match the expressions they were generated from. Similar to Ruby's randexp library.

E.g.

regen.Generate("[a-z0-9]{1,64}")

will return a lowercase alphanumeric string between 1 and 64 characters long.

Expressions are parsed using the Go standard library's parser: http://golang.org/pkg/regexp/syntax/.

Constraints

"." will generate any character, not necessarily a printable one.

"x{0,}", "x*", and "x+" will generate a random number of x's up to an arbitrary limit. If you care about the maximum number, specify it explicitly in the expression, e.g. "x{0,256}".

Flags

Flags can be passed to the parser by setting them in the GeneratorArgs struct. Newline flags are respected, and newlines won't be generated unless the appropriate flags for matching them are set.

E.g. Generate(".|[^a]") will never generate newlines. To generate newlines, create a generator and pass the flag syntax.MatchNL.

The Perl character class flag is supported, and required if the pattern contains them.

Unicode groups are not supported at this time. Support may be added in the future.

Concurrent Use

A generator can safely be used from multiple goroutines without locking.

A large bottleneck with running generators concurrently is actually the entropy source. Sources returned from rand.NewSource() are slow to seed, and not safe for concurrent use. Instead, the source passed in GeneratorArgs is used to seed an XorShift64 source (algorithm from the paper at http://vigna.di.unimi.it/ftp/papers/xorshift.pdf). This source only uses a single variable internally, and is much faster to seed than the default source. One source is created per call to NewGenerator. If no source is passed in, the default source is used to seed.

The source is not locked and does not use atomic operations, so there is a chance that multiple goroutines using the same source may get the same output. While obviously not cryptographically secure, I think the simplicity and performance benefit outweighs the risk of collisions. If you really care about preventing this, the solution is simple: don't call a single Generator from multiple goroutines.

Benchmarks

Benchmarks are included for creating and running generators for limited-length, complex regexes, and simple, highly-repetitive regexes.

go test -bench .

The complex benchmarks generate fake HTTP messages with the following regex:

POST (/[-a-zA-Z0-9_.]{3,12}){3,6}
Content-Length: [0-9]{2,3}
X-Auth-Token: [a-zA-Z0-9+/]{64}

([A-Za-z0-9+/]{64}
){3,15}[A-Za-z0-9+/]{60}([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)

The repetitive benchmarks use the regex

a{999}

See regen_benchmarks_test.go for more information.

On my mid-2014 MacBook Pro (2.6GHz Intel Core i5, 8GB 1600MHz DDR3), the results of running the benchmarks with minimal load are:

BenchmarkComplexCreation-4                       200	   8322160 ns/op
BenchmarkComplexGeneration-4                   10000	    153625 ns/op
BenchmarkLargeRepeatCreateSerial-4  	        3000	    411772 ns/op
BenchmarkLargeRepeatGenerateSerial-4	        5000	    291416 ns/op

Index

Examples

Constants

View Source
const DefaultMaxUnboundedRepeatCount = 4096

DefaultMaxUnboundedRepeatCount is default value for MaxUnboundedRepeatCount.

Variables

This section is empty.

Functions

func Generate

func Generate(pattern string) (string, error)

Generate a random string that matches the regular expression pattern. If args is nil, default values are used.

This function does not seed the default RNG, so you must call rand.Seed() if you want non-deterministic strings.

Example
pattern := "[ab]{5}"
str, _ := Generate(pattern)

if matched, _ := regexp.MatchString(pattern, str); matched {
	fmt.Println("Matches!")
}
Output:

Matches!

Types

type CaptureGroupHandler

type CaptureGroupHandler func(index int, name string, group *syntax.Regexp, generator Generator, args *GeneratorArgs) string

CaptureGroupHandler is a function that is called for each capture group in a regular expression. index and name are the index and name of the group. If unnamed, name is empty. The first capture group has index 0 (not 1, as when matching). group is the regular expression within the group (e.g. for `(\w+)`, group would be `\w+`). generator is the generator for group. args is the args used to create the generator calling this function.

Example
pattern := `Hello, (?P<firstname>[A-Z][a-z]{2,10}) (?P<lastname>[A-Z][a-z]{2,10})`

generator, _ := NewGenerator(pattern, &GeneratorArgs{
	Flags: syntax.Perl,
	CaptureGroupHandler: func(index int, name string, group *syntax.Regexp, generator Generator, args *GeneratorArgs) string {
		if name == "firstname" {
			return fmt.Sprintf("FirstName (e.g. %s)", generator.Generate())
		}
		return fmt.Sprintf("LastName (e.g. %s)", generator.Generate())
	},
})

// Print to stderr since we're generating random output and can't assert equality.
fmt.Fprintln(os.Stderr, generator.Generate())

// Needed for "go test" to run this example. (Must be a blank line before.)
Output:

type Generator

type Generator interface {
	Generate() string
	String() string
}

Generator generates random strings.

func NewGenerator

func NewGenerator(pattern string, inputArgs *GeneratorArgs) (generator Generator, err error)

NewGenerator creates a generator that returns random strings that match the regular expression in pattern. If args is nil, default values are used.

Example
pattern := "[ab]{5}"

// Note that this uses a constant seed, so the generated string
// will always be the same across different runs of the program.
// Use a more random seed for real use (e.g. time-based).
generator, _ := NewGenerator(pattern, &GeneratorArgs{
	RngSource: rand.NewSource(0),
})

str := generator.Generate()

if matched, _ := regexp.MatchString(pattern, str); matched {
	fmt.Println("Matches!")
}
Output:

Matches!
Example (Perl)
pattern := `\d{5}`

generator, _ := NewGenerator(pattern, &GeneratorArgs{
	Flags: syntax.Perl,
})

str := generator.Generate()

if matched, _ := regexp.MatchString("[[:digit:]]{5}", str); matched {
	fmt.Println("Matches!")
}
Output:

Matches!

type GeneratorArgs

type GeneratorArgs struct {
	// May be nil.
	// Used to seed a custom RNG that is a lot faster than the default implementation.
	// See http://vigna.di.unimi.it/ftp/papers/xorshift.pdf.
	RngSource rand.Source

	// Default is 0 (syntax.POSIX).
	Flags syntax.Flags

	// Maximum number of instances to generate for unbounded repeat expressions (e.g. ".*" and "{1,}")
	// Default is DefaultMaxUnboundedRepeatCount.
	MaxUnboundedRepeatCount uint
	// Minimum number of instances to generate for unbounded repeat expressions (e.g. ".*")
	// Default is 0.
	MinUnboundedRepeatCount uint

	// Set this to perform special processing of capture groups (e.g. `(\w+)`). The zero value will generate strings
	// from the expressions in the group.
	CaptureGroupHandler CaptureGroupHandler

	// the lowest ASCII chat could be used for generating random string, default to 0 indicates no limit
	CharSetLowBound rune
	// the highest ASCII chat could be used for generating random string, default to 0 indicates no limit
	CharSetHighBound rune
	// contains filtered or unexported fields
}

GeneratorArgs are arguments passed to NewGenerator that control how generators are created.

func (*GeneratorArgs) Rng

func (a *GeneratorArgs) Rng() *rand.Rand

Rng returns the random number generator used by generators. Panics if called before the GeneratorArgs has been initialized by NewGenerator.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL