internal/value: extract Vector and Map logic as separate package
The implementation of reflect/protoreflect.NewGoExtension needs to be able to
provide a constructor for wrapping *[]T as a protoreflect.Vector.
However, it cannot depend on internal/impl since impl also depends on prototype.
Extract the common logic of Vector creation into a separate package that
has no dependencies on either impl or prototype.
Change-Id: I9295fde9b8861de11af085c91d9dfa56047d1b1e
Reviewed-on: https://go-review.googlesource.com/c/147446
Reviewed-by: Herbie Ong <herbie@google.com>
diff --git a/internal/value/convert.go b/internal/value/convert.go
new file mode 100644
index 0000000..2b91171
--- /dev/null
+++ b/internal/value/convert.go
@@ -0,0 +1,220 @@
+// 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 "github.com/golang/protobuf/v2/reflect/protoreflect"
+)
+
+// Unwrapper unwraps the value to the underlying value.
+// This is implemented by Vector and Map.
+type Unwrapper interface {
+ Unwrap() interface{}
+}
+
+// messageV1 is the protoV1.Message interface.
+type messageV1 = interface {
+ Reset()
+ String() string
+ ProtoMessage()
+}
+
+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.ProtoEnum)(nil)).Elem()
+ messageIfaceV1 = reflect.TypeOf((*messageV1)(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. NewConverter panics if it unable to provide a
+// conversion between the two. The Converter methods also panic when they are
+// called on incorrect Go types.
+//
+// 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 {
+ return NewLegacyConverter(t, k, nil)
+}
+
+// NewLegacyConverter is identical to NewConverter,
+// but supports wrapping legacy v1 messages to implement the v2 message API
+// using the provided wrapLegacyMessage function.
+// The wrapped message must implement Unwrapper.
+func NewLegacyConverter(t reflect.Type, k pref.Kind, wrapLegacyMessage func(reflect.Value) pref.Message) Converter {
+ switch k {
+ case pref.BoolKind:
+ if t.Kind() == reflect.Bool {
+ return makeScalarConverter(t, boolType)
+ }
+ case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
+ if t.Kind() == reflect.Int32 {
+ return makeScalarConverter(t, int32Type)
+ }
+ case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
+ if t.Kind() == reflect.Int64 {
+ return makeScalarConverter(t, int64Type)
+ }
+ case pref.Uint32Kind, pref.Fixed32Kind:
+ if t.Kind() == reflect.Uint32 {
+ return makeScalarConverter(t, uint32Type)
+ }
+ case pref.Uint64Kind, pref.Fixed64Kind:
+ if t.Kind() == reflect.Uint64 {
+ return makeScalarConverter(t, uint64Type)
+ }
+ case pref.FloatKind:
+ if t.Kind() == reflect.Float32 {
+ return makeScalarConverter(t, float32Type)
+ }
+ case pref.DoubleKind:
+ if t.Kind() == reflect.Float64 {
+ return makeScalarConverter(t, float64Type)
+ }
+ case pref.StringKind:
+ if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) {
+ return makeScalarConverter(t, stringType)
+ }
+ case pref.BytesKind:
+ if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) {
+ return makeScalarConverter(t, bytesType)
+ }
+ case pref.EnumKind:
+ // Handle v2 enums, which must satisfy the proto.Enum interface.
+ if t.Kind() != reflect.Ptr && t.Implements(enumIfaceV2) {
+ et := reflect.Zero(t).Interface().(pref.ProtoEnum).ProtoReflect().Type()
+ return Converter{
+ toPB: func(v reflect.Value) pref.Value {
+ if v.Type() != t {
+ panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
+ }
+ e := v.Interface().(pref.ProtoEnum)
+ return pref.ValueOf(e.ProtoReflect().Number())
+ },
+ toGo: func(v pref.Value) reflect.Value {
+ rv := reflect.ValueOf(et.GoNew(v.Enum()))
+ if rv.Type() != t {
+ panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
+ }
+ return rv
+ },
+ }
+ }
+
+ // Handle v1 enums, which we identify as simply a named int32 type.
+ if wrapLegacyMessage != nil && t.Kind() == reflect.Int32 && t.PkgPath() != "" {
+ return Converter{
+ toPB: 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()))
+ },
+ toGo: func(v pref.Value) reflect.Value {
+ return reflect.ValueOf(v.Enum()).Convert(t)
+ },
+ }
+ }
+ case pref.MessageKind, pref.GroupKind:
+ // Handle v2 messages, which must satisfy the proto.Message interface.
+ if t.Kind() == reflect.Ptr && t.Implements(messageIfaceV2) {
+ mt := reflect.Zero(t).Interface().(pref.ProtoMessage).ProtoReflect().Type()
+ return Converter{
+ toPB: 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())
+ },
+ toGo: func(v pref.Value) reflect.Value {
+ rv := reflect.ValueOf(v.Message())
+ if rv.Type() != t {
+ panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
+ }
+ return rv
+ },
+ newMessage: func() pref.Message {
+ return mt.GoNew().ProtoReflect()
+ },
+ }
+ }
+
+ // Handle v1 messages, which we need to wrap as a v2 message.
+ if wrapLegacyMessage != nil && t.Kind() == reflect.Ptr && t.Implements(messageIfaceV1) {
+ return Converter{
+ toPB: 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(wrapLegacyMessage(v))
+ },
+ toGo: func(v pref.Value) reflect.Value {
+ rv := reflect.ValueOf(v.Message().(Unwrapper).Unwrap())
+ if rv.Type() != t {
+ panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
+ }
+ return rv
+ },
+ newMessage: func() pref.Message {
+ return wrapLegacyMessage(reflect.New(t.Elem()))
+ },
+ }
+ }
+ }
+ panic(fmt.Sprintf("invalid Go type %v for protobuf kind %v", t, k))
+}
+
+func makeScalarConverter(goType, pbType reflect.Type) Converter {
+ return Converter{
+ toPB: 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())
+ },
+ toGo: 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 {
+ toPB func(reflect.Value) pref.Value
+ toGo func(pref.Value) reflect.Value
+ newMessage func() pref.Message
+}
+
+func (c Converter) PBValueOf(v reflect.Value) pref.Value { return c.toPB(v) }
+func (c Converter) GoValueOf(v pref.Value) reflect.Value { return c.toGo(v) }
+func (c Converter) NewMessage() pref.Message { return c.newMessage() }
diff --git a/internal/value/map.go b/internal/value/map.go
new file mode 100644
index 0000000..c1590d0
--- /dev/null
+++ b/internal/value/map.go
@@ -0,0 +1,87 @@
+// 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
+
+import (
+ "reflect"
+
+ pref "github.com/golang/protobuf/v2/reflect/protoreflect"
+)
+
+func MapOf(p interface{}, kc, kv Converter) pref.Map {
+ // TODO: Validate that p is a *map[K]V?
+ rv := reflect.ValueOf(p).Elem()
+ return mapReflect{rv, kc, kv}
+}
+
+type mapReflect struct {
+ v reflect.Value // addressable map[K]V
+ keyConv Converter
+ valConv Converter
+}
+
+func (ms mapReflect) Len() int {
+ return ms.v.Len()
+}
+func (ms mapReflect) Has(k pref.MapKey) bool {
+ rk := ms.keyConv.GoValueOf(k.Value())
+ rv := ms.v.MapIndex(rk)
+ return rv.IsValid()
+}
+func (ms mapReflect) Get(k pref.MapKey) pref.Value {
+ rk := ms.keyConv.GoValueOf(k.Value())
+ rv := ms.v.MapIndex(rk)
+ if !rv.IsValid() {
+ return pref.Value{}
+ }
+ return ms.valConv.PBValueOf(rv)
+}
+func (ms mapReflect) Set(k pref.MapKey, v pref.Value) {
+ if ms.v.IsNil() {
+ ms.v.Set(reflect.MakeMap(ms.v.Type()))
+ }
+ rk := ms.keyConv.GoValueOf(k.Value())
+ rv := ms.valConv.GoValueOf(v)
+ ms.v.SetMapIndex(rk, rv)
+}
+func (ms mapReflect) Clear(k pref.MapKey) {
+ rk := ms.keyConv.GoValueOf(k.Value())
+ ms.v.SetMapIndex(rk, reflect.Value{})
+}
+func (ms mapReflect) Mutable(k pref.MapKey) pref.Mutable {
+ // Mutable is only valid for messages and panics for other kinds.
+ if ms.v.IsNil() {
+ ms.v.Set(reflect.MakeMap(ms.v.Type()))
+ }
+ rk := ms.keyConv.GoValueOf(k.Value())
+ rv := ms.v.MapIndex(rk)
+ if !rv.IsValid() || rv.IsNil() {
+ // TODO: Is checking for nil proper behavior for custom messages?
+ pv := pref.ValueOf(ms.valConv.NewMessage())
+ rv = ms.valConv.GoValueOf(pv)
+ ms.v.SetMapIndex(rk, rv)
+ }
+ return rv.Interface().(pref.Message)
+}
+func (ms mapReflect) Range(f func(pref.MapKey, pref.Value) bool) {
+ for _, k := range ms.v.MapKeys() {
+ if v := ms.v.MapIndex(k); v.IsValid() {
+ pk := ms.keyConv.PBValueOf(k).MapKey()
+ pv := ms.valConv.PBValueOf(v)
+ if !f(pk, pv) {
+ return
+ }
+ }
+ }
+}
+func (ms mapReflect) Unwrap() interface{} {
+ return ms.v.Interface()
+}
+func (ms mapReflect) ProtoMutable() {}
+
+var (
+ _ pref.Map = mapReflect{}
+ _ Unwrapper = mapReflect{}
+)
diff --git a/internal/value/vector.go b/internal/value/vector.go
new file mode 100644
index 0000000..4c1a78d
--- /dev/null
+++ b/internal/value/vector.go
@@ -0,0 +1,63 @@
+// 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
+
+import (
+ "reflect"
+
+ pref "github.com/golang/protobuf/v2/reflect/protoreflect"
+)
+
+func VectorOf(p interface{}, c Converter) pref.Vector {
+ // TODO: Validate that p is a *[]T?
+ rv := reflect.ValueOf(p).Elem()
+ return vectorReflect{rv, c}
+}
+
+type vectorReflect struct {
+ v reflect.Value // addressable []T
+ conv Converter
+}
+
+func (vs vectorReflect) Len() int {
+ return vs.v.Len()
+}
+func (vs vectorReflect) Get(i int) pref.Value {
+ return vs.conv.PBValueOf(vs.v.Index(i))
+}
+func (vs vectorReflect) Set(i int, v pref.Value) {
+ vs.v.Index(i).Set(vs.conv.GoValueOf(v))
+}
+func (vs vectorReflect) Append(v pref.Value) {
+ vs.v.Set(reflect.Append(vs.v, vs.conv.GoValueOf(v)))
+}
+func (vs vectorReflect) Mutable(i int) pref.Mutable {
+ // Mutable is only valid for messages and panics for other kinds.
+ rv := vs.v.Index(i)
+ if rv.IsNil() {
+ // TODO: Is checking for nil proper behavior for custom messages?
+ pv := pref.ValueOf(vs.conv.NewMessage())
+ rv.Set(vs.conv.GoValueOf(pv))
+ }
+ return rv.Interface().(pref.Message)
+}
+func (vs vectorReflect) MutableAppend() pref.Mutable {
+ // MutableAppend is only valid for messages and panics for other kinds.
+ pv := pref.ValueOf(vs.conv.NewMessage())
+ vs.v.Set(reflect.Append(vs.v, vs.conv.GoValueOf(pv)))
+ return vs.v.Index(vs.Len() - 1).Interface().(pref.Message)
+}
+func (vs vectorReflect) Truncate(i int) {
+ vs.v.Set(vs.v.Slice(0, i))
+}
+func (vs vectorReflect) Unwrap() interface{} {
+ return vs.v.Interface()
+}
+func (vs vectorReflect) ProtoMutable() {}
+
+var (
+ _ pref.Vector = vectorReflect{}
+ _ Unwrapper = vectorReflect{}
+)