-
Notifications
You must be signed in to change notification settings - Fork 29
/
converter.go
1520 lines (1404 loc) · 41 KB
/
converter.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package toolbox
import (
"errors"
"fmt"
"math"
"reflect"
"strconv"
"strings"
"time"
)
// DefaultDateLayout is set to 2006-01-02 15:04:05.000
var DefaultDateLayout = "2006-01-02 15:04:05.000"
var numericTypes = []reflect.Type{
reflect.TypeOf(int(0)),
reflect.TypeOf(int8(0)),
reflect.TypeOf(int16(0)),
reflect.TypeOf(int32(0)),
reflect.TypeOf(int64(0)),
reflect.TypeOf(uint(0)),
reflect.TypeOf(uint8(0)),
reflect.TypeOf(uint16(0)),
reflect.TypeOf(uint32(0)),
reflect.TypeOf(uint64(0)),
reflect.TypeOf(float32(0.0)),
reflect.TypeOf(float64(0.0)),
}
// AsString converts an input to string.
func AsString(input interface{}) string {
switch value := input.(type) {
case string:
return value
case *string:
if value == nil {
return ""
}
return *value
case []byte:
return string(value)
case []interface{}:
if len(value) == 0 {
return ""
}
if _, isByte := value[0].(byte); isByte {
var stringBytes = make([]byte, len(value))
for i, v := range value {
stringBytes[i] = v.(byte)
}
return string(stringBytes)
}
var result = ""
for _, v := range value {
result += AsString(v)
}
return result
}
reflectValue := reflect.ValueOf(input)
if reflectValue.Kind() == reflect.Ptr {
reflectValue = reflectValue.Elem()
}
switch reflectValue.Kind() {
case reflect.Bool:
return strconv.FormatBool(reflectValue.Bool())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(reflectValue.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return strconv.FormatUint(reflectValue.Uint(), 10)
case reflect.Float64:
return strconv.FormatFloat(reflectValue.Float(), 'g', -1, 64)
case reflect.Float32:
return strconv.FormatFloat(reflectValue.Float(), 'g', -1, 32)
}
return fmt.Sprintf("%v", input)
}
// CanConvertToFloat checkis if float conversion is possible.
func CanConvertToFloat(value interface{}) bool {
if _, ok := value.(float64); ok {
return true
}
_, err := strconv.ParseFloat(AsString(value), 64)
return err == nil
}
// AsFloat converts an input to float.
func AsFloat(value interface{}) float64 {
if result, err := ToFloat(value); err == nil {
return result
}
return 0
}
// ToFloat converts an input to float or error
func ToFloat(value interface{}) (float64, error) {
if value == nil {
return 0, NewNilPointerError("float value was nil")
}
switch actualValue := value.(type) {
case float64:
return actualValue, nil
case *float64:
if actualValue == nil {
return 0, nil
}
return *actualValue, nil
case *float32:
if actualValue == nil {
return 0, nil
}
return float64(*actualValue), nil
case int:
return float64(actualValue), nil
case uint:
return float64(actualValue), nil
case int64:
return float64(actualValue), nil
case uint64:
return float64(actualValue), nil
case int32:
return float64(actualValue), nil
case uint32:
return float64(actualValue), nil
case float32:
return float64(actualValue), nil
case bool:
if actualValue {
return 1.0, nil
}
return 0.0, nil
}
if reflect.TypeOf(value).Kind() == reflect.Ptr {
floatValue, err := ToFloat(DereferenceValue(value))
if err != nil && IsNilPointerError(err) {
return floatValue, nil
}
return floatValue, err
}
valueAsString := AsString(DereferenceValue(value))
return strconv.ParseFloat(valueAsString, 64)
}
// ToBoolean converts an input to bool.
func ToBoolean(value interface{}) (bool, error) {
if boolValue, ok := value.(bool); ok {
return boolValue, nil
}
valueAsString := AsString(value)
return strconv.ParseBool(valueAsString)
}
// AsBoolean converts an input to bool.
func AsBoolean(value interface{}) bool {
result, err := ToBoolean(value)
if err != nil {
return false
}
return result
}
// CanConvertToInt returns true if an input can be converted to int value.
func CanConvertToInt(value interface{}) bool {
if _, ok := value.(int); ok {
return true
}
valueAsString := AsString(value)
if _, err := strconv.ParseInt(valueAsString, 10, 64); err == nil {
return true
}
return false
}
var intBitSize = reflect.TypeOf(int64(0)).Bits()
// AsInt converts an input to int.
func AsInt(value interface{}) int {
var result, err = ToInt(value)
if err == nil {
return result
} else {
var floatResult, err = ToFloat(value)
if err == nil {
return AsInt(floatResult)
}
}
return 0
}
// ToInt converts input value to int or error
func ToInt(value interface{}) (int, error) {
if text, ok := value.(string); ok { //common use case
return strconv.Atoi(text)
}
return toInt(value)
}
func toInt(value interface{}) (int, error) {
if value == nil {
return 0, NewNilPointerError("int value was nil")
}
switch actual := value.(type) {
case int:
return actual, nil
case *int:
if actual == nil {
return 0, nil
}
return *actual, nil
case int8:
return int(actual), nil
case int16:
return int(actual), nil
case int32:
return int(actual), nil
case *int64:
if actual == nil {
return 0, nil
}
return int(*actual), nil
case int64:
return int(actual), nil
case uint:
return int(actual), nil
case uint8:
return int(actual), nil
case uint16:
return int(actual), nil
case uint32:
return int(actual), nil
case uint64:
return int(actual), nil
case float32:
return int(actual), nil
case float64:
return int(actual), nil
case bool:
if actual {
return 1, nil
}
return 0, nil
}
if reflect.TypeOf(value).Kind() == reflect.Ptr {
value := DereferenceValue(value)
if intValue, err := ToInt(value); err != nil {
if err != nil && IsNilPointerError(err) {
return intValue, err
}
return intValue, err
}
}
valueAsString := AsString(value)
if strings.Contains(valueAsString, ".") {
floatValue, err := strconv.ParseFloat(valueAsString, intBitSize)
if err != nil {
return 0, err
}
return int(floatValue), nil
}
result, err := strconv.ParseInt(valueAsString, 10, 64)
return int(result), err
}
func unitToTime(timestamp int64) *time.Time {
var timeValue time.Time
if timestamp > math.MaxUint32 {
var timestampInMs = timestamp / 1000000
if timestampInMs > math.MaxUint32 {
timeValue = time.Unix(0, timestamp)
} else {
timeValue = time.Unix(0, timestamp*1000000)
}
} else {
timeValue = time.Unix(timestamp, 0)
}
return &timeValue
}
func textToTime(value, dateLayout string) (*time.Time, error) {
floatValue, err := ToFloat(value)
if err == nil {
return unitToTime(int64(floatValue)), nil
}
rawValue := value
timeValue, err := ParseTime(value, dateLayout)
if err != nil {
if dateLayout != "" {
updated := value
if len(value) > len(dateLayout) {
updated = string(value[:len(dateLayout)])
}
timeValue, err = ParseTime(updated, dateLayout)
}
if err != nil { //JSON default time format fallback
if timeValue, err = ParseTime(value, time.RFC3339); err == nil {
return &timeValue, err
}
if msIndex := strings.LastIndex(rawValue, "."); msIndex != -1 && msIndex < len(value)-1 {
ms := value[msIndex+1:]
i := 0
for ; i < len(ms); i++ {
if ms[i] < '0' || ms[i] > '9' {
break
}
}
msLayout := fmt.Sprintf("2006-01-02T15:04:05.%sZ07:00", strings.Repeat("9", i))
if timeValue, err = ParseTime(rawValue, msLayout); err == nil {
return &timeValue, err
}
}
return nil, err
}
}
return &timeValue, nil
}
// ToTime converts value to time, optionally uses layout if value if of string type
func ToTime(value interface{}, dateLayout string) (*time.Time, error) {
if value == nil {
return nil, errors.New("values was empty")
}
switch actual := value.(type) {
case time.Time:
return &actual, nil
case *time.Time:
return actual, nil
case float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
var floatValue, _ = ToFloat(value)
return unitToTime(int64(floatValue)), nil
case *float32, *float64, *int, *int8, *int16, *int32, *int64, *uint, *uint8, *uint16, *uint32, *uint64:
actual = DereferenceValue(actual)
return ToTime(actual, dateLayout)
case string:
return textToTime(actual, dateLayout)
case map[string]interface{}:
if len(actual) == 0 {
return nil, nil
}
}
textValue := AsString(DereferenceValue(value))
return textToTime(textValue, dateLayout)
}
// AsTime converts an input to time, it takes time input, dateLaout as parameters.
func AsTime(value interface{}, dateLayout string) *time.Time {
result, err := ToTime(value, dateLayout)
if err != nil {
return nil
}
return result
}
// DiscoverValueAndKind discovers input kind, it applies checks of the following types: int, float, bool, string
func DiscoverValueAndKind(input string) (interface{}, reflect.Kind) {
if len(input) == 0 {
return nil, reflect.Invalid
}
if strings.Contains(input, ".") {
if floatValue, err := strconv.ParseFloat(input, 64); err == nil {
return floatValue, reflect.Float64
}
}
if intValue, err := strconv.ParseInt(input, 10, 64); err == nil {
return int(intValue), reflect.Int
} else if strings.ToLower(input) == "true" {
return true, reflect.Bool
} else if strings.ToLower(input) == "false" {
return false, reflect.Bool
}
return input, reflect.String
}
// DiscoverCollectionValuesAndKind discovers passed in slice item kind, and returns slice of values converted to discovered type.
// It tries the following kind int, float, bool, string
func DiscoverCollectionValuesAndKind(values interface{}) ([]interface{}, reflect.Kind) {
var candidateKind = reflect.Int
var result = make([]interface{}, 0)
ProcessSlice(values, func(value interface{}) bool {
stringValue := strings.ToLower(AsString(value))
switch candidateKind {
case reflect.String:
return false
case reflect.Int:
if !strings.Contains(stringValue, ".") && CanConvertToInt(value) {
return true
}
candidateKind = reflect.Float64
fallthrough
case reflect.Float64:
if CanConvertToFloat(value) {
return true
}
candidateKind = reflect.Bool
fallthrough
case reflect.Bool:
if stringValue == "true" || stringValue == "false" {
return true
}
candidateKind = reflect.String
}
return true
})
ProcessSlice(values, func(value interface{}) bool {
switch candidateKind {
case reflect.Float64:
result = append(result, AsFloat(value))
case reflect.Int:
result = append(result, AsInt(value))
case reflect.Bool:
result = append(result, AsBoolean(value))
default:
result = append(result, AsString(value))
}
return true
})
return result, candidateKind
}
// UnwrapValue returns value
func UnwrapValue(value *reflect.Value) interface{} {
return value.Interface()
}
// NewBytes copies from input
func NewBytes(input []byte) []byte {
if input != nil {
var result = make([]byte, len(input))
copy(result, input)
return result
}
return nil
}
// ParseTime parses time, adjusting date layout to length of input
func ParseTime(input, layout string) (time.Time, error) {
if len(layout) == 0 {
layout = DefaultDateLayout
} //GetFieldValue returns field value
lastPosition := len(input)
if lastPosition >= len(layout) {
lastPosition = len(layout)
}
layout = layout[0:lastPosition]
return time.Parse(layout, input)
}
// Converter represets data converter, it converts incompatibe data structure, like map and struct, string and time, *string to string, etc.
type Converter struct {
DateLayout string
MappedKeyTag string
}
func (c *Converter) assignConvertedMap(target, source interface{}, targetIndirectValue reflect.Value, targetIndirectPointerType reflect.Type) error {
mapType := DiscoverTypeByKind(target, reflect.Map)
mapPointer := reflect.New(mapType)
mapValueType := mapType.Elem()
mapKeyType := mapType.Key()
newMap := mapPointer.Elem()
newMap.Set(reflect.MakeMap(mapType))
var err error
err = ProcessMap(source, func(key, value interface{}) bool {
if value == nil {
return true
}
mapValueType = reflect.TypeOf(value)
targetMapValuePointer := reflect.New(mapValueType)
err = c.AssignConverted(targetMapValuePointer.Interface(), value)
if err != nil {
err = fmt.Errorf("failed to assigned converted map value %v to %v due to %v", source, target, err)
return false
}
targetMapKeyPointer := reflect.New(mapKeyType)
err = c.AssignConverted(targetMapKeyPointer.Interface(), key)
if err != nil {
err = fmt.Errorf("failed to assigned converted map key %v to %v due to %v", source, target, err)
return false
}
var elementKey = targetMapKeyPointer.Elem()
var elementValue = targetMapValuePointer.Elem()
if elementKey.Type() != mapKeyType {
if elementKey.Type().AssignableTo(mapKeyType) {
elementKey = elementKey.Convert(mapKeyType)
}
}
if !elementValue.Type().AssignableTo(newMap.Type().Elem()) {
var compatibleValue = reflect.New(newMap.Type().Elem())
err = c.AssignConverted(compatibleValue.Interface(), elementValue.Interface())
if err != nil {
return false
}
elementValue = compatibleValue.Elem()
}
newMap.SetMapIndex(elementKey, elementValue)
return true
})
if err != nil {
return err
}
if targetIndirectPointerType.Kind() == reflect.Map {
if targetIndirectValue.Type().AssignableTo(mapPointer.Type()) {
targetIndirectValue.Set(mapPointer)
} else {
targetIndirectValue.Set(mapPointer.Elem())
}
} else {
targetIndirectValue.Set(newMap)
}
return err
}
func (c *Converter) assignConvertedSlice(target, source interface{}, targetIndirectValue reflect.Value, targetIndirectPointerType reflect.Type) error {
sliceType := DiscoverTypeByKind(target, reflect.Slice)
slicePointer := reflect.New(sliceType)
slice := slicePointer.Elem()
componentType := DiscoverComponentType(target)
var err error
ProcessSlice(source, func(item interface{}) bool {
var targetComponentPointer = reflect.New(componentType)
if componentType.Kind() == reflect.Map {
targetComponent := reflect.MakeMap(componentType)
targetComponentPointer.Elem().Set(targetComponent)
}
err = c.AssignConverted(targetComponentPointer.Interface(), item)
if err != nil {
err = fmt.Errorf("failed to convert slice item from %T to %T, values: from %v to %v, due to %v", item, targetComponentPointer.Interface(), item, targetComponentPointer.Interface(), err)
return false
}
slice.Set(reflect.Append(slice, targetComponentPointer.Elem()))
return true
})
if targetIndirectPointerType.Kind() == reflect.Slice {
targetIndirectValue.Set(slicePointer)
} else {
targetIndirectValue.Set(slice)
}
return err
}
func (c *Converter) assignConvertedStruct(target interface{}, inputMap map[string]interface{}, targetIndirectValue reflect.Value, targetIndirectPointerType reflect.Type) error {
newStructPointer := reflect.New(targetIndirectValue.Type())
newStruct := newStructPointer.Elem()
fieldsMapping := NewFieldSettingByKey(newStructPointer.Interface(), c.MappedKeyTag)
var defaultValueMap = make(map[string]interface{})
var anonymousValueMap map[string]reflect.Value
var anonymousFields map[string]reflect.Value
for _, value := range fieldsMapping {
if defaultValue, ok := value[defaultKey]; ok {
var fieldName = value[fieldNameKey]
defaultValueMap[fieldName] = defaultValue
}
if index, ok := value[fieldIndexKey]; ok {
if len(anonymousValueMap) == 0 {
anonymousValueMap = make(map[string]reflect.Value)
anonymousFields = make(map[string]reflect.Value)
}
field := newStruct.Field(AsInt(index))
if field.Type().Kind() == reflect.Ptr {
fieldStruct := reflect.New(field.Type().Elem())
anonymousValueMap[index] = fieldStruct
anonymousFields[index] = field
} else {
anonymousValueMap[index] = field.Addr()
anonymousFields[index] = field.Addr()
}
}
}
for key, value := range inputMap {
aStruct := newStruct
mapping, found := fieldsMapping[strings.ToLower(key)]
if found {
var field reflect.Value
fieldName := mapping[fieldNameKey]
if fieldIndex, ok := mapping[fieldIndexKey]; ok {
var structPointer = anonymousValueMap[fieldIndex]
if anonymousFields[fieldIndex].CanAddr() {
anonymousFields[fieldIndex].Set(structPointer)
}
aStruct = structPointer.Elem()
initAnonymousStruct(structPointer.Interface())
}
field = aStruct.FieldByName(fieldName)
fieldType, _ := aStruct.Type().FieldByName(fieldName)
if isExported := fieldType.PkgPath == ""; !isExported {
structField := &StructField{
Owner: newStructPointer,
Value: field,
Type: fieldType,
}
if !onUnexportedHandler(structField) {
continue
}
field = structField.Value
}
if _, has := defaultValueMap[fieldName]; has {
delete(defaultValueMap, fieldName)
}
previousLayout := c.DateLayout
if HasTimeLayout(mapping) {
c.DateLayout = GetTimeLayout(mapping)
c.DateLayout = previousLayout
}
if (!field.CanAddr()) && field.Kind() == reflect.Ptr {
if err := c.AssignConverted(field.Interface(), value); err != nil {
return fmt.Errorf("failed to convert %v to %v due to %v", value, field, err)
}
} else {
if value == nil {
continue
}
if err := c.AssignConverted(field.Addr().Interface(), value); err != nil {
return fmt.Errorf("failed to convert %v to %v due to %v", value, field, err)
}
}
if HasTimeLayout(mapping) {
c.DateLayout = previousLayout
}
}
}
for fieldName, value := range defaultValueMap {
field := newStruct.FieldByName(fieldName)
err := c.AssignConverted(field.Addr().Interface(), value)
if err != nil {
return fmt.Errorf("failed to assign default value %v to %v due to %v", value, field, err)
}
}
if targetIndirectPointerType.Kind() == reflect.Slice {
targetIndirectValue.Set(newStructPointer)
} else {
targetIndirectValue.Set(newStruct)
}
return nil
}
// customConverter map of target, source type with converter
var customConverter = make(map[reflect.Type]map[reflect.Type]func(target, source interface{}) error)
// RegisterConverter register custom converter for supplied target, source type
func RegisterConverter(target, source reflect.Type, converter func(target, source interface{}) error) {
if _, ok := customConverter[target]; !ok {
customConverter[target] = make(map[reflect.Type]func(target, source interface{}) error)
}
customConverter[target][source] = converter
}
// GetConverter returns register converter for supplied target and source type
func GetConverter(target, source interface{}) (func(target, source interface{}) error, bool) {
sourceConverters, ok := customConverter[reflect.TypeOf(target)]
if !ok {
return nil, false
}
converter, ok := sourceConverters[reflect.TypeOf(source)]
return converter, ok
}
// AssignConverted assign to the target source, target needs to be pointer, input has to be convertible or compatible type
func (c *Converter) AssignConverted(target, source interface{}) error {
if target == nil {
return fmt.Errorf("destination Pointer was nil %v %v", target, source)
}
if source == nil {
return nil
}
switch targetValuePointer := target.(type) {
case *string:
switch sourceValue := source.(type) {
case string:
*targetValuePointer = sourceValue
return nil
case *string:
*targetValuePointer = *sourceValue
return nil
case []byte:
*targetValuePointer = string(sourceValue)
return nil
case *[]byte:
*targetValuePointer = string(NewBytes(*sourceValue))
return nil
default:
*targetValuePointer = AsString(source)
return nil
}
case **string:
switch sourceValue := source.(type) {
case string:
*targetValuePointer = &sourceValue
return nil
case *string:
*targetValuePointer = sourceValue
return nil
case []byte:
var stringSourceValue = string(sourceValue)
*targetValuePointer = &stringSourceValue
return nil
case *[]byte:
var stringSourceValue = string(NewBytes(*sourceValue))
*targetValuePointer = &stringSourceValue
return nil
default:
stringSourceValue := AsString(source)
*targetValuePointer = &stringSourceValue
return nil
}
case *[]string:
switch sourceValue := source.(type) {
case []string:
*targetValuePointer = sourceValue
return nil
case *[]string:
*targetValuePointer = *sourceValue
return nil
case *string:
transient := []string{*sourceValue}
*targetValuePointer = transient
return nil
case string:
transient := []string{sourceValue}
*targetValuePointer = transient
return nil
default:
if IsSlice(source) {
var stingItems = make([]string, 0)
ProcessSlice(source, func(item interface{}) bool {
stingItems = append(stingItems, AsString(item))
return true
})
*targetValuePointer = stingItems
return nil
} else if IsMap(source) {
if len(AsMap(source)) == 0 {
return nil
}
}
return fmt.Errorf("expected []string but had: %T", source)
}
case *bool:
switch sourceValue := source.(type) {
case bool:
*targetValuePointer = sourceValue
return nil
case *bool:
*targetValuePointer = *sourceValue
return nil
case int:
*targetValuePointer = sourceValue != 0
return nil
case string:
if sourceValue == "" {
*targetValuePointer = false
return nil
}
boolValue, err := strconv.ParseBool(sourceValue)
if err != nil {
return err
}
*targetValuePointer = boolValue
return nil
case *string:
if sourceValue == nil || *sourceValue == "" {
*targetValuePointer = false
return nil
}
boolValue, err := strconv.ParseBool(*sourceValue)
if err != nil {
return err
}
*targetValuePointer = boolValue
return nil
}
case **bool:
switch sourceValue := source.(type) {
case bool:
*targetValuePointer = &sourceValue
return nil
case *bool:
*targetValuePointer = sourceValue
return nil
case int:
boolValue := sourceValue != 0
*targetValuePointer = &boolValue
return nil
case string:
if sourceValue == "" {
boolVal := false
*targetValuePointer = &boolVal
return nil
}
boolValue, err := strconv.ParseBool(sourceValue)
if err != nil {
return err
}
*targetValuePointer = &boolValue
return nil
case *string:
if sourceValue == nil || *sourceValue == "" {
boolVal := false
*targetValuePointer = &boolVal
return nil
}
boolValue, err := strconv.ParseBool(*sourceValue)
if err != nil {
return err
}
*targetValuePointer = &boolValue
return nil
}
case *[]byte:
switch sourceValue := source.(type) {
case []byte:
*targetValuePointer = sourceValue
return nil
case *[]byte:
*targetValuePointer = *sourceValue
return nil
case string:
*targetValuePointer = []byte(sourceValue)
return nil
case *string:
var stringValue = *sourceValue
*targetValuePointer = []byte(stringValue)
return nil
}
case **[]byte:
switch sourceValue := source.(type) {
case []byte:
bytes := NewBytes(sourceValue)
*targetValuePointer = &bytes
return nil
case *[]byte:
bytes := NewBytes(*sourceValue)
*targetValuePointer = &bytes
return nil
case string:
bytes := []byte(sourceValue)
*targetValuePointer = &bytes
return nil
case *string:
bytes := []byte(*sourceValue)
*targetValuePointer = &bytes
return nil
}
case *int, *int8, *int16, *int32, *int64:
directValue := reflect.Indirect(reflect.ValueOf(targetValuePointer))
var intValue, err = ToInt(source)
if err != nil {
return err
}
directValue.SetInt(int64(intValue))
return nil
case **int, **int8, **int16, **int32, **int64:
directType := reflect.TypeOf(targetValuePointer).Elem().Elem()
var intValue, err = ToInt(source)
if err != nil {
if IsNilPointerError(err) {
return nil
}
return err
}
switch directType.Kind() {
case reflect.Int8:
alignValue := int8(intValue)
reflect.ValueOf(targetValuePointer).Elem().Set(reflect.ValueOf(&alignValue))
case reflect.Int16:
alignValue := int16(intValue)
reflect.ValueOf(targetValuePointer).Elem().Set(reflect.ValueOf(&alignValue))
case reflect.Int32:
alignValue := int32(intValue)
reflect.ValueOf(targetValuePointer).Elem().Set(reflect.ValueOf(&alignValue))
case reflect.Int64:
alignValue := int64(intValue)
reflect.ValueOf(targetValuePointer).Elem().Set(reflect.ValueOf(&alignValue))
default:
reflect.ValueOf(targetValuePointer).Elem().Set(reflect.ValueOf(&intValue))
}
return nil
case *uint, *uint8, *uint16, *uint32, *uint64:
directValue := reflect.Indirect(reflect.ValueOf(targetValuePointer))
value, err := ToInt(source)
if err != nil {
return err
}
directValue.SetUint(uint64(value))
return nil
case **uint, **uint8, **uint16, **uint32, **uint64:
directType := reflect.TypeOf(targetValuePointer).Elem().Elem()
value, err := ToInt(source)
if !IsNilPointerError(err) && err != nil {
return err
}
switch directType.Kind() {
case reflect.Uint8:
alignValue := uint8(value)
reflect.ValueOf(targetValuePointer).Elem().Set(reflect.ValueOf(&alignValue))
case reflect.Uint16:
alignValue := uint16(value)
reflect.ValueOf(targetValuePointer).Elem().Set(reflect.ValueOf(&alignValue))
case reflect.Uint32:
alignValue := uint32(value)
reflect.ValueOf(targetValuePointer).Elem().Set(reflect.ValueOf(&alignValue))
case reflect.Uint64:
alignValue := uint64(value)
reflect.ValueOf(targetValuePointer).Elem().Set(reflect.ValueOf(&alignValue))
default:
reflect.ValueOf(targetValuePointer).Elem().Set(reflect.ValueOf(&value))
}
return nil
case *float32, *float64:
directValue := reflect.Indirect(reflect.ValueOf(targetValuePointer))
value, err := ToFloat(source)
if err != nil {
return err
}
directValue.SetFloat(value)
return nil
case **float32, **float64:
directType := reflect.TypeOf(targetValuePointer).Elem().Elem()
value, err := ToFloat(source)
if err != nil {
return err
}
if directType.Kind() == reflect.Float32 {
float32Value := float32(value)
reflect.ValueOf(targetValuePointer).Elem().Set(reflect.ValueOf(&float32Value))
} else {
reflect.ValueOf(targetValuePointer).Elem().Set(reflect.ValueOf(&value))
}
return nil
case *time.Time:
timeValue, err := ToTime(source, c.DateLayout)
if err != nil {
return err
}
*targetValuePointer = *timeValue
return nil
case **time.Time:
if source == nil {
return nil
}
timeValue, err := ToTime(source, c.DateLayout)
if err != nil {
return err
}
*targetValuePointer = timeValue
return nil
case *interface{}:
if converter, ok := GetConverter(target, source); ok {
return converter(target, source)
}
(*targetValuePointer) = source
return nil
case **interface{}:
if converter, ok := GetConverter(target, source); ok {
return converter(target, source)
}
(*targetValuePointer) = &source
return nil
default:
if converter, ok := GetConverter(target, source); ok {
return converter(target, source)
}
}
sourceValue := reflect.ValueOf(source)
if source == nil || !sourceValue.IsValid() || (sourceValue.CanSet() && sourceValue.IsNil()) {
return nil