Debian Codegraph @

internal/qmp-gen/templates/simpleunion

raw
1 {{/*
2
3 It's important to note that union implementations are always a basic
4 type or a struct, never another union. This means that we can safely
5 decode union implementations with json.Unmarshal, so we don't have to
6 handle recursively calling decodeFoo functions to unmarshal unions.
7
8 Also, there is one simple union type whose name clashes with the
9 underlying struct type: ImageInfoSpecificVmdk. The struct type is not
10 used anywhere outside the simple union, so we just skip the
11 redefinition, but still tack on all the marshaling logic.
12
13 */}}
14
15 {{ $basename := .Name.Go }}
16
17 // {{ .Name }} -> {{ $basename }} (simple union)
18
19 // {{ $basename }} implements the "{{ .Name }}" QMP API type.
20 //
21 // Can be one of:
22 {{- range $suffix, $type := .Options }}
23 // - {{ $basename }}{{ $suffix.Go }}
24 {{- end }}
25 type {{ $basename }} interface {
26 is{{ $basename }}()
27 }
28
29 {{- range $suffix, $type := .Options }}
30 {{ $subname := printf "%s%s" $basename $suffix.Go }}
31 {{- if ne $subname $type.Go }}
32 // {{ $subname }} is an implementation of {{ $basename }}.
33 type {{ $subname }} {{ $type.Go }}
34 {{- end }}
35
36 func ({{ $subname }}) is{{ $basename }}() {}
37
38 // MarshalJSON implements json.Marshaler.
39 func (s {{ $subname }}) MarshalJSON() ([]byte, error) {
40 v := map[string]interface{}{
41 "type": "{{ $suffix }}",
42 "data": {{ $type.Go }} (s),
43 }
44 return json.Marshal(v)
45 }
46 {{- end }}
47
48 func decode{{ $basename }}(bs json.RawMessage) ({{ $basename }}, error) {
49 v := struct{
50 T string `json:"type"`
51 V json.RawMessage `json:"data"`
52 }{}
53 if err := json.Unmarshal([]byte(bs), &v); err != nil {
54 return nil, err
55 }
56 switch v.T {
57 {{- range $suffix, $type := .Options }}
58 case "{{ $suffix }}":
59 var ret {{ $basename }}{{ $suffix.Go }}
60 if err := json.Unmarshal([]byte(v.V), &ret); err != nil {
61 return nil, err
62 }
63 return ret, nil
64 {{- end }}
65 default:
66 return nil, fmt.Errorf("unknown subtype %q for union {{ $basename }}", v.T)
67 }
68 }