MCPcopy Create free account
hub / github.com/google/go-cloud / unstringifyMapKey

Function unstringifyMapKey

docstore/driver/codec.go:631–671  ·  view source on GitHub ↗

Given a map key encoded as a string, and the type of the map key, convert the key into the type. For example, if we are decoding the key "3" for a map[int]interface{}, then key is "3" and keyType is reflect.Int.

(key string, keyType reflect.Type)

Source from the content-addressed store, hash-verified

629// For example, if we are decoding the key "3" for a map[int]interface{}, then key is "3"
630// and keyType is reflect.Int.
631func unstringifyMapKey(key string, keyType reflect.Type) (reflect.Value, error) {
632 // This code is mostly from the middle of decodeState.object in encoding/json/decode.go.
633 // Except for literalStore, which I don't understand.
634 // TODO(jba): understand literalStore.
635 switch {
636 case keyType.Kind() == reflect.String:
637 return reflect.ValueOf(key).Convert(keyType), nil
638 case reflect.PtrTo(keyType).Implements(textUnmarshalerType):
639 tu := reflect.New(keyType)
640 if err := tu.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(key)); err != nil {
641 return reflect.Value{}, err
642 }
643 return tu.Elem(), nil
644 case keyType.Kind() == reflect.Interface && keyType.NumMethod() == 0:
645 // TODO: remove this case? encoding/json doesn't support it.
646 return reflect.ValueOf(key), nil
647 default:
648 switch keyType.Kind() {
649 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
650 n, err := strconv.ParseInt(key, 10, 64)
651 if err != nil {
652 return reflect.Value{}, err
653 }
654 if reflect.Zero(keyType).OverflowInt(n) {
655 return reflect.Value{}, overflowError(n, keyType)
656 }
657 return reflect.ValueOf(n).Convert(keyType), nil
658 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
659 n, err := strconv.ParseUint(key, 10, 64)
660 if err != nil {
661 return reflect.Value{}, err
662 }
663 if reflect.Zero(keyType).OverflowUint(n) {
664 return reflect.Value{}, overflowError(n, keyType)
665 }
666 return reflect.ValueOf(n).Convert(keyType), nil
667 default:
668 return reflect.Value{}, gcerr.Newf(gcerr.InvalidArgument, nil, "invalid key type %s", keyType)
669 }
670 }
671}
672
673func decodeStruct(v reflect.Value, d Decoder) error {
674 fs, err := fieldCache.Fields(v.Type())

Callers 1

decodeMapFunction · 0.85

Calls 3

NewfFunction · 0.92
overflowErrorFunction · 0.85
UnmarshalTextMethod · 0.45

Tested by

no test coverage detected