forked from goadesign/goa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
random.go
92 lines (77 loc) · 2.01 KB
/
random.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package expr
import (
"crypto/md5"
"encoding/binary"
"math/rand"
"github.com/manveru/faker"
)
// Random generates consistent random values of different types given a seed.
// The random values are consistent in that given the same seed the same random values get
// generated.
// The generator tracks the user types that it has processed to avoid infinite recursions, this
// means a new generator should be created when wanting to generate a new random value for a user
// type.
type Random struct {
Seed string
Seen map[string]*interface{}
faker *faker.Faker
rand *rand.Rand
}
// NewRandom returns a random value generator seeded from the given string value.
func NewRandom(seed string) *Random {
hasher := md5.New()
hasher.Write([]byte(seed))
sint := int64(binary.BigEndian.Uint64(hasher.Sum(nil)))
source := rand.NewSource(sint)
ran := rand.New(source)
faker := &faker.Faker{
Language: "end",
Dict: faker.Dict["en"],
Rand: ran,
}
return &Random{
Seed: seed,
faker: faker,
rand: ran,
}
}
// Int produces a random integer.
func (r *Random) Int() int {
return r.rand.Int()
}
// Int32 produces a random 32-bit integer.
func (r *Random) Int32() int32 {
return r.rand.Int31()
}
// Int64 produces a random 64-bit integer.
func (r *Random) Int64() int64 {
return r.rand.Int63()
}
// String produces a random string.
func (r *Random) String() string {
return r.faker.Sentence(2, false)
}
// Bool produces a random boolean.
func (r *Random) Bool() bool {
return r.rand.Int()%2 == 0
}
// Float32 produces a random float32 value.
func (r *Random) Float32() float32 {
return r.rand.Float32()
}
// Float64 produces a random float64 value.
func (r *Random) Float64() float64 {
return r.rand.Float64()
}
// UInt produces a random uint value.
func (r *Random) UInt() uint {
return uint(r.UInt64())
}
// UInt32 produces a random uint32 value.
func (r *Random) UInt32() uint32 {
return r.rand.Uint32()
}
// UInt64 produces a random uint64 value.
func (r *Random) UInt64() uint64 {
return r.rand.Uint64()
}