// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Added as a .go file to avoid embedding issues of the template. package main import "text/template" var generatedTmpl = template.Must(template.New("generated").Parse(` // generated by jsonenums {{.Command}}; DO NOT EDIT package {{.PackageName}} import ( "encoding/json" "fmt" ) {{range $typename, $values := .TypesAndValues}} var ( _{{$typename}}NameToValue = map[string]{{$typename}} { {{range $values}}"{{.}}": {{.}}, {{end}} } _{{$typename}}ValueToName = map[{{$typename}}]string { {{range $values}}{{.}}: "{{.}}", {{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 returns *r as the JSON encoding of r. 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) } return json.Marshal(s) } // UnmarshalJSON sets *r to a copy of data. 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) } *r = v return nil } {{end}} `))