-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
127 lines (108 loc) · 2.11 KB
/
main.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package main
import (
"bytes"
_ "embed"
"flag"
"fmt"
"go/format"
"io"
"math"
"os"
"strconv"
"text/template"
"unicode"
"unicode/utf8"
)
// IntType represents Go integer type.
type IntType struct {
Name string
Iterations int
}
// Config is generation config.
type Config struct {
PackageName string
Types []IntType
}
func times(num int) []struct{} {
return make([]struct{}, num)
}
func title(s string) string {
r, size := utf8.DecodeRuneInString(s)
return string(unicode.ToUpper(r)) + s[size:]
}
func add(a, b int) int {
return a + b
}
func sub(a, b int) int {
return a - b
}
var (
//go:embed gen.tmpl
rawTemplate string
)
func computeIterations(max uint64) int {
// Compute maximum pow of 1000 plus remainder.
return len(strconv.FormatUint(max, 10))/3 + 1
}
func generate(w io.Writer, pkgName string) error {
buf := bytes.Buffer{}
types := []IntType{
{
Name: "int64",
Iterations: computeIterations(math.MaxUint64),
},
{
Name: "int32",
Iterations: computeIterations(math.MaxUint32),
},
{
Name: "int16",
Iterations: computeIterations(math.MaxUint16),
},
}
t := template.Must(template.New("gen").Funcs(template.FuncMap{
"times": times,
"title": title,
"add": add,
"sub": sub,
}).Parse(rawTemplate))
if err := t.ExecuteTemplate(&buf, "main", Config{
PackageName: pkgName,
Types: types,
}); err != nil {
return fmt.Errorf("execute: %w", err)
}
formatted, err := format.Source(buf.Bytes())
if err != nil {
_, _ = os.Stderr.Write(buf.Bytes())
return fmt.Errorf("format: %w", err)
}
if _, err := w.Write(formatted); err != nil {
return fmt.Errorf("write: %w", err)
}
return nil
}
func run() error {
var (
o = flag.String("output", "", "output file")
pkgName = flag.String("package", "jx", "package name")
)
flag.Parse()
var w io.Writer = os.Stdout
if path := *o; path != "" {
f, err := os.Create(path) // #nosec G304
if err != nil {
return err
}
defer func() {
fmt.Println(f.Close())
}()
w = f
}
return generate(w, *pkgName)
}
func main() {
if err := run(); err != nil {
panic(err)
}
}