-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode_input.go
More file actions
72 lines (59 loc) · 1.98 KB
/
Copy pathdecode_input.go
File metadata and controls
72 lines (59 loc) · 1.98 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
package instruct
import (
"errors"
"fmt"
"reflect"
"github.com/rrgmc/instruct/types"
)
func (d *Decoder[IT, DC]) decodeInput(input IT, data any, decodeOptions DecodeOptions[IT, DC]) error {
return d.decodeInputFromType(input, reflect.TypeOf(data), data, decodeOptions)
}
func (d *Decoder[IT, DC]) decodeInputFromType(input IT, typ reflect.Type, data any, decodeOptions DecodeOptions[IT, DC]) error {
si, err := d.structInfoFromType(typ)
if err != nil {
return err
}
return d.decodeInputFromStructInfo(input, si, data, decodeOptions)
}
func (d *Decoder[IT, DC]) decodeInputFromStructInfo(input IT, si *structInfo, data any, decodeOptions DecodeOptions[IT, DC]) error {
if isZero(decodeOptions.Ctx) {
return errors.New("decode context cannot be nil")
}
rv := reflect.ValueOf(data)
if rv.Kind() != reflect.Pointer || rv.IsNil() {
return &types.InvalidDecodeError{reflect.TypeOf(data)}
}
if decodeOptions.MapTags != nil {
var err error
// if there is a decode-specific map tag, create a new struct info based on the default one.
si, err = structInfoWithMapTags(si, decodeOptions.MapTags, d.options)
if err != nil {
return err
}
}
err := d.decodeStruct(si, input, reflect.ValueOf(data), decodeOptions)
if err != nil {
return err
}
// validate decode operations
for _, operation := range d.options.DecodeOperations {
if v, ok := operation.(DecodeOperationValidate[IT, DC]); ok {
err = v.Validate(decodeOptions.Ctx, input)
if err != nil {
return err
}
}
}
return nil
}
// structInfoFromType builds an structInfo from a [reflect.Type], using the decoder options.
func (d *Decoder[IT, DC]) structInfoFromType(typ reflect.Type) (*structInfo, error) {
if typ == nil {
return nil, fmt.Errorf("cannot decode to nil")
}
typ = reflectElem(typ)
if typ.Kind() != reflect.Struct {
return nil, fmt.Errorf("can only decode to struct, received: %v", typ.Kind())
}
return d.options.structInfoProvider.provide(typ, d.options.defaultMapTags.Get(typ), d.options)
}