This repository has been archived by the owner on Oct 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhooks.go
198 lines (173 loc) · 6.3 KB
/
hooks.go
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
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package mapdecode
import (
"fmt"
"reflect"
"strconv"
"time"
"github.com/uber-go/mapdecode/internal/mapstructure"
)
var _typeOfDuration = reflect.TypeOf(time.Duration(0))
// FieldHookFunc is a hook called while decoding a specific struct field. It
// receives information about the target field, and the source data.
type FieldHookFunc func(dest reflect.StructField, srcData reflect.Value) (reflect.Value, error)
func composeFieldHooks(hooks []FieldHookFunc) FieldHookFunc {
return func(dest reflect.StructField, srcData reflect.Value) (reflect.Value, error) {
var err error
for _, hook := range hooks {
srcData, err = hook(dest, srcData)
if err != nil {
return srcData, err
}
}
return srcData, err
}
}
// DecodeHookFunc is a hook called before decoding a value into a specific
// type.
type DecodeHookFunc func(from, to reflect.Type, data reflect.Value) (reflect.Value, error)
// Note: DecodeHookFunc is a reflect.Value version of DecodeHookFuncType.
// Builds a mapstructure-compatible hook from a DecodeHookFunc.
func fromDecodeHookFunc(hook DecodeHookFunc) mapstructure.DecodeHookFuncType {
return func(from, to reflect.Type, data interface{}) (interface{}, error) {
var value reflect.Value
if data != nil {
value = reflect.ValueOf(data)
} else {
// mapstructure is pretty good about giving us non-nil data but
// let's process it gracefully anyway.
value = reflect.Zero(from)
}
out, err := hook(from, to, value)
if err != nil {
return nil, err
}
return out.Interface(), nil
}
}
// Composes multiple DecodeHookFuncs into one. The hooks are applied in-order
// and values produced by a hook are fed into the next hook.
func composeDecodeHooks(hooks []DecodeHookFunc) DecodeHookFunc {
return func(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {
var err error
for _, hook := range hooks {
data, err = hook(from, to, data)
if err != nil {
return data, err
}
// Update the `from` type to reflect changes made by the hook.
from = data.Type()
}
return data, err
}
}
// Wraps a DecodeHookFunc to support pointers in either direction (source and
// destination).
func supportPointers(hook DecodeHookFunc) (outputHook DecodeHookFunc) {
outputHook = func(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {
// Get rid of pointers in either direction. This lets us parse **foo if we
// know how to parse foo.
switch {
case from.Kind() == reflect.Ptr: // *foo => bar
// Decoding a pointer type to a non-pointer type. Dereference if
// non-nil, use zero-value otherwise.
from = from.Elem()
if data.IsNil() {
data = reflect.Zero(from)
} else {
data = data.Elem()
}
return outputHook(from, to, data)
case to.Kind() == reflect.Ptr: // foo => *bar
// Decoding a non-pointer type to a pointer. Decode as usual and take
// a pointer to the result.
out, err := outputHook(from, to.Elem(), data)
if err != nil {
return out, err
}
// If we didn't know what to do with the input, the returned value
// will just be the data as-is and it won't have the correct type.
if !out.Type().AssignableTo(to.Elem()) {
return data, nil
}
result := reflect.New(to.Elem())
result.Elem().Set(out)
return result, nil
}
return hook(from, to, data)
}
return
}
// Builds a DecodeHookFunc which unmarshals types using the given unmarshaling
// scheme. See the unmarshaler type for more information.
func unmarshalerHook(opts *options) DecodeHookFunc {
return func(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {
if from == to {
return data, nil
}
if !reflect.PtrTo(to).Implements(opts.Unmarshaler.Interface) {
return data, nil
}
// The following lines are roughly equivalent to,
// value := new(foo)
// err := value.Decode(...)
// return *value, err
value := reflect.New(to)
err := opts.Unmarshaler.Unmarshal(value, decodeFrom(opts, data.Interface()))
if err != nil {
err = fmt.Errorf("could not decode %v from %v: %v", to, from, err)
}
return value.Elem(), err
}
}
// A DecodeHookFunc which decodes strings into time.Durations.
func durationHook(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {
if from.Kind() != reflect.String || to != _typeOfDuration {
return data, nil
}
d, err := time.ParseDuration(data.String())
return reflect.ValueOf(d), err
}
// stringToPrimitivesHook is a DecodeHookFunc which decodes strings into
// primitives.
//
// Integers are parsed in base 10.
func strconvHook(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {
if from.Kind() != reflect.String {
return data, nil
}
s := data.String()
switch to.Kind() {
case reflect.Bool:
b, err := strconv.ParseBool(s)
return reflect.ValueOf(b), err
case reflect.Float32, reflect.Float64:
f, err := strconv.ParseFloat(s, to.Bits())
return reflect.ValueOf(f).Convert(to), err
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i, err := strconv.ParseInt(s, 10, to.Bits())
return reflect.ValueOf(i).Convert(to), err
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
u, err := strconv.ParseUint(s, 10, to.Bits())
return reflect.ValueOf(u).Convert(to), err
}
return data, nil
}