-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtagged_union.go
More file actions
290 lines (264 loc) · 7.93 KB
/
Copy pathtagged_union.go
File metadata and controls
290 lines (264 loc) · 7.93 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// Package union provides generic union type implementations for Go with JSON
// marshaling and unmarshaling support.
//
// This package offers two union types:
//
// - TaggedUnion: A discriminated union with explicit variant/value wrapper
// - Union: An untagged union that marshals data directly
//
// # TaggedUnion
//
// TaggedUnion represents a discriminated union where the JSON representation
// includes a variant field indicating which type is active and a value field
// containing the data.
//
// Example usage:
//
// type Shape struct {
// Circle *Circle `variant:"circle"`
// Rectangle *Rectangle `variant:"rectangle"`
// Triangle *Triangle `variant:"triangle"`
// }
//
// var shape union.TaggedUnion[Shape]
// shape.Value.Circle = &Circle{Radius: 5.0}
//
// // Marshals to: {"type": "circle", "value": {"radius": 5.0}}
// data, _ := json.Marshal(shape)
//
// The `variant` struct tag specifies the variant name in JSON. If no tag is provided,
// the field name is used (e.g., "Circle" instead of "circle").
//
// Custom field names can be specified by implementing JSONDiscriminator():
//
// func (s Shape) JSONDiscriminator() (string, string) {
// return "kind", "data"
// }
//
// // Marshals to: {"kind": "circle", "data": {...}}
//
// For a flat representation (variant fields merged into the top-level object),
// implement JSONDiscriminator() returning a single string:
//
// func (s Shape) JSONDiscriminator() string {
// return "kind"
// }
//
// // Marshals to: {"kind": "circle", "radius": 5.0}
//
// # Union
//
// Union represents an untagged union where the JSON representation is the data
// itself, without any wrapper. When unmarshaling, each field is tried in order
// until one successfully deserializes to a non-zero value.
//
// Example usage:
//
// type Shape struct {
// Circle *Circle
// Rectangle *Rectangle
// Triangle *Triangle
// }
//
// var shape union.Union[Shape]
// shape.Value.Circle = &Circle{Radius: 5.0}
//
// // Marshals to: {"radius": 5.0}
// data, _ := json.Marshal(shape)
//
// // Unmarshaling tries each field until one produces a non-zero value
// _ = json.Unmarshal([]byte(`{"width": 10, "height": 5}`), &shape)
// // shape.Value.Rectangle will be set
package union
import (
"cmp"
"encoding/json"
"errors"
"reflect"
)
// TaggedUnion represents a discriminated union type that can hold one of several
// variant types defined in the Spec struct. The Spec type should be a struct where
// each field represents a possible variant of the union.
//
// Only one field in the Spec struct should be non-zero at any time. When marshaling
// to JSON, the union is represented as an object with a variant field (indicating which
// variant is active) and a value field (containing the variant's data).
type TaggedUnion[Spec any] struct{ Value Spec }
// fieldNames returns the names of the variant and value fields to use in JSON marshaling.
// It checks if the Spec type implements JSONDiscriminator() string for flat representation (value is ""),
// then JSONDiscriminator() (string, string) for custom envelope names, otherwise defaults to "type" and "value".
func (u *TaggedUnion[Spec]) fieldNames() (variant, value string) {
if tf, ok := any(u.Value).(interface{ JSONDiscriminator() string }); ok {
if name := tf.JSONDiscriminator(); name != "" {
return name, ""
}
}
if tu, ok := any(u.Value).(interface{ JSONDiscriminator() (string, string) }); ok {
variant, value = tu.JSONDiscriminator()
if variant == "" {
variant = "type"
}
if value == "" {
value = "value"
}
return variant, value
}
return "type", "value"
}
// GetValue returns the value of the active variant in the union.
// It iterates through all fields in the Spec struct and returns the value
// of the non-zero field. If no fields are set or multiple fields are set,
// it returns nil (indicating an invalid state).
func (u TaggedUnion[Spec]) GetValue() any {
v := reflect.ValueOf(u.Value)
t := v.Type()
if t.Kind() != reflect.Struct {
return nil
}
var value any
for i := 0; i < t.NumField(); i++ {
vf := v.Field(i)
if vf.IsZero() {
continue
}
if value != nil {
// invariant violation: multiple variants set
return nil
}
value = vf.Interface()
}
return value
}
// MarshalJSON implements the json.Marshaler interface.
// It serializes the union to JSON as an object with two fields:
// - A variant field (default "type") containing the variant name
// - A value field (default "value") containing the variant's data
//
// The variant name is determined by the struct field's `variant` struct tag,
// or the field name if no variant is specified.
//
// Returns an error if:
// - The Spec type is not a struct
// - No fields are set (zero state)
// - Multiple fields are set (invalid state)
func (u TaggedUnion[Spec]) MarshalJSON() ([]byte, error) {
v := reflect.ValueOf(u.Value)
t := v.Type()
if t.Kind() != reflect.Struct {
return nil, errors.New("spec must be a struct")
}
var value any
var variant string
for i := 0; i < t.NumField(); i++ {
vf := v.Field(i)
tf := t.Field(i)
if vf.IsZero() {
continue
}
if value != nil {
// invariant violation: multiple variants set
return nil, errors.New("multiple variants set")
}
value = vf.Interface()
variant = cmp.Or(tf.Tag.Get("variant"), tf.Name)
}
if value == nil {
return nil, errors.New("zero variants set")
}
variantField, valueField := u.fieldNames()
if valueField != "" {
out := map[string]any{
variantField: variant,
valueField: value,
}
return json.Marshal(out)
}
raw, err := json.Marshal(value)
if err != nil {
return nil, err
}
var out map[string]json.RawMessage
if err := json.Unmarshal(raw, &out); err != nil {
return nil, err
}
if _, exists := out[variantField]; exists {
return nil, errors.New("variant field conflicts with discriminator: " + variantField)
}
variantJSON, err := json.Marshal(variant)
if err != nil {
return nil, err
}
out[variantField] = variantJSON
return json.Marshal(out)
}
// UnmarshalJSON implements the json.Unmarshaler interface.
// It deserializes JSON data into the union by:
// 1. Reading the variant field to determine which variant is active
// 2. Unmarshaling the value field into the corresponding struct field
//
// The method handles both pointer and non-pointer fields correctly.
//
// Returns an error if:
// - The JSON data is malformed
// - The Spec type is not a struct
// - The variant or value fields are missing
// - The variant field doesn't match any known variant
// - Multiple struct fields match the same variant (invalid Spec definition)
// - The value cannot be unmarshaled into the target field type
func (u *TaggedUnion[Spec]) UnmarshalJSON(data []byte) error {
var zero Spec
u.Value = zero
v := reflect.ValueOf(&u.Value).Elem()
t := v.Type()
if t.Kind() != reflect.Struct {
return errors.New("spec must be a struct")
}
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
variantField, valueField := u.fieldNames()
rawVariant, ok := raw[variantField]
if !ok {
return errors.New("missing variant field: " + variantField)
}
var rawValue json.RawMessage
if valueField != "" {
rawValue, ok = raw[valueField]
if !ok {
return errors.New("missing value field: " + valueField)
}
} else {
delete(raw, variantField)
payload, err := json.Marshal(raw)
if err != nil {
return err
}
rawValue = payload
}
var variant string
if err := json.Unmarshal(rawVariant, &variant); err != nil {
return err
}
var matched bool
for i := 0; i < t.NumField(); i++ {
vf := v.Field(i)
tf := t.Field(i)
if cmp.Or(tf.Tag.Get("variant"), tf.Name) != variant {
continue
}
if matched {
return errors.New("multiple fields matched")
}
target := reflect.New(tf.Type)
if err := json.Unmarshal(rawValue, target.Interface()); err != nil {
return err
}
vf.Set(target.Elem())
matched = true
}
if !matched {
return errors.New("unknown variant: " + variant)
}
return nil
}