161 lines
5.3 KiB
Go
Raw Normal View History

// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package value provides functionality for wrapping Go values to implement
// protoreflect values.
package value
import (
"fmt"
"reflect"
pref "google.golang.org/protobuf/reflect/protoreflect"
)
// Unwrapper unwraps the value to the underlying value.
all: rename Vector as List The terminology Vector does not occur in protobuf documentation at all, so we should rename the Go use of the term to something more recognizable. As such, all instances that match the regexp "[Vv]ect(or)?" were replaced. The C++ documentation uses the term "Repeated", which is a reasonable name. However, the term became overloaded in 2014, when maps were added as a feature and implementated under the hood as repeated fields. This is confusing as it means "repeated" could either refer to repeated fields proper (i.e., explicitly marked with the "repeated" label in the proto file) or map fields. In the case of the C++ reflective API, this is not a problem since repeated fields proper and map fields are interacted with through the same RepeatedField type. In Go, we do not use a single type to handle both types of repeated fields: 1) We are coming up with the Go protobuf reflection API for the first time and so do not need to piggy-back on the repeated fields API to remain backwards compatible since no former usages of Go protobuf reflection exists. 2) Map fields are commonly represented in Go as the Go map type, which do not preserve ordering information. As such it is fundamentally impossible to present an unordered map as a consistently ordered list. Thus, Go needs two different interfaces for lists and maps. Given the above situation, "Repeated" is not a great term to use since it refers to two different things (when we only want one of the meanings). To distinguish between the two, we'll use the terms "List" and "Map" instead. There is some precedence for the term "List" in the protobuf codebase (e.g., "getRepeatedInt32List"). Change-Id: Iddcdb6b78e1e60c14fa4ca213c15f45e214b967b Reviewed-on: https://go-review.googlesource.com/c/149657 Reviewed-by: Damien Neil <dneil@google.com>
2018-11-14 14:05:19 -08:00
// This is implemented by List and Map.
type Unwrapper interface {
ProtoUnwrap() interface{}
}
var (
boolType = reflect.TypeOf(bool(false))
int32Type = reflect.TypeOf(int32(0))
int64Type = reflect.TypeOf(int64(0))
uint32Type = reflect.TypeOf(uint32(0))
uint64Type = reflect.TypeOf(uint64(0))
float32Type = reflect.TypeOf(float32(0))
float64Type = reflect.TypeOf(float64(0))
stringType = reflect.TypeOf(string(""))
bytesType = reflect.TypeOf([]byte(nil))
enumIfaceV2 = reflect.TypeOf((*pref.Enum)(nil)).Elem()
messageIfaceV2 = reflect.TypeOf((*pref.ProtoMessage)(nil)).Elem()
byteType = reflect.TypeOf(byte(0))
)
// NewConverter matches a Go type with a protobuf kind and returns a Converter
// that converts between the two. Enums must be a named int32 kind that
// implements protoreflect.Enum, and messages must be pointer to a named
// struct type that implements protoreflect.ProtoMessage.
//
// This matcher deliberately supports a wider range of Go types than what
// protoc-gen-go historically generated to be able to automatically wrap some
// v1 messages generated by other forks of protoc-gen-go.
func NewConverter(t reflect.Type, k pref.Kind) Converter {
switch k {
case pref.BoolKind:
if t.Kind() == reflect.Bool {
return newScalarConverter(t, boolType)
}
case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
if t.Kind() == reflect.Int32 {
return newScalarConverter(t, int32Type)
}
case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
if t.Kind() == reflect.Int64 {
return newScalarConverter(t, int64Type)
}
case pref.Uint32Kind, pref.Fixed32Kind:
if t.Kind() == reflect.Uint32 {
return newScalarConverter(t, uint32Type)
}
case pref.Uint64Kind, pref.Fixed64Kind:
if t.Kind() == reflect.Uint64 {
return newScalarConverter(t, uint64Type)
}
case pref.FloatKind:
if t.Kind() == reflect.Float32 {
return newScalarConverter(t, float32Type)
}
case pref.DoubleKind:
if t.Kind() == reflect.Float64 {
return newScalarConverter(t, float64Type)
}
case pref.StringKind:
if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) {
return newScalarConverter(t, stringType)
}
case pref.BytesKind:
if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) {
return newScalarConverter(t, bytesType)
}
case pref.EnumKind:
// Handle enums, which must be a named int32 type.
if t.Implements(enumIfaceV2) && t.Kind() == reflect.Int32 {
return Converter{
PBValueOf: func(v reflect.Value) pref.Value {
if v.Type() != t {
panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
}
return pref.ValueOf(pref.EnumNumber(v.Int()))
},
GoValueOf: func(v pref.Value) reflect.Value {
return reflect.ValueOf(v.Enum()).Convert(t)
},
NewEnum: func(n pref.EnumNumber) pref.Enum {
return reflect.ValueOf(n).Convert(t).Interface().(pref.Enum)
},
}
}
case pref.MessageKind, pref.GroupKind:
// Handle v2 messages, which must satisfy the proto.Message interface.
if t.Implements(messageIfaceV2) && t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct {
return Converter{
PBValueOf: func(v reflect.Value) pref.Value {
if v.Type() != t {
panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
}
return pref.ValueOf(v.Interface().(pref.ProtoMessage).ProtoReflect())
},
GoValueOf: func(v pref.Value) reflect.Value {
rv := reflect.ValueOf(v.Message().Interface())
if rv.Type() != t {
panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
}
return rv
},
NewMessage: func() pref.Message {
return reflect.New(t.Elem()).Interface().(pref.ProtoMessage).ProtoReflect()
},
}
}
}
panic(fmt.Sprintf("invalid Go type %v for protobuf kind %v", t, k))
}
func newScalarConverter(goType, pbType reflect.Type) Converter {
return Converter{
PBValueOf: func(v reflect.Value) pref.Value {
if v.Type() != goType {
panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), goType))
}
if goType.Kind() == reflect.String && pbType.Kind() == reflect.Slice && v.Len() == 0 {
return pref.ValueOf([]byte(nil)) // ensure empty string is []byte(nil)
}
return pref.ValueOf(v.Convert(pbType).Interface())
},
GoValueOf: func(v pref.Value) reflect.Value {
rv := reflect.ValueOf(v.Interface())
if rv.Type() != pbType {
panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), pbType))
}
if pbType.Kind() == reflect.String && goType.Kind() == reflect.Slice && rv.Len() == 0 {
return reflect.Zero(goType) // ensure empty string is []byte(nil)
}
return rv.Convert(goType)
},
}
}
// Converter provides functions for converting to/from Go reflect.Value types
// and protobuf protoreflect.Value types.
type Converter struct {
PBValueOf func(reflect.Value) pref.Value
GoValueOf func(pref.Value) reflect.Value
NewEnum func(pref.EnumNumber) pref.Enum
NewMessage func() pref.Message
}