forked from egonelbre/exp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spec.go
97 lines (82 loc) · 1.51 KB
/
spec.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
package mm
import (
"bytes"
"fmt"
"go/format"
"os"
"text/template"
"unsafe"
)
type Allocator interface {
Alignment() int
Alloc(size int) unsafe.Pointer
}
type Reallocator interface {
Realloc(p *unsafe.Pointer, size int) bool
}
type Deallocator interface {
Dealloc(p unsafe.Pointer) bool
}
type Owner interface {
Owns(p unsafe.Pointer) bool
}
type Emptyer interface {
Empty() bool
}
type Spec struct {
Type string
Alignment int
Dealloc bool
Owns bool
Empty bool
}
func SpecFor(v Allocator) *Spec {
_, dealloc := v.(Deallocator)
_, owns := v.(Owner)
_, empty := v.(Emptyer)
return &Spec{
Type: fmt.Sprintf("%+T", v),
Alignment: v.Alignment(),
Dealloc: dealloc,
Owns: owns,
Empty: empty,
}
}
var funcs = template.FuncMap{
"min": func(a, b int) int {
if a < b {
return a
}
return b
},
"max": func(a, b int) int {
if a > b {
return a
}
return b
},
}
type Error struct {
Message error
Generated []byte
}
func (err *Error) Error() string {
if err.Generated == nil {
return err.Message.Error()
}
return fmt.Sprintf("%v\n\n%v", string(err.Generated), err.Message)
}
func Generate(def string, specs map[string]*Spec) ([]byte, error) {
t := template.Must(template.New("").Funcs(funcs).Parse(def))
var buf bytes.Buffer
err := t.Execute(&buf, specs)
if err != nil {
return nil, &Error{err, nil}
}
data, err := format.Source(buf.Bytes())
if err != nil {
os.Stdout.Write(buf.Bytes())
return nil, &Error{err, nil}
}
return data, nil
}