-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunion.go
More file actions
48 lines (39 loc) · 1.12 KB
/
union.go
File metadata and controls
48 lines (39 loc) · 1.12 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
package paramutil
import (
"fmt"
"github.com/sfcompute/nodes-go/packages/param"
"reflect"
)
var paramUnionType = reflect.TypeOf(param.APIUnion{})
// VariantFromUnion can be used to extract the present variant from a param union type.
// A param union type is a struct with an embedded field of [APIUnion].
func VariantFromUnion(u reflect.Value) (any, error) {
if u.Kind() == reflect.Ptr {
u = u.Elem()
}
if u.Kind() != reflect.Struct {
return nil, fmt.Errorf("param: cannot extract variant from non-struct union")
}
isUnion := false
nVariants := 0
variantIdx := -1
for i := 0; i < u.NumField(); i++ {
if !u.Field(i).IsZero() {
nVariants++
variantIdx = i
}
if u.Field(i).Type() == paramUnionType {
isUnion = u.Type().Field(i).Anonymous
}
}
if !isUnion {
return nil, fmt.Errorf("param: cannot extract variant from non-union")
}
if nVariants > 1 {
return nil, fmt.Errorf("param: cannot extract variant from union with multiple variants")
}
if nVariants == 0 {
return nil, fmt.Errorf("param: cannot extract variant from union with no variants")
}
return u.Field(variantIdx).Interface(), nil
}