convert.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package value provides functionality for wrapping Go values to implement
  5. // protoreflect values.
  6. package value
  7. import (
  8. "fmt"
  9. "reflect"
  10. papi "github.com/golang/protobuf/protoapi"
  11. pref "github.com/golang/protobuf/v2/reflect/protoreflect"
  12. )
  13. // Unwrapper unwraps the value to the underlying value.
  14. // This is implemented by List and Map.
  15. type Unwrapper interface {
  16. ProtoUnwrap() interface{}
  17. }
  18. var (
  19. boolType = reflect.TypeOf(bool(false))
  20. int32Type = reflect.TypeOf(int32(0))
  21. int64Type = reflect.TypeOf(int64(0))
  22. uint32Type = reflect.TypeOf(uint32(0))
  23. uint64Type = reflect.TypeOf(uint64(0))
  24. float32Type = reflect.TypeOf(float32(0))
  25. float64Type = reflect.TypeOf(float64(0))
  26. stringType = reflect.TypeOf(string(""))
  27. bytesType = reflect.TypeOf([]byte(nil))
  28. enumIfaceV2 = reflect.TypeOf((*pref.Enum)(nil)).Elem()
  29. messageIfaceV1 = reflect.TypeOf((*papi.Message)(nil)).Elem()
  30. messageIfaceV2 = reflect.TypeOf((*pref.ProtoMessage)(nil)).Elem()
  31. byteType = reflect.TypeOf(byte(0))
  32. )
  33. // NewConverter matches a Go type with a protobuf kind and returns a Converter
  34. // that converts between the two. NewConverter panics if it unable to provide a
  35. // conversion between the two. The Converter methods also panic when they are
  36. // called on incorrect Go types.
  37. //
  38. // This matcher deliberately supports a wider range of Go types than what
  39. // protoc-gen-go historically generated to be able to automatically wrap some
  40. // v1 messages generated by other forks of protoc-gen-go.
  41. func NewConverter(t reflect.Type, k pref.Kind) Converter {
  42. return NewLegacyConverter(t, k, nil)
  43. }
  44. // LegacyWrapper is a set of wrapper methods that wraps legacy v1 Go types
  45. // to implement the v2 reflection APIs.
  46. type (
  47. LegacyWrapper interface {
  48. EnumOf(interface{}) LegacyEnum
  49. EnumTypeOf(interface{}) pref.EnumType
  50. MessageOf(interface{}) LegacyMessage
  51. MessageTypeOf(interface{}) pref.MessageType
  52. ExtensionTypeOf(pref.ExtensionDescriptor, interface{}) pref.ExtensionType
  53. // TODO: Remove these eventually. See the TODOs in protoapi.
  54. ExtensionDescFromType(pref.ExtensionType) *papi.ExtensionDesc
  55. ExtensionTypeFromDesc(*papi.ExtensionDesc) pref.ExtensionType
  56. }
  57. LegacyEnum = interface {
  58. pref.Enum
  59. ProtoUnwrap() interface{}
  60. }
  61. LegacyMessage = interface {
  62. pref.Message
  63. ProtoUnwrap() interface{}
  64. }
  65. )
  66. // NewLegacyConverter is identical to NewConverter,
  67. // but supports wrapping legacy v1 messages to implement the v2 message API
  68. // using the provided LegacyWrapper.
  69. func NewLegacyConverter(t reflect.Type, k pref.Kind, w LegacyWrapper) Converter {
  70. switch k {
  71. case pref.BoolKind:
  72. if t.Kind() == reflect.Bool {
  73. return makeScalarConverter(t, boolType)
  74. }
  75. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  76. if t.Kind() == reflect.Int32 {
  77. return makeScalarConverter(t, int32Type)
  78. }
  79. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  80. if t.Kind() == reflect.Int64 {
  81. return makeScalarConverter(t, int64Type)
  82. }
  83. case pref.Uint32Kind, pref.Fixed32Kind:
  84. if t.Kind() == reflect.Uint32 {
  85. return makeScalarConverter(t, uint32Type)
  86. }
  87. case pref.Uint64Kind, pref.Fixed64Kind:
  88. if t.Kind() == reflect.Uint64 {
  89. return makeScalarConverter(t, uint64Type)
  90. }
  91. case pref.FloatKind:
  92. if t.Kind() == reflect.Float32 {
  93. return makeScalarConverter(t, float32Type)
  94. }
  95. case pref.DoubleKind:
  96. if t.Kind() == reflect.Float64 {
  97. return makeScalarConverter(t, float64Type)
  98. }
  99. case pref.StringKind:
  100. if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) {
  101. return makeScalarConverter(t, stringType)
  102. }
  103. case pref.BytesKind:
  104. if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) {
  105. return makeScalarConverter(t, bytesType)
  106. }
  107. case pref.EnumKind:
  108. // Handle v2 enums, which must satisfy the proto.Enum interface.
  109. if t.Kind() != reflect.Ptr && t.Implements(enumIfaceV2) {
  110. et := reflect.Zero(t).Interface().(pref.Enum).Type()
  111. return Converter{
  112. PBValueOf: func(v reflect.Value) pref.Value {
  113. if v.Type() != t {
  114. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  115. }
  116. e := v.Interface().(pref.Enum)
  117. return pref.ValueOf(e.Number())
  118. },
  119. GoValueOf: func(v pref.Value) reflect.Value {
  120. rv := reflect.ValueOf(et.New(v.Enum()))
  121. if rv.Type() != t {
  122. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
  123. }
  124. return rv
  125. },
  126. EnumType: et,
  127. }
  128. }
  129. // Handle v1 enums, which we identify as simply a named int32 type.
  130. if w != nil && t.PkgPath() != "" && t.Kind() == reflect.Int32 {
  131. et := w.EnumTypeOf(reflect.Zero(t).Interface())
  132. return Converter{
  133. PBValueOf: func(v reflect.Value) pref.Value {
  134. if v.Type() != t {
  135. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  136. }
  137. return pref.ValueOf(pref.EnumNumber(v.Int()))
  138. },
  139. GoValueOf: func(v pref.Value) reflect.Value {
  140. return reflect.ValueOf(v.Enum()).Convert(t)
  141. },
  142. EnumType: et,
  143. IsLegacy: true,
  144. }
  145. }
  146. case pref.MessageKind, pref.GroupKind:
  147. // Handle v2 messages, which must satisfy the proto.Message interface.
  148. if t.Kind() == reflect.Ptr && t.Implements(messageIfaceV2) {
  149. mt := reflect.Zero(t).Interface().(pref.ProtoMessage).ProtoReflect().Type()
  150. return Converter{
  151. PBValueOf: func(v reflect.Value) pref.Value {
  152. if v.Type() != t {
  153. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  154. }
  155. return pref.ValueOf(v.Interface().(pref.ProtoMessage).ProtoReflect())
  156. },
  157. GoValueOf: func(v pref.Value) reflect.Value {
  158. rv := reflect.ValueOf(v.Message().Interface())
  159. if rv.Type() != t {
  160. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
  161. }
  162. return rv
  163. },
  164. MessageType: mt,
  165. }
  166. }
  167. // Handle v1 messages, which we need to wrap as a v2 message.
  168. if w != nil && t.Kind() == reflect.Ptr && t.Implements(messageIfaceV1) {
  169. mt := w.MessageTypeOf(reflect.Zero(t).Interface())
  170. return Converter{
  171. PBValueOf: func(v reflect.Value) pref.Value {
  172. if v.Type() != t {
  173. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  174. }
  175. return pref.ValueOf(w.MessageOf(v.Interface()))
  176. },
  177. GoValueOf: func(v pref.Value) reflect.Value {
  178. rv := reflect.ValueOf(v.Message().(Unwrapper).ProtoUnwrap())
  179. if rv.Type() != t {
  180. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
  181. }
  182. return rv
  183. },
  184. MessageType: mt,
  185. IsLegacy: true,
  186. }
  187. }
  188. }
  189. panic(fmt.Sprintf("invalid Go type %v for protobuf kind %v", t, k))
  190. }
  191. func makeScalarConverter(goType, pbType reflect.Type) Converter {
  192. return Converter{
  193. PBValueOf: func(v reflect.Value) pref.Value {
  194. if v.Type() != goType {
  195. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), goType))
  196. }
  197. if goType.Kind() == reflect.String && pbType.Kind() == reflect.Slice && v.Len() == 0 {
  198. return pref.ValueOf([]byte(nil)) // ensure empty string is []byte(nil)
  199. }
  200. return pref.ValueOf(v.Convert(pbType).Interface())
  201. },
  202. GoValueOf: func(v pref.Value) reflect.Value {
  203. rv := reflect.ValueOf(v.Interface())
  204. if rv.Type() != pbType {
  205. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), pbType))
  206. }
  207. if pbType.Kind() == reflect.String && goType.Kind() == reflect.Slice && rv.Len() == 0 {
  208. return reflect.Zero(goType) // ensure empty string is []byte(nil)
  209. }
  210. return rv.Convert(goType)
  211. },
  212. }
  213. }
  214. // Converter provides functions for converting to/from Go reflect.Value types
  215. // and protobuf protoreflect.Value types.
  216. type Converter struct {
  217. PBValueOf func(reflect.Value) pref.Value
  218. GoValueOf func(pref.Value) reflect.Value
  219. EnumType pref.EnumType
  220. MessageType pref.MessageType
  221. IsLegacy bool
  222. }