convert.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. )
  12. // Unwrapper unwraps the value to the underlying value.
  13. // This is implemented by List and Map.
  14. type Unwrapper interface {
  15. Unwrap() interface{}
  16. }
  17. // messageV1 is the protoV1.Message interface.
  18. type messageV1 = interface {
  19. Reset()
  20. String() string
  21. ProtoMessage()
  22. }
  23. var (
  24. boolType = reflect.TypeOf(bool(false))
  25. int32Type = reflect.TypeOf(int32(0))
  26. int64Type = reflect.TypeOf(int64(0))
  27. uint32Type = reflect.TypeOf(uint32(0))
  28. uint64Type = reflect.TypeOf(uint64(0))
  29. float32Type = reflect.TypeOf(float32(0))
  30. float64Type = reflect.TypeOf(float64(0))
  31. stringType = reflect.TypeOf(string(""))
  32. bytesType = reflect.TypeOf([]byte(nil))
  33. enumIfaceV2 = reflect.TypeOf((*pref.ProtoEnum)(nil)).Elem()
  34. messageIfaceV1 = reflect.TypeOf((*messageV1)(nil)).Elem()
  35. messageIfaceV2 = reflect.TypeOf((*pref.ProtoMessage)(nil)).Elem()
  36. byteType = reflect.TypeOf(byte(0))
  37. )
  38. // NewConverter matches a Go type with a protobuf kind and returns a Converter
  39. // that converts between the two. NewConverter panics if it unable to provide a
  40. // conversion between the two. The Converter methods also panic when they are
  41. // called on incorrect Go types.
  42. //
  43. // This matcher deliberately supports a wider range of Go types than what
  44. // protoc-gen-go historically generated to be able to automatically wrap some
  45. // v1 messages generated by other forks of protoc-gen-go.
  46. func NewConverter(t reflect.Type, k pref.Kind) Converter {
  47. return NewLegacyConverter(t, k, nil, nil, nil)
  48. }
  49. // Legacy enums and messages do not self-report their own protoreflect types.
  50. // Thus, the caller needs to provide functions for retrieving those when
  51. // a v1 enum or message is encountered.
  52. type (
  53. enumTypeOf = func(reflect.Type) pref.EnumType
  54. messageTypeOf = func(reflect.Type) pref.MessageType
  55. messageValueOf = func(reflect.Value) pref.ProtoMessage
  56. )
  57. // NewLegacyConverter is identical to NewConverter,
  58. // but supports wrapping legacy v1 messages to implement the v2 message API
  59. // using the provided enumTypeOf, messageTypeOf and messageValueOf functions.
  60. // The wrapped message must implement Unwrapper.
  61. func NewLegacyConverter(t reflect.Type, k pref.Kind, etOf enumTypeOf, mtOf messageTypeOf, mvOf messageValueOf) Converter {
  62. switch k {
  63. case pref.BoolKind:
  64. if t.Kind() == reflect.Bool {
  65. return makeScalarConverter(t, boolType)
  66. }
  67. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  68. if t.Kind() == reflect.Int32 {
  69. return makeScalarConverter(t, int32Type)
  70. }
  71. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  72. if t.Kind() == reflect.Int64 {
  73. return makeScalarConverter(t, int64Type)
  74. }
  75. case pref.Uint32Kind, pref.Fixed32Kind:
  76. if t.Kind() == reflect.Uint32 {
  77. return makeScalarConverter(t, uint32Type)
  78. }
  79. case pref.Uint64Kind, pref.Fixed64Kind:
  80. if t.Kind() == reflect.Uint64 {
  81. return makeScalarConverter(t, uint64Type)
  82. }
  83. case pref.FloatKind:
  84. if t.Kind() == reflect.Float32 {
  85. return makeScalarConverter(t, float32Type)
  86. }
  87. case pref.DoubleKind:
  88. if t.Kind() == reflect.Float64 {
  89. return makeScalarConverter(t, float64Type)
  90. }
  91. case pref.StringKind:
  92. if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) {
  93. return makeScalarConverter(t, stringType)
  94. }
  95. case pref.BytesKind:
  96. if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) {
  97. return makeScalarConverter(t, bytesType)
  98. }
  99. case pref.EnumKind:
  100. // Handle v2 enums, which must satisfy the proto.Enum interface.
  101. if t.Kind() != reflect.Ptr && t.Implements(enumIfaceV2) {
  102. et := reflect.Zero(t).Interface().(pref.ProtoEnum).ProtoReflect().Type()
  103. return Converter{
  104. PBValueOf: func(v reflect.Value) pref.Value {
  105. if v.Type() != t {
  106. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  107. }
  108. e := v.Interface().(pref.ProtoEnum)
  109. return pref.ValueOf(e.ProtoReflect().Number())
  110. },
  111. GoValueOf: func(v pref.Value) reflect.Value {
  112. rv := reflect.ValueOf(et.New(v.Enum()))
  113. if rv.Type() != t {
  114. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
  115. }
  116. return rv
  117. },
  118. EnumType: et,
  119. }
  120. }
  121. // Handle v1 enums, which we identify as simply a named int32 type.
  122. if etOf != nil && t.PkgPath() != "" && t.Kind() == reflect.Int32 {
  123. et := etOf(t)
  124. return Converter{
  125. PBValueOf: func(v reflect.Value) pref.Value {
  126. if v.Type() != t {
  127. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  128. }
  129. return pref.ValueOf(pref.EnumNumber(v.Int()))
  130. },
  131. GoValueOf: func(v pref.Value) reflect.Value {
  132. return reflect.ValueOf(v.Enum()).Convert(t)
  133. },
  134. EnumType: et,
  135. IsLegacy: true,
  136. }
  137. }
  138. case pref.MessageKind, pref.GroupKind:
  139. // Handle v2 messages, which must satisfy the proto.Message interface.
  140. if t.Kind() == reflect.Ptr && t.Implements(messageIfaceV2) {
  141. mt := reflect.Zero(t).Interface().(pref.ProtoMessage).ProtoReflect().Type()
  142. return Converter{
  143. PBValueOf: func(v reflect.Value) pref.Value {
  144. if v.Type() != t {
  145. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  146. }
  147. return pref.ValueOf(v.Interface())
  148. },
  149. GoValueOf: func(v pref.Value) reflect.Value {
  150. rv := reflect.ValueOf(v.Message())
  151. if rv.Type() != t {
  152. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
  153. }
  154. return rv
  155. },
  156. MessageType: mt,
  157. }
  158. }
  159. // Handle v1 messages, which we need to wrap as a v2 message.
  160. if mtOf != nil && t.Kind() == reflect.Ptr && t.Implements(messageIfaceV1) {
  161. mt := mtOf(t)
  162. return Converter{
  163. PBValueOf: func(v reflect.Value) pref.Value {
  164. if v.Type() != t {
  165. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), t))
  166. }
  167. return pref.ValueOf(mvOf(v).ProtoReflect())
  168. },
  169. GoValueOf: func(v pref.Value) reflect.Value {
  170. rv := reflect.ValueOf(v.Message().(Unwrapper).Unwrap())
  171. if rv.Type() != t {
  172. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), t))
  173. }
  174. return rv
  175. },
  176. MessageType: mt,
  177. IsLegacy: true,
  178. }
  179. }
  180. }
  181. panic(fmt.Sprintf("invalid Go type %v for protobuf kind %v", t, k))
  182. }
  183. func makeScalarConverter(goType, pbType reflect.Type) Converter {
  184. return Converter{
  185. PBValueOf: func(v reflect.Value) pref.Value {
  186. if v.Type() != goType {
  187. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), goType))
  188. }
  189. if goType.Kind() == reflect.String && pbType.Kind() == reflect.Slice && v.Len() == 0 {
  190. return pref.ValueOf([]byte(nil)) // ensure empty string is []byte(nil)
  191. }
  192. return pref.ValueOf(v.Convert(pbType).Interface())
  193. },
  194. GoValueOf: func(v pref.Value) reflect.Value {
  195. rv := reflect.ValueOf(v.Interface())
  196. if rv.Type() != pbType {
  197. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), pbType))
  198. }
  199. if pbType.Kind() == reflect.String && goType.Kind() == reflect.Slice && rv.Len() == 0 {
  200. return reflect.Zero(goType) // ensure empty string is []byte(nil)
  201. }
  202. return rv.Convert(goType)
  203. },
  204. }
  205. }
  206. // Converter provides functions for converting to/from Go reflect.Value types
  207. // and protobuf protoreflect.Value types.
  208. type Converter struct {
  209. PBValueOf func(reflect.Value) pref.Value
  210. GoValueOf func(pref.Value) reflect.Value
  211. EnumType pref.EnumType
  212. MessageType pref.MessageType
  213. IsLegacy bool
  214. }