forked from ghetzel/go-stockutil
/
values.go
367 lines (308 loc) · 9.1 KB
/
values.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
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
// Helpers for type inflection and simplifying working with Golang generic interface types
package typeutil
import (
"fmt"
"reflect"
"strings"
"time"
"github.com/PerformLine/go-stockutil/utils"
"github.com/davecgh/go-spew/spew"
)
type TypeConvertFunc = utils.TypeConvertFunc
var scs = spew.ConfigState{
Indent: ` `,
DisableCapacities: true,
SortKeys: true,
}
// Register's a handler used for converting one type to another. Type are checked in the following
// manner: The input value's reflect.Type String() value is matched, falling back to its
// reflect.Kind String() value, finally checking for a special "*" value that matches any type.
// If the handler function returns nil, its value replaces the input value. If the special error
// type PassthroughType is returned, the original value is returned unmodified.
func RegisterTypeHandler(handler TypeConvertFunc, types ...string) {
utils.RegisterTypeHandler(handler, types...)
}
// Returns whether the given value represents the underlying type's zero value
func IsZero(value interface{}) bool {
return utils.IsZero(value)
}
// Returns whether the given value is "empty" in the semantic sense. Zero values
// are considered empty, as are arrays, slices, and maps containing only empty
// values (called recursively). Finally, strings are trimmed of whitespace and
// considered empty if the result is zero-length.
//
func IsEmpty(value interface{}) bool {
valueV := reflect.ValueOf(value)
if valueV.Kind() == reflect.Ptr {
valueV = valueV.Elem()
}
// short circuit for zero values of certain types
switch valueV.Kind() {
case reflect.Struct:
if IsZero(value) {
return true
}
}
switch valueV.Kind() {
case reflect.Array, reflect.Slice:
if valueV.Len() == 0 {
return true
} else {
for i := 0; i < valueV.Len(); i++ {
if indexV := valueV.Index(i); indexV.IsValid() && !IsEmpty(indexV.Interface()) {
return false
}
}
return true
}
case reflect.Map:
if valueV.Len() == 0 {
return true
} else {
for _, keyV := range valueV.MapKeys() {
if indexV := valueV.MapIndex(keyV); indexV.IsValid() && !IsEmpty(indexV.Interface()) {
return false
}
}
return true
}
case reflect.Chan:
if valueV.Len() == 0 {
return true
}
case reflect.String:
if len(strings.TrimSpace(fmt.Sprintf("%v", value))) == 0 {
return true
}
}
return false
}
// Return the concrete value pointed to by a pointer type, or within an
// interface type. Allows functions receiving pointers to supported types
// to work with those types without doing reflection.
//
func ResolveValue(in interface{}) interface{} {
if inV, ok := in.(Variant); ok {
in = inV.Value
}
return utils.ResolveValue(in)
}
// Dectect whether the concrete underlying value of the given input is one or more
// Kinds of value.
func IsKind(in interface{}, kinds ...reflect.Kind) bool {
return utils.IsKind(in, kinds...)
}
// Return whether the given input is a discrete scalar value (ints, floats, bools,
// strings), otherwise known as "primitive types" in some other languages.
//
func IsScalar(in interface{}) bool {
if !IsKind(in, utils.CompoundTypes...) {
return true
}
return false
}
// Returns whether the given value is a slice or array.
func IsArray(in interface{}) bool {
return IsKind(in, utils.SliceTypes...)
}
// Returns whether the given value is a map.
func IsMap(in interface{}) bool {
return IsKind(in, reflect.Map)
}
// Returns whether the given value is a struct.
func IsStruct(in interface{}) bool {
return IsKind(in, reflect.Struct)
}
// Returns whether the given value is a function of any kind
func IsFunction(in interface{}) bool {
return IsKind(in, reflect.Func)
}
// Returns whether the given value represents a numeric value.
func IsNumeric(in interface{}) bool {
return utils.IsNumeric(in)
}
// Returns whether the given value represents an integer value.
func IsInteger(in interface{}) bool {
return utils.IsInteger(in)
}
// Returns whether the given value represents a floating point value.
func IsFloat(in interface{}) bool {
return utils.IsFloat(in)
}
// Returns whether the given value is a function. If inParams is not -1, the function must
// accept that number of arguments. If outParams is not -1, the function must return that
// number of values.
func IsFunctionArity(in interface{}, inParams int, outParams int) bool {
if IsKind(in, reflect.Func) {
inT := reflect.TypeOf(in)
if inParams < 0 || inParams >= 0 && inT.NumIn() == inParams {
if outParams < 0 || outParams >= 0 && inT.NumOut() == outParams {
return true
}
}
}
return false
}
// Returns the length of the given value that could have a length (strings, slices, arrays,
// maps, and channels). If the value is not a type that has a length, -1 is returned.
func Len(in interface{}) int {
if IsKind(in, reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String) {
return reflect.ValueOf(in).Len()
} else {
return -1
}
}
// Returns a pretty-printed string representation of the given values.
func Dump(in1 interface{}, in ...interface{}) string {
return scs.Sdump(append([]interface{}{in1}, in...)...)
}
// Returns a pretty-printed string representation of the given values.
func Dumpf(format string, in ...interface{}) string {
return fmt.Sprintf(format, scs.Sdump(in...))
}
// Attempts to set the given reflect.Value to the given interface value
func SetValue(target interface{}, value interface{}) error {
var targetV, valueV, originalV reflect.Value
// if we were given a reflect.Value target, then we shouldn't take the reflect.ValueOf that
if tV, ok := target.(reflect.Value); ok {
targetV = tV
} else {
targetV = reflect.ValueOf(target)
if targetV.Kind() == reflect.Struct {
return fmt.Errorf("Must pass a pointer to a struct instance, got %T", target)
} else if targetV.Kind() == reflect.Ptr {
// dereference pointers to get at the real destination
targetV = targetV.Elem()
}
}
// targets must be valid in order to set them to values
if !targetV.IsValid() {
return fmt.Errorf("Target %T is not valid", target)
}
// perform custom type conversions (if any)
if v, err := utils.ConvertCustomType(value); err == nil {
value = v
} else if err != utils.PassthroughType {
return err
}
// if the value we were given was a reflect.Value, just use that
if vV, ok := value.(reflect.Value); ok {
originalV = vV
valueV = vV
} else {
originalV = reflect.ValueOf(value)
valueV = reflect.ValueOf(ResolveValue(value))
}
// get the underlying value that was passed in
if valueV.IsValid() {
targetT := targetV.Type()
valueT := valueV.Type()
// if the target value is a string-a-like, stringify whatever we got in
if targetT.Kind() == reflect.String && valueV.CanInterface() {
valueV = reflect.ValueOf(fmt.Sprintf("%v", valueV.Interface()))
valueT = valueV.Type()
if !valueV.IsValid() {
return fmt.Errorf(
"Converting %T to %v produced an invalid value",
value,
targetT,
)
}
}
if valueT.AssignableTo(targetT) {
// attempt direct assignment
targetV.Set(valueV)
} else if valueT.ConvertibleTo(targetT) {
// attempt type conversion
targetV.Set(valueV.Convert(targetT))
} else if targetV.Kind() == reflect.Ptr {
if originalV.Kind() == reflect.Ptr {
return SetValue(targetV, originalV)
} else {
return fmt.Errorf(
"Unable to set target: value for target %v must be given as a pointer",
targetT,
)
}
} else {
if targetV.Kind() == reflect.Struct {
if embeddedV := targetV.FieldByName(valueT.Name()); embeddedV.IsValid() {
if err := SetValue(embeddedV, value); err == nil {
return nil
}
}
}
// handle some well-know, type specific edge cases
switch value.(type) {
case time.Time:
return SetValue(target, value.(time.Time).UnixNano())
case *time.Time:
if tm := value.(*time.Time); tm != nil {
return SetValue(target, tm.UnixNano())
}
}
// no dice.
return fmt.Errorf(
"Unable to set target: %T has no path to becoming %v",
value,
targetT,
)
}
} else {
return fmt.Errorf("Unable to set target to the given %T value", value)
}
return nil
}
func IsKindOfInteger(in interface{}) bool {
var kind reflect.Kind
if k, ok := in.(reflect.Kind); ok {
kind = k
} else {
kind = reflect.TypeOf(in).Kind()
}
return IsKind(
kind,
reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64,
reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64,
reflect.Uintptr,
)
}
func IsKindOfFloat(in interface{}) bool {
var kind reflect.Kind
if k, ok := in.(reflect.Kind); ok {
kind = k
} else {
kind = reflect.TypeOf(in).Kind()
}
return IsKind(
kind,
reflect.Float32,
reflect.Float64,
)
}
func IsKindOfBool(in interface{}) bool {
var kind reflect.Kind
if k, ok := in.(reflect.Kind); ok {
kind = k
} else {
kind = reflect.TypeOf(in).Kind()
}
return IsKind(kind, reflect.Bool)
}
func IsKindOfString(in interface{}) bool {
var kind reflect.Kind
if k, ok := in.(reflect.Kind); ok {
kind = k
} else if inT := reflect.TypeOf(in); inT != nil {
kind = inT.Kind()
}
return IsKind(kind, reflect.String)
}