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

Method decodeBasic

mapstructure.go:509–563  ·  view source on GitHub ↗

This decodes a basic type (bool, int, string, etc.) and sets the value to "data" of that type.

(name string, data interface{}, val reflect.Value)

Source from the content-addressed store, hash-verified

507// This decodes a basic type (bool, int, string, etc.) and sets the
508// value to "data" of that type.
509func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error {
510 if val.IsValid() && val.Elem().IsValid() {
511 elem := val.Elem()
512
513 // If we can't address this element, then its not writable. Instead,
514 // we make a copy of the value (which is a pointer and therefore
515 // writable), decode into that, and replace the whole value.
516 copied := false
517 if !elem.CanAddr() {
518 copied = true
519
520 // Make *T
521 copy := reflect.New(elem.Type())
522
523 // *T = elem
524 copy.Elem().Set(elem)
525
526 // Set elem so we decode into it
527 elem = copy
528 }
529
530 // Decode. If we have an error then return. We also return right
531 // away if we're not a copy because that means we decoded directly.
532 if err := d.decode(name, data, elem); err != nil || !copied {
533 return err
534 }
535
536 // If we're a copy, we need to set te final result
537 val.Set(elem.Elem())
538 return nil
539 }
540
541 dataVal := reflect.ValueOf(data)
542
543 // If the input data is a pointer, and the assigned type is the dereference
544 // of that exact pointer, then indirect it so that we can assign it.
545 // Example: *string to string
546 if dataVal.Kind() == reflect.Ptr && dataVal.Type().Elem() == val.Type() {
547 dataVal = reflect.Indirect(dataVal)
548 }
549
550 if !dataVal.IsValid() {
551 dataVal = reflect.Zero(val.Type())
552 }
553
554 dataValType := dataVal.Type()
555 if !dataValType.AssignableTo(val.Type()) {
556 return fmt.Errorf(
557 "'%s' expected type '%s', got '%s'",
558 name, val.Type(), dataValType)
559 }
560
561 val.Set(dataVal)
562 return nil
563}
564
565func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error {
566 dataVal := reflect.Indirect(reflect.ValueOf(data))

Callers 1

decodeMethod · 0.95

Calls 1

decodeMethod · 0.95

Tested by

no test coverage detected