Change template

This commit is contained in:
Nise Void 2018-10-31 16:25:09 +01:00
parent eec6d38da6
commit 4d849550dc
Signed by: NiseVoid
GPG Key ID: FBA14AC83EA602F3
2 changed files with 37 additions and 41 deletions

View File

@ -16,7 +16,6 @@
// Given the name of a (signed or unsigned) integer type T that has constants
// defined, jsonenums will create a new self-contained Go source file implementing
//
// func (t T) String() string
// func (t T) MarshalJSON() ([]byte, error)
// func (t *T) UnmarshalJSON([]byte) error
//
@ -47,7 +46,6 @@
// in the same directory will create the file pill_jsonenums.go, in package painkiller,
// containing a definition of
//
// func (r Pill) String() string
// func (r Pill) MarshalJSON() ([]byte, error)
// func (r *Pill) UnmarshalJSON([]byte) error
//

View File

@ -18,7 +18,7 @@ package main
import "text/template"
var generatedTmpl = template.Must(template.New("generated").Parse(`
// generated by jsonenums {{.Command}}; DO NOT EDIT
// Code generated by "jsonenums {{.Command}}"; DO NOT EDIT.
package {{.PackageName}}
@ -30,32 +30,28 @@ import (
{{range $typename, $values := .TypesAndValues}}
var (
_{{$typename}}NameToValue map[string]{{$typename}}
_{{$typename}}ValueToName map[{{$typename}}]string
)
func init() {
_{{$typename}}NameToValue = map[string]{{$typename}} {
{{range $values}}"{{.}}": {{.}},
{{range $values}}{{.}}.String(): {{.}},
{{end}}
}
_{{$typename}}ValueToName = map[{{$typename}}]string {
{{range $values}}{{.}}: "{{.}}",
{{range $values}}{{.}}: {{.}}.String(),
{{end}}
}
)
func init() {
var v {{$typename}}
if _, ok := interface{}(v).(fmt.Stringer); ok {
_{{$typename}}NameToValue = map[string]{{$typename}} {
{{range $values}}interface{}({{.}}).(fmt.Stringer).String(): {{.}},
{{end}}
}
}
}
// MarshalJSON is generated so {{$typename}} satisfies json.Marshaler.
// MarshalJSON implements json.Marshaler
func (r {{$typename}}) MarshalJSON() ([]byte, error) {
if s, ok := interface{}(r).(fmt.Stringer); ok {
return json.Marshal(s.String())
}
s, ok := _{{$typename}}ValueToName[r]
if !ok {
return nil, fmt.Errorf("invalid {{$typename}}: %d", r)
@ -63,16 +59,18 @@ func (r {{$typename}}) MarshalJSON() ([]byte, error) {
return json.Marshal(s)
}
// UnmarshalJSON is generated so {{$typename}} satisfies json.Unmarshaler.
// UnmarshalJSON implements json.Unmarshaler
func (r *{{$typename}}) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return fmt.Errorf("{{$typename}} should be a string, got %s", data)
}
v, ok := _{{$typename}}NameToValue[s]
if !ok {
return fmt.Errorf("invalid {{$typename}} %q", s)
return fmt.Errorf("invalid value: %s", s)
}
*r = v
return nil
}