This repository was archived by the owner on Dec 30, 2025. It is now read-only.
forked from mitchellh/mapstructure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassign.go
More file actions
1590 lines (1324 loc) · 42.7 KB
/
assign.go
File metadata and controls
1590 lines (1324 loc) · 42.7 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
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 object
import (
"encoding/json"
"errors"
"fmt"
"math"
"reflect"
"strconv"
"strings"
)
var defaultAssigner *assigner
var weakAssigner *assigner
func init() {
defaultAssigner = newAssigner(&AssignConfig{
TagName: "json",
Converter: toLowerCamel,
})
weakAssigner = newAssigner(&AssignConfig{
TagName: "json",
Converter: toLowerCamel,
WeaklyTypedInput: true,
})
}
// AssignConfig is the configuration used to create a new decoder
// and allows customization of various aspects of decoding.
type AssignConfig struct {
// If WeaklyTypedInput is true, the decoder will make the following
// "weak" conversions:
//
// - bools to string (true = "1", false = "0")
// - numbers to string (base 10)
// - bools to int/uint (true = 1, false = 0)
// - strings to int/uint (base implied by prefix)
// - int to bool (true if value != 0)
// - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F,
// FALSE, false, False. Anything else is an error)
// - empty array = empty map and vice versa
// - negative numbers to overflowed uint values (base 10)
// - slice of maps to a merged map
// - single values are converted to slices if required. Each
// element is weakly decoded. For example: "4" can become []int{4}
// if the target type is an int slice.
//
WeaklyTypedInput bool
// TagName is the tag name that object reads for field names.
// This defaults to "json"
TagName string
// IncludeIgnoreFields includes all struct fields that were ignored by '-'
IncludeIgnoreFields bool
// Converter is the function used to convert the struct field name
// to map key. Defaults to `Lower Camel`.
Converter func(fieldName string) string
// Metadata is the struct that will contain extra metadata about
// the decoding. If this is nil, then no metadata will be tracked.
Metadata *Metadata
// SkipKeys is a list of keys that should be skipped during decoding.
SkipKeys []string
// SkipSameValues if true will skip the same values during decoding.
SkipSameValues bool
}
// Metadata contains information about the decoding process that
// would be tedious or difficult to obtain otherwise.
type Metadata struct {
// Keys are the target object keys of the structure which were successfully assigned
Keys []string
// Unused are the keys that were found in the source but
// weren't decoded since there was no matching field in the target object
Unused []string
// Unset are the field names that were found in the target object
// but weren't set in the decoding process since there was no matching value
// in the input
Unset []string
}
// Assign decodes values from the source object and assigns them to the target object.
// This function uses reflection, so it can handle objects of any type.
// Parameters:
// - target: Any type, pointer to the object that will be assigned values.
// - source: Any type, source object whose values will be decoded into target.
// - configs: Optional function slice for configuring the decoding process,
// each function receives a *AssignConfig pointer.
//
// Returns:
// - error: Returns an error if an error occurs during the decoding process.
func Assign(target any, source any, configs ...func(c *AssignConfig)) error {
return defaultAssigner.Assign(target, source, configs...)
}
type assigner struct {
config *AssignConfig
skipKeysCache map[string]struct{}
}
func newAssigner(c *AssignConfig) *assigner {
a := &assigner{
config: c,
skipKeysCache: make(map[string]struct{}),
}
for _, k := range c.SkipKeys {
a.skipKeysCache[k] = struct{}{}
}
return a
}
func (a *assigner) withConfig(configs ...func(c *AssignConfig)) *assigner {
config := *a.config // copy config
for _, fn := range configs {
fn(&config)
}
if config.Metadata != nil {
if config.Metadata.Keys == nil {
config.Metadata.Keys = []string{}
}
if config.Metadata.Unused == nil {
config.Metadata.Unused = []string{}
}
if config.Metadata.Unset == nil {
config.Metadata.Unset = []string{}
}
}
return newAssigner(&config)
}
// Assign decodes and assigns values from the source to the target.
// The target must be a pointer to a value that can be addressed.
// It returns an error if the target is not a pointer or cannot be addressed,
// or if any error occurs during the assignment process.
func (a *assigner) Assign(target, source any, configs ...func(c *AssignConfig)) error {
// Check that target is a pointer
targetVal := reflect.ValueOf(target)
if targetVal.Kind() != reflect.Ptr {
return errors.New("target must be a pointer")
}
// Get the element that the pointer points to
targetVal = targetVal.Elem()
if !targetVal.CanAddr() {
return errors.New("target must be addressable (a pointer)")
}
// Apply custom configurations if provided
as := a
if len(configs) > 0 {
as = as.withConfig(configs...)
}
sourceVal := reflect.ValueOf(source)
// Perform the assignment
return as.assign(targetVal, "", sourceVal, "")
}
// assign decodes an unknown data type into a specific reflection value.
func (a *assigner) assign(targetVal reflect.Value, targetKey metaKey, sourceVal reflect.Value, sourceKey metaKey) error {
// Check if we should skip this key based on configuration
if a.shouldSkipKey(targetKey, sourceKey) {
return nil
}
// Handle typed nil values
if sourceVal.IsValid() {
// Check if input is a typed nil. Typed nils won't
// match the "source == nil" check below, so we handle them here.
if sourceVal.Kind() == reflect.Ptr && sourceVal.IsNil() {
sourceVal = reflect.Value{}
}
}
// Handle invalid source values
if !sourceVal.IsValid() {
return nil
}
// Skip same values if configured to do so
if a.config.SkipSameValues {
if reflect.DeepEqual(targetVal.Interface(), sourceVal.Interface()) {
a.addMetaUnused(sourceKey)
a.addMetaUnset(targetKey)
return nil
}
}
if sourceVal.Kind() == reflect.Interface {
sourceVal = sourceVal.Elem()
}
// Process based on target type
var err error
targetKind := targetVal.Kind()
addMetaKey := true
switch targetKind {
case reflect.Bool:
err = a.assignBool(targetVal, targetKey, sourceVal, sourceKey)
case reflect.Interface:
err = a.assignBasic(targetVal, targetKey, sourceVal, sourceKey)
case reflect.String:
err = a.assignString(targetVal, targetKey, sourceVal, sourceKey)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
err = a.assignInt(targetVal, targetKey, sourceVal, sourceKey)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
err = a.assignUint(targetVal, targetKey, sourceVal, sourceKey)
case reflect.Float32, reflect.Float64:
err = a.assignFloat(targetVal, targetKey, sourceVal, sourceKey)
case reflect.Struct:
err = a.assignStruct(targetVal, targetKey, sourceVal, sourceKey)
case reflect.Map:
err = a.assignMap(targetVal, targetKey, sourceVal, sourceKey)
case reflect.Ptr:
addMetaKey, err = a.assignPtr(targetVal, targetKey, sourceVal, sourceKey)
case reflect.Slice:
err = a.assignSlice(targetVal, targetKey, sourceVal, sourceKey)
case reflect.Array:
err = a.assignArray(targetVal, targetKey, sourceVal, sourceKey)
case reflect.Func:
err = a.assignFunc(targetVal, targetKey, sourceVal, sourceKey)
default:
// Unsupported type
return fmt.Errorf("%s: unsupported type: %s", targetKey.String(), targetKind)
}
// Mark key as used if we're tracking metadata and assignment was successful
if addMetaKey && err == nil {
a.addMetaKey(targetKey)
}
return err
}
// assignBasic decodes a basic type (bool, int, string, etc.) and sets the
// value to "data" of that type.
func (a *assigner) assignBasic(targetVal reflect.Value, targetKey metaKey, sourceVal reflect.Value, sourceKey metaKey) error {
// Handle the case where targetVal is a valid pointer to a valid element
if targetVal.IsValid() && targetVal.Elem().IsValid() {
elem := targetVal.Elem()
// If we can't address this element, then it's not writable. Instead,
// we make a copy of the value (which is a pointer and therefore
// writable), decode into that, and replace the whole value.
copied := false
if !elem.CanAddr() {
copied = true
// Create a new pointer to the element's type
copy := reflect.New(elem.Type())
// Set the copy's element to the original element's value
copy.Elem().Set(elem)
// Update elem to point to our copy so we decode into it
elem = copy
}
// Decode the value. If there's an error, return it immediately.
// Also return immediately if we're not working with a copy,
// which means we decoded directly.
if err := a.assign(elem, targetKey, sourceVal, sourceKey); err != nil || !copied {
return err
}
// If we used a copy, we need to set the final result
targetVal.Set(elem.Elem())
return nil
}
// If the input data is a pointer, and the assigned type is the dereference
// of that exact pointer, then indirect it so that we can assign it.
// Example: *string to string
if sourceVal.Kind() == reflect.Ptr && sourceVal.Type().Elem() == targetVal.Type() {
sourceVal = reflect.Indirect(sourceVal)
}
// Handle invalid source values by using the zero value of target type
if !sourceVal.IsValid() {
sourceVal = reflect.Zero(targetVal.Type())
}
// Check if we can assign the source value to the target
sourceType := sourceVal.Type()
if !sourceType.AssignableTo(targetVal.Type()) {
return fmt.Errorf(
"'%s' expected type '%s', got '%s'",
targetKey.String(), targetVal.Type(), sourceType)
}
// Perform the assignment
targetVal.Set(sourceVal)
return nil
}
// assignString assigns a value to a string target, performing type conversions as needed.
func (a *assigner) assignString(targetVal reflect.Value, targetKey metaKey, sourceVal reflect.Value, _ metaKey) error {
// Get the source value, dereferencing pointers if necessary
sourceVal = reflect.Indirect(sourceVal)
sourceKind := sourceVal.Kind()
if isString(sourceKind) {
// Direct string assignment
targetVal.SetString(sourceVal.String())
return nil
}
if a.config.WeaklyTypedInput {
if isBool(sourceKind) {
// Convert boolean to string ("1" for true, "0" for false)
if sourceVal.Bool() {
targetVal.SetString("1")
} else {
targetVal.SetString("0")
}
return nil
}
if isInt(sourceKind) {
// Convert integer to string
targetVal.SetString(strconv.FormatInt(sourceVal.Int(), 10))
return nil
}
if isUint(sourceKind) {
// Convert unsigned integer to string
targetVal.SetString(strconv.FormatUint(sourceVal.Uint(), 10))
return nil
}
if isFloat(sourceKind) {
// Convert float to string
targetVal.SetString(strconv.FormatFloat(sourceVal.Float(), 'f', -1, 64))
return nil
}
if isArraySlice(sourceKind) {
// Handle slices and arrays
sourceType := sourceVal.Type()
elemKind := sourceType.Elem().Kind()
if elemKind == reflect.Uint8 {
// Convert byte slice/array to string
var uints []uint8
if sourceKind == reflect.Array {
// For arrays, copy elements to a slice
uints = make([]uint8, sourceVal.Len())
for i := range uints {
uints[i] = sourceVal.Index(i).Interface().(uint8)
}
} else {
// For slices, direct type assertion
uints = sourceVal.Interface().([]uint8)
}
targetVal.SetString(string(uints))
return nil
}
}
}
return fmt.Errorf(
"'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
targetKey.String(),
targetVal.Type(),
sourceVal.Type(),
sourceVal.Interface(),
)
}
func (a *assigner) assignInt(targetVal reflect.Value, targetKey metaKey, sourceVal reflect.Value, _ metaKey) error {
sourceVal = reflect.Indirect(sourceVal)
sourceKind := sourceVal.Kind()
sourceType := sourceVal.Type()
if isInt(sourceKind) {
targetVal.SetInt(sourceVal.Int())
return nil
}
if isUint(sourceKind) {
targetVal.SetInt(int64(sourceVal.Uint()))
return nil
}
if isFloat(sourceKind) {
targetVal.SetInt(int64(sourceVal.Float()))
return nil
}
if a.config.WeaklyTypedInput {
if isBool(sourceKind) {
if sourceVal.Bool() {
targetVal.SetInt(1)
} else {
targetVal.SetInt(0)
}
return nil
}
if isString(sourceKind) {
str := sourceVal.String()
if str == "" {
str = "0"
}
i, err := strconv.ParseInt(str, 0, targetVal.Type().Bits())
if err == nil {
targetVal.SetInt(i)
} else {
return fmt.Errorf("cannot parse '%s' as int: %s", targetKey.String(), err)
}
return nil
}
}
if sourceType.PkgPath() == "encoding/json" && sourceType.Name() == "Number" {
jn := sourceVal.Interface().(json.Number)
i, err := jn.Int64()
if err != nil {
return fmt.Errorf(
"error parsing json.Number into %s: %s", targetKey.String(), err)
}
targetVal.SetInt(i)
return nil
}
return fmt.Errorf(
"'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
targetKey.String(),
targetVal.Type(),
sourceVal.Type(),
sourceVal.Interface(),
)
}
func (a *assigner) assignUint(targetVal reflect.Value, targetKey metaKey, sourceVal reflect.Value, _ metaKey) error {
sourceVal = reflect.Indirect(sourceVal)
sourceKind := sourceVal.Kind()
sourceType := sourceVal.Type()
if isInt(sourceKind) {
i := sourceVal.Int()
if i < 0 && !a.config.WeaklyTypedInput {
return fmt.Errorf("cannot parse '%s', %d overflows uint",
targetKey.String(), i)
}
targetVal.SetUint(uint64(i))
return nil
}
if isUint(sourceKind) {
targetVal.SetUint(sourceVal.Uint())
return nil
}
if isFloat(sourceKind) {
f := sourceVal.Float()
if f < 0 && !a.config.WeaklyTypedInput {
return fmt.Errorf("cannot parse '%s', %f overflows uint",
targetKey.String(), f)
}
targetVal.SetUint(uint64(f))
return nil
}
if a.config.WeaklyTypedInput {
if isBool(sourceKind) {
if sourceVal.Bool() {
targetVal.SetUint(1)
} else {
targetVal.SetUint(0)
}
return nil
}
if isString(sourceKind) {
str := sourceVal.String()
if str == "" {
str = "0"
}
i, err := strconv.ParseUint(str, 0, targetVal.Type().Bits())
if err == nil {
targetVal.SetUint(i)
} else {
return fmt.Errorf("cannot parse '%s' as uint: %s", targetKey.String(), err)
}
return nil
}
}
if isJsonNumber(sourceType) {
jn, ok := sourceVal.Interface().(json.Number)
if !ok {
return fmt.Errorf("expected json.Number, got different type for '%s'", targetKey.String())
}
i, err := strconv.ParseUint(string(jn), 0, 64)
if err != nil {
return fmt.Errorf(
"error decoding json.Number into %s: %s", targetKey.String(), err)
}
targetVal.SetUint(i)
return nil
}
return fmt.Errorf(
"'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
targetKey.String(),
targetVal.Type(),
sourceVal.Type(),
sourceVal.Interface(),
)
}
func (a *assigner) assignBool(targetVal reflect.Value, targetKey metaKey, sourceVal reflect.Value, sourceKey metaKey) error {
sourceVal = reflect.Indirect(sourceVal)
sourceKind := sourceVal.Kind()
if isBool(sourceKind) {
targetVal.SetBool(sourceVal.Bool())
return nil
}
if a.config.WeaklyTypedInput {
if isInt(sourceKind) {
targetVal.SetBool(sourceVal.Int() != 0)
return nil
}
if isUint(sourceKind) {
targetVal.SetBool(sourceVal.Uint() != 0)
return nil
}
if isFloat(sourceKind) {
targetVal.SetBool(sourceVal.Float() != 0)
return nil
}
if isString(sourceKind) {
b, err := strconv.ParseBool(sourceVal.String())
if err == nil {
targetVal.SetBool(b)
} else if sourceVal.String() == "" {
targetVal.SetBool(false)
} else {
return fmt.Errorf("cannot parse '%s' as bool: %s", sourceKey.String(), err)
}
return nil
}
}
return fmt.Errorf(
"'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
targetKey.String(),
targetVal.Type(),
sourceVal.Type(),
sourceVal.Interface(),
)
}
func (a *assigner) assignFloat(targetVal reflect.Value, targetKey metaKey, sourceVal reflect.Value, _ metaKey) error {
sourceVal = reflect.Indirect(sourceVal)
sourceKind := sourceVal.Kind()
sourceType := sourceVal.Type()
if isInt(sourceKind) {
targetVal.SetFloat(float64(sourceVal.Int()))
return nil
}
if isUint(sourceKind) {
targetVal.SetFloat(float64(sourceVal.Uint()))
return nil
}
if isFloat(sourceKind) {
f := sourceVal.Float()
if err := a.checkNaNAndInf(targetKey, f); err != nil {
if a.config.WeaklyTypedInput {
targetVal.SetFloat(0)
} else {
return err
}
} else {
targetVal.SetFloat(f)
}
return nil
}
if a.config.WeaklyTypedInput {
if isBool(sourceKind) {
if sourceVal.Bool() {
targetVal.SetFloat(1)
} else {
targetVal.SetFloat(0)
}
return nil
}
if isString(sourceKind) {
str := sourceVal.String()
if str == "" {
str = "0"
}
f, err := strconv.ParseFloat(str, targetVal.Type().Bits())
if err != nil {
return fmt.Errorf("cannot parse '%s' as float: %s", targetKey.String(), err)
}
return a.setFloatValue(targetVal, targetKey, f)
}
}
if isJsonNumber(sourceType) {
// We need to get the interface to type assert to json.Number
sourceInterface := sourceVal.Interface()
jn, ok := sourceInterface.(json.Number)
if !ok {
return fmt.Errorf("error decoding json.Number into %s: type assertion failed", targetKey.String())
}
i, err := jn.Float64()
if err != nil {
return fmt.Errorf(
"error decoding json.Number into %s: %s", targetKey.String(), err)
}
return a.setFloatValue(targetVal, targetKey, i)
}
return fmt.Errorf(
"'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
targetKey.String(),
targetVal.Type(),
sourceVal.Type(),
sourceVal.Interface(),
)
}
// setFloatValue sets the float value after checking for NaN and Inf
func (a *assigner) setFloatValue(targetVal reflect.Value, key metaKey, f float64) error {
if err := a.checkNaNAndInf(key, f); err != nil {
if a.config.WeaklyTypedInput {
targetVal.SetFloat(0)
return nil
}
return err
}
targetVal.SetFloat(f)
return nil
}
// checkNaNAndInf checks if a float value is NaN or Infinity and returns appropriate error if needed
func (a *assigner) checkNaNAndInf(key metaKey, f float64) error {
if math.IsNaN(f) || math.IsInf(f, 0) {
return fmt.Errorf("error decoding '%s': NaN or Inf values are not allowed", key.String())
}
return nil
}
func (a *assigner) assignMap(targetVal reflect.Value, targetKey metaKey, sourceVal reflect.Value, sourceKey metaKey) error {
sourceVal = reflect.Indirect(sourceVal)
// Handle nil case explicitly
if !sourceVal.IsValid() {
return fmt.Errorf("'%s' expected a map, got nil", targetKey.String())
}
sourceKind := sourceVal.Kind()
if isMap(sourceKind) {
return a.assignMapFromMap(targetVal, targetKey, sourceVal, sourceKey)
}
if isStruct(sourceKind) {
return a.assignMapFromStruct(targetVal, targetKey, sourceVal, sourceKey)
}
if a.config.WeaklyTypedInput && isArraySlice(sourceKind) {
return a.assignMapFromSlice(targetVal, targetKey, sourceVal, sourceKey)
}
return fmt.Errorf("'%s' expected a map, got '%s'", targetKey.String(), sourceVal.Kind())
}
func (a *assigner) assignMapFromSlice(targetVal reflect.Value, targetKey metaKey, sourceVal reflect.Value, sourceKey metaKey) error {
if sourceVal.IsNil() {
return nil
}
targetMapType := targetVal.Type()
targetKeyType := targetMapType.Key()
targetElemType := targetMapType.Elem()
if sourceVal.Len() == 0 {
targetVal.Set(reflect.MakeMap(reflect.MapOf(targetKeyType, targetElemType)))
a.addMetaKey(targetKey)
return nil
}
if targetVal.IsNil() {
targetVal.Set(reflect.MakeMap(reflect.MapOf(targetKeyType, targetElemType)))
}
for i := 0; i < sourceVal.Len(); i++ {
k := strconv.Itoa(i)
srcElem := sourceVal.Index(i)
err := a.assign(
targetVal,
targetKey,
srcElem,
sourceKey.newChild(reflect.Slice, k),
)
if err != nil {
return err
}
}
return nil
}
func (a *assigner) assignMapFromMap(targetVal reflect.Value, targetKey metaKey, sourceVal reflect.Value, sourceKey metaKey) error {
targetValType := targetVal.Type()
targetValKeyType := targetValType.Key()
targetValElemType := targetValType.Elem()
if sourceVal.IsNil() {
return nil
}
// Accumulate errors
errors := make([]string, 0)
// If the input data is empty, then we just match what the input data is.
if sourceVal.Len() == 0 {
targetVal.Set(reflect.MakeMap(reflect.MapOf(targetValKeyType, targetValElemType)))
a.addMetaKey(targetKey)
return nil
}
if targetVal.IsNil() {
targetVal.Set(reflect.MakeMap(reflect.MapOf(targetValKeyType, targetValElemType)))
}
for _, srcKey := range sourceVal.MapKeys() {
kStr := fmt.Sprintf("%v", srcKey.Interface())
targetElem := reflect.Indirect(reflect.New(targetValElemType))
sourceElem := sourceVal.MapIndex(srcKey)
childTargetKey := targetKey.newChild(reflect.Map, kStr)
childSourceKey := sourceKey.newChild(reflect.Map, kStr)
if a.shouldSkipKey(childTargetKey, childSourceKey) {
continue
}
// First decode the key into the proper type
currentKey := reflect.Indirect(reflect.New(targetValKeyType))
if err := weakAssigner.assign(currentKey, "", srcKey, ""); err != nil {
errors = appendErrors(errors, err)
continue
}
// Next decode the data into the proper type
if err := a.assign(targetElem, childTargetKey, sourceElem, childSourceKey); err != nil {
errors = appendErrors(errors, err)
continue
}
targetVal.SetMapIndex(currentKey, targetElem)
}
// If we had errors, return those
if len(errors) > 0 {
return &Error{errors}
}
return nil
}
func (a *assigner) assignMapFromStruct(targetVal reflect.Value, targetKey metaKey, sourceVal reflect.Value, sourceKey metaKey) error {
targetMapType := targetVal.Type()
targetKeyType := targetMapType.Key()
targetElemType := targetMapType.Elem()
if targetVal.IsNil() {
targetVal.Set(reflect.MakeMap(reflect.MapOf(targetKeyType, targetElemType)))
}
sourceFields := a.flattenStruct(sourceVal)
for _, srcField := range sourceFields {
// Next get the actual value of this field and verify it is assignable
// to the map value.
if !srcField.fieldVal.Type().AssignableTo(targetVal.Type().Elem()) {
return fmt.Errorf("cannot assign type '%s' to map value field of type '%s'", srcField.fieldVal.Type(), targetVal.Type().Elem())
}
targetFieldKey := targetKey.newChild(reflect.Map, srcField.actualName)
sourceFieldKey := sourceKey.newChild(reflect.Struct, srcField.displayName)
if a.shouldSkipKey(targetFieldKey, sourceFieldKey) {
continue
}
keyVal := reflect.Indirect(reflect.New(targetKeyType))
if err := weakAssigner.assign(keyVal, "", srcField.ActualNameVal(), ""); err != nil {
return fmt.Errorf("error converting map key '%s': %w", srcField.actualName, err)
}
srcFieldKind := srcField.fieldVal.Kind()
if isStruct(srcFieldKind) { // this is an embedded struct, so handle it differently
sourceFieldType := srcField.fieldVal.Type()
// Check if struct can be directly assigned to map element
if sourceFieldType.AssignableTo(targetElemType) {
targetVal.SetMapIndex(keyVal, srcField.fieldVal)
a.addMetaKey(targetFieldKey)
continue
}
// Create a new map for nested struct
targetChild := map[string]any{}
targetChildVal := reflect.ValueOf(targetChild)
if !targetChildVal.Type().AssignableTo(targetElemType) {
a.addMetaUnused(sourceFieldKey)
continue
}
if err := a.assignMapFromStruct(targetChildVal, targetFieldKey, srcField.fieldVal, sourceFieldKey); err != nil {
return err
}
targetVal.SetMapIndex(keyVal, targetChildVal)
a.addMetaKey(targetFieldKey)
continue
}
if srcField.omitempty && isEmptyValue(srcField.fieldVal) {
a.addMetaUnused(sourceFieldKey)
continue
}
targetVal.SetMapIndex(keyVal, srcField.fieldVal)
a.addMetaKey(targetFieldKey)
}
return nil
}
func (a *assigner) assignPtr(targetVal reflect.Value, targetKey metaKey, sourceVal reflect.Value, sourceKey metaKey) (bool, error) {
// If the input data is nil, then we want to just set the output
// pointer to be nil as well.
if isPtrAble(sourceVal.Kind()) {
isNil := sourceVal.IsNil()
if !isNil {
switch v := reflect.Indirect(sourceVal); v.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
isNil = v.IsNil()
}
}
if isNil {
if !targetVal.IsNil() && targetVal.CanSet() {
nilValue := reflect.New(targetVal.Type()).Elem()
targetVal.Set(nilValue)
}
return true, nil
}
}
// Create an element of the concrete (non pointer) type and decode
// into that. Then set the value of the pointer to this type.
targetValType := targetVal.Type()
targetValElemType := targetValType.Elem()
if targetVal.CanSet() {
realVal := targetVal
if targetVal.IsNil() {
realVal = reflect.New(targetValElemType)
}
if err := a.assign(reflect.Indirect(realVal), targetKey, sourceVal, sourceKey); err != nil {
return false, err
}
targetVal.Set(realVal)
} else {
if err := a.assign(reflect.Indirect(targetVal), targetKey, sourceVal, sourceKey); err != nil {
return false, err
}
}
return false, nil
}
func (a *assigner) assignFunc(targetVal reflect.Value, targetKey metaKey, sourceVal reflect.Value, _ metaKey) error {
// Create an element of the concrete (non pointer) type and decode
// into that. Then set the value of the pointer to this type.
sourceVal = reflect.Indirect(sourceVal)
if targetVal.Type() != sourceVal.Type() {
return fmt.Errorf(
"'%s' expected type '%s', got unconvertible type '%s', value: '%v'",
targetKey.String(),
targetVal.Type(),
sourceVal.Type(),
sourceVal.Interface(),
)
}
targetVal.Set(sourceVal)
return nil
}
func (a *assigner) assignSlice(targetVal reflect.Value, targetKey metaKey, sourceVal reflect.Value, sourceKey metaKey) error {
sourceVal = reflect.Indirect(sourceVal)
sourceKind := sourceVal.Kind()
targetValType := targetVal.Type()
targetValElemType := targetValType.Elem()
sliceType := reflect.SliceOf(targetValElemType)
// If we have a non array/slice type then we first attempt to convert.
if !isArraySlice(sourceKind) {
if !a.config.WeaklyTypedInput {
return fmt.Errorf(
"'%s': source data must be an array or slice, got %s",
targetKey.String(),
sourceKind,
)
}
switch {
// Slice and array we use the normal logic
case sourceKind == reflect.Slice, sourceKind == reflect.Array:
break
// Empty maps turn into empty slices
case sourceKind == reflect.Map:
if sourceVal.Len() == 0 {
targetVal.Set(reflect.MakeSlice(sliceType, 0, 0))
a.addMetaKey(targetKey)
return nil
}
// Create slice of maps of other sizes
return a.assignSlice(targetVal, targetKey, a.wrapSlice(sourceVal), sourceKey)
case sourceKind == reflect.String && targetValElemType.Kind() == reflect.Uint8:
// Convert sourceVal from type string to type []byte
return a.assignSlice(targetVal, targetKey, reflect.ValueOf([]byte(sourceVal.String())), sourceKey)
// All other types we try to convert to the slice type
// and "lift" it into it. i.e. a string becomes a string slice.
default:
// Just re-try this function with data as a slice.
return a.assignSlice(targetVal, targetKey, a.wrapSlice(sourceVal), sourceKey)
}
}
// If the input value is nil, then don't allocate since empty != nil
if sourceKind != reflect.Array && sourceVal.IsNil() {
return nil
}
// Make a new slice to hold our result, same size as the original data.
targetValSlice := targetVal
if targetValSlice.IsNil() {
// Make a new slice to hold our result, same size as the original data.
targetValSlice = reflect.MakeSlice(sliceType, sourceVal.Len(), sourceVal.Len())
} else if targetValSlice.Len() > sourceVal.Len() {
targetValSlice = targetValSlice.Slice(0, sourceVal.Len())
}
// Accumulate any errors
errors := make([]string, 0)
for i := 0; i < sourceVal.Len(); i++ {
sourceElem := sourceVal.Index(i)
// Ensure target slice has enough capacity
for targetValSlice.Len() <= i {
targetValSlice = reflect.Append(targetValSlice, reflect.Zero(targetValElemType))
}
targetField := targetValSlice.Index(i)
k := strconv.Itoa(i)