MCPcopy
hub / github.com/mitchellh/mapstructure / decodeMapFromStruct

Method decodeMapFromStruct

mapstructure.go:908–1016  ·  view source on GitHub ↗
(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value)

Source from the content-addressed store, hash-verified

906}
907
908func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error {
909 typ := dataVal.Type()
910 for i := 0; i < typ.NumField(); i++ {
911 // Get the StructField first since this is a cheap operation. If the
912 // field is unexported, then ignore it.
913 f := typ.Field(i)
914 if f.PkgPath != "" {
915 continue
916 }
917
918 // Next get the actual value of this field and verify it is assignable
919 // to the map value.
920 v := dataVal.Field(i)
921 if !v.Type().AssignableTo(valMap.Type().Elem()) {
922 return fmt.Errorf("cannot assign type '%s' to map value field of type '%s'", v.Type(), valMap.Type().Elem())
923 }
924
925 tagValue := f.Tag.Get(d.config.TagName)
926 keyName := f.Name
927
928 if tagValue == "" && d.config.IgnoreUntaggedFields {
929 continue
930 }
931
932 // If Squash is set in the config, we squash the field down.
933 squash := d.config.Squash && v.Kind() == reflect.Struct && f.Anonymous
934
935 v = dereferencePtrToStructIfNeeded(v, d.config.TagName)
936
937 // Determine the name of the key in the map
938 if index := strings.Index(tagValue, ","); index != -1 {
939 if tagValue[:index] == "-" {
940 continue
941 }
942 // If "omitempty" is specified in the tag, it ignores empty values.
943 if strings.Index(tagValue[index+1:], "omitempty") != -1 && isEmptyValue(v) {
944 continue
945 }
946
947 // If "squash" is specified in the tag, we squash the field down.
948 squash = squash || strings.Index(tagValue[index+1:], "squash") != -1
949 if squash {
950 // When squashing, the embedded type can be a pointer to a struct.
951 if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct {
952 v = v.Elem()
953 }
954
955 // The final type must be a struct
956 if v.Kind() != reflect.Struct {
957 return fmt.Errorf("cannot squash non-struct type '%s'", v.Type())
958 }
959 }
960 if keyNameTagValue := tagValue[:index]; keyNameTagValue != "" {
961 keyName = keyNameTagValue
962 }
963 } else if len(tagValue) > 0 {
964 if tagValue == "-" {
965 continue

Callers 2

decodeMapMethod · 0.95
decodeStructMethod · 0.95

Calls 3

decodeMethod · 0.95
isEmptyValueFunction · 0.85

Tested by

no test coverage detected