-
Notifications
You must be signed in to change notification settings - Fork 1
/
rand.go
88 lines (72 loc) · 1.89 KB
/
rand.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
package main
import (
"flag"
"io"
"strings"
"text/template"
"github.com/micvbang/go-helpy/gen"
)
type templateData struct {
Type string
PackageName string
}
func main() {
var d templateData
flag.StringVar(&d.Type, "type", "", "Name of the type")
flag.StringVar(&d.PackageName, "package-name", "", "Name of the package to place the generated file in")
flag.Parse()
random := template.Must(template.New("template").Parse(randomTemplate))
gen.GenerateToPackage(d.PackageName, "gen_random.go", func(w io.Writer) error {
return random.Execute(w, d)
})
funcMap := template.FuncMap{
"HasPrefix": strings.HasPrefix,
}
randomTest := template.Must(template.New("template").Funcs(funcMap).Parse(randomTemplateTest))
gen.GenerateToPackage(d.PackageName, "gen_random_test.go", func(w io.Writer) error {
return randomTest.Execute(w, d)
})
}
const randomTemplate = `
package {{.PackageName}}
import (
"math/rand"
)
// Code generated. DO NOT EDIT.
// Random returns a non-negative pseudo-random number of type {{.Type}}
func Random() {{.Type}} {
return {{.Type}}(rand.Int63())
}
// RandomN returns a non-negative pseudo-random number in [0,n) of type {{.Type}}. It panics if n <= 0.
func RandomN(n {{.Type}}) {{.Type}} {
return {{.Type}}(rand.Int63n(int64(n)))
}
`
const randomTemplateTest = `
package {{.PackageName}}
import (
"testing"
)
// Code generated. DO NOT EDIT.
// TestRandom simply runs Random to ensure that it compiles during testing.
func TestRandom(t *testing.T) {
for i := 0; i < 10; i++ {
Random()
}
}
// TestRandomN runs RandomN and ensures that output is within expected range.
func TestRandomN(t *testing.T) {
for i := 1; i < 127; i++ {
v := {{.Type}}(i)
got := RandomN(v)
if got >= v {
t.Errorf("expected value < %v, got %v", v, got)
}
{{if (HasPrefix .Type "int") }}
if got >= v {
t.Errorf("expected value > 0, got %v", got)
}
{{end}}
}
}
`