convert.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. pref "github.com/golang/protobuf/v2/reflect/protoreflect"
  11. piface "github.com/golang/protobuf/v2/runtime/protoiface"
  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((*piface.MessageV1)(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.
  54. // See the TODOs in internal/impl/legacy_extension.go.
  55. ExtensionDescFromType(pref.ExtensionType) *piface.ExtensionDescV1
  56. ExtensionTypeFromDesc(*piface.ExtensionDescV1) pref.ExtensionType
  57. }
  58. LegacyEnum = interface {
  59. pref.Enum
  60. ProtoUnwrap() interface{}
  61. }
  62. LegacyMessage = interface {
  63. pref.Message
  64. ProtoUnwrap() interface{}
  65. }
  66. )
  67. // NewLegacyConverter is identical to NewConverter,
  68. // but supports wrapping legacy v1 messages to implement the v2 message API
  69. // using the provided LegacyWrapper.
  70. func NewLegacyConverter(t reflect.Type, k pref.Kind, w LegacyWrapper) Converter {
  71. switch k {
  72. case pref.BoolKind:
  73. if t.Kind() == reflect.Bool {
  74. return makeScalarConverter(t, boolType)
  75. }
  76. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  77. if t.Kind() == reflect.Int32 {
  78. return makeScalarConverter(t, int32Type)
  79. }
  80. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  81. if t.Kind() == reflect.Int64 {
  82. return makeScalarConverter(t, int64Type)
  83. }
  84. case pref.Uint32Kind, pref.Fixed32Kind:
  85. if t.Kind() == reflect.Uint32 {
  86. return makeScalarConverter(t, uint32Type)
  87. }
  88. case pref.Uint64Kind, pref.Fixed64Kind:
  89. if t.Kind() == reflect.Uint64 {
  90. return makeScalarConverter(t, uint64Type)
  91. }
  92. case pref.FloatKind:
  93. if t.Kind() == reflect.Float32 {
  94. return makeScalarConverter(t, float32Type)
  95. }
  96. case pref.DoubleKind:
  97. if t.Kind() == reflect.Float64 {
  98. return makeScalarConverter(t, float64Type)
  99. }
  100. case pref.StringKind:
  101. if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) {
  102. return makeScalarConverter(t, stringType)
  103. }
  104. case pref.BytesKind:
  105. if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) {
  106. return makeScalarConverter(t, bytesType)
  107. }
  108. case pref.EnumKind:
  109. // Handle v2 enums, which must satisfy the proto.Enum interface.
  110. if t.Kind() != reflect.Ptr && t.Implements(enumIfaceV2) {
  111. et := reflect.Zero(t).Interface().(pref.Enum).Type()
  112. return Converter{
  113. PBValueOf: func(v reflect.Value) pref.Value {
  114. if v.Type() != t {
  115. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  116. }
  117. e := v.Interface().(pref.Enum)
  118. return pref.ValueOf(e.Number())
  119. },
  120. GoValueOf: func(v pref.Value) reflect.Value {
  121. rv := reflect.ValueOf(et.New(v.Enum()))
  122. if rv.Type() != t {
  123. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
  124. }
  125. return rv
  126. },
  127. EnumType: et,
  128. }
  129. }
  130. // Handle v1 enums, which we identify as simply a named int32 type.
  131. if w != nil && t.PkgPath() != "" && t.Kind() == reflect.Int32 {
  132. et := w.EnumTypeOf(reflect.Zero(t).Interface())
  133. return Converter{
  134. PBValueOf: func(v reflect.Value) pref.Value {
  135. if v.Type() != t {
  136. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  137. }
  138. return pref.ValueOf(pref.EnumNumber(v.Int()))
  139. },
  140. GoValueOf: func(v pref.Value) reflect.Value {
  141. return reflect.ValueOf(v.Enum()).Convert(t)
  142. },
  143. EnumType: et,
  144. IsLegacy: true,
  145. }
  146. }
  147. case pref.MessageKind, pref.GroupKind:
  148. // Handle v2 messages, which must satisfy the proto.Message interface.
  149. if t.Kind() == reflect.Ptr && t.Implements(messageIfaceV2) {
  150. mt := reflect.Zero(t).Interface().(pref.ProtoMessage).ProtoReflect().Type()
  151. return Converter{
  152. PBValueOf: func(v reflect.Value) pref.Value {
  153. if v.Type() != t {
  154. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  155. }
  156. return pref.ValueOf(v.Interface().(pref.ProtoMessage).ProtoReflect())
  157. },
  158. GoValueOf: func(v pref.Value) reflect.Value {
  159. rv := reflect.ValueOf(v.Message().Interface())
  160. if rv.Type() != t {
  161. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
  162. }
  163. return rv
  164. },
  165. MessageType: mt,
  166. }
  167. }
  168. // Handle v1 messages, which we need to wrap as a v2 message.
  169. if w != nil && t.Kind() == reflect.Ptr && t.Implements(messageIfaceV1) {
  170. mt := w.MessageTypeOf(reflect.Zero(t).Interface())
  171. return Converter{
  172. PBValueOf: func(v reflect.Value) pref.Value {
  173. if v.Type() != t {
  174. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  175. }
  176. return pref.ValueOf(w.MessageOf(v.Interface()))
  177. },
  178. GoValueOf: func(v pref.Value) reflect.Value {
  179. rv := reflect.ValueOf(v.Message().(Unwrapper).ProtoUnwrap())
  180. if rv.Type() != t {
  181. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
  182. }
  183. return rv
  184. },
  185. MessageType: mt,
  186. IsLegacy: true,
  187. }
  188. }
  189. }
  190. panic(fmt.Sprintf("invalid Go type %v for protobuf kind %v", t, k))
  191. }
  192. func makeScalarConverter(goType, pbType reflect.Type) Converter {
  193. return Converter{
  194. PBValueOf: func(v reflect.Value) pref.Value {
  195. if v.Type() != goType {
  196. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), goType))
  197. }
  198. if goType.Kind() == reflect.String && pbType.Kind() == reflect.Slice && v.Len() == 0 {
  199. return pref.ValueOf([]byte(nil)) // ensure empty string is []byte(nil)
  200. }
  201. return pref.ValueOf(v.Convert(pbType).Interface())
  202. },
  203. GoValueOf: func(v pref.Value) reflect.Value {
  204. rv := reflect.ValueOf(v.Interface())
  205. if rv.Type() != pbType {
  206. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), pbType))
  207. }
  208. if pbType.Kind() == reflect.String && goType.Kind() == reflect.Slice && rv.Len() == 0 {
  209. return reflect.Zero(goType) // ensure empty string is []byte(nil)
  210. }
  211. return rv.Convert(goType)
  212. },
  213. }
  214. }
  215. // Converter provides functions for converting to/from Go reflect.Value types
  216. // and protobuf protoreflect.Value types.
  217. type Converter struct {
  218. PBValueOf func(reflect.Value) pref.Value
  219. GoValueOf func(pref.Value) reflect.Value
  220. EnumType pref.EnumType
  221. MessageType pref.MessageType
  222. IsLegacy bool
  223. }