convert.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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 impl
  5. import (
  6. "fmt"
  7. "reflect"
  8. "google.golang.org/protobuf/reflect/protoreflect"
  9. )
  10. // unwrapper unwraps the value to the underlying value.
  11. // This is implemented by List and Map.
  12. type unwrapper interface {
  13. protoUnwrap() interface{}
  14. }
  15. // A Converter coverts to/from Go reflect.Value types and protobuf protoreflect.Value types.
  16. type Converter interface {
  17. // PBValueOf converts a reflect.Value to a protoreflect.Value.
  18. PBValueOf(reflect.Value) protoreflect.Value
  19. // GoValueOf converts a protoreflect.Value to a reflect.Value.
  20. GoValueOf(protoreflect.Value) reflect.Value
  21. // IsValidPB returns whether a protoreflect.Value is compatible with this type.
  22. IsValidPB(protoreflect.Value) bool
  23. // IsValidGo returns whether a reflect.Value is compatible with this type.
  24. IsValidGo(reflect.Value) bool
  25. // New returns a new field value.
  26. // For scalars, it returns the default value of the field.
  27. // For composite types, it returns a new mutable value.
  28. New() protoreflect.Value
  29. // Zero returns a new field value.
  30. // For scalars, it returns the default value of the field.
  31. // For composite types, it returns an immutable, empty value.
  32. Zero() protoreflect.Value
  33. }
  34. // NewConverter matches a Go type with a protobuf field and returns a Converter
  35. // that converts between the two. Enums must be a named int32 kind that
  36. // implements protoreflect.Enum, and messages must be pointer to a named
  37. // struct type that implements protoreflect.ProtoMessage.
  38. //
  39. // This matcher deliberately supports a wider range of Go types than what
  40. // protoc-gen-go historically generated to be able to automatically wrap some
  41. // v1 messages generated by other forks of protoc-gen-go.
  42. func NewConverter(t reflect.Type, fd protoreflect.FieldDescriptor) Converter {
  43. switch {
  44. case fd.IsList():
  45. return newListConverter(t, fd)
  46. case fd.IsMap():
  47. return newMapConverter(t, fd)
  48. default:
  49. return newSingularConverter(t, fd)
  50. }
  51. }
  52. var (
  53. boolType = reflect.TypeOf(bool(false))
  54. int32Type = reflect.TypeOf(int32(0))
  55. int64Type = reflect.TypeOf(int64(0))
  56. uint32Type = reflect.TypeOf(uint32(0))
  57. uint64Type = reflect.TypeOf(uint64(0))
  58. float32Type = reflect.TypeOf(float32(0))
  59. float64Type = reflect.TypeOf(float64(0))
  60. stringType = reflect.TypeOf(string(""))
  61. bytesType = reflect.TypeOf([]byte(nil))
  62. byteType = reflect.TypeOf(byte(0))
  63. )
  64. var (
  65. boolZero = protoreflect.ValueOfBool(false)
  66. int32Zero = protoreflect.ValueOfInt32(0)
  67. int64Zero = protoreflect.ValueOfInt64(0)
  68. uint32Zero = protoreflect.ValueOfUint32(0)
  69. uint64Zero = protoreflect.ValueOfUint64(0)
  70. float32Zero = protoreflect.ValueOfFloat32(0)
  71. float64Zero = protoreflect.ValueOfFloat64(0)
  72. stringZero = protoreflect.ValueOfString("")
  73. bytesZero = protoreflect.ValueOfBytes(nil)
  74. )
  75. func newSingularConverter(t reflect.Type, fd protoreflect.FieldDescriptor) Converter {
  76. defVal := func(fd protoreflect.FieldDescriptor, zero protoreflect.Value) protoreflect.Value {
  77. if fd.Cardinality() == protoreflect.Repeated {
  78. // Default isn't defined for repeated fields.
  79. return zero
  80. }
  81. return fd.Default()
  82. }
  83. switch fd.Kind() {
  84. case protoreflect.BoolKind:
  85. if t.Kind() == reflect.Bool {
  86. return &boolConverter{t, defVal(fd, boolZero)}
  87. }
  88. case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
  89. if t.Kind() == reflect.Int32 {
  90. return &int32Converter{t, defVal(fd, int32Zero)}
  91. }
  92. case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
  93. if t.Kind() == reflect.Int64 {
  94. return &int64Converter{t, defVal(fd, int64Zero)}
  95. }
  96. case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
  97. if t.Kind() == reflect.Uint32 {
  98. return &uint32Converter{t, defVal(fd, uint32Zero)}
  99. }
  100. case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
  101. if t.Kind() == reflect.Uint64 {
  102. return &uint64Converter{t, defVal(fd, uint64Zero)}
  103. }
  104. case protoreflect.FloatKind:
  105. if t.Kind() == reflect.Float32 {
  106. return &float32Converter{t, defVal(fd, float32Zero)}
  107. }
  108. case protoreflect.DoubleKind:
  109. if t.Kind() == reflect.Float64 {
  110. return &float64Converter{t, defVal(fd, float64Zero)}
  111. }
  112. case protoreflect.StringKind:
  113. if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) {
  114. return &stringConverter{t, defVal(fd, stringZero)}
  115. }
  116. case protoreflect.BytesKind:
  117. if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) {
  118. return &bytesConverter{t, defVal(fd, bytesZero)}
  119. }
  120. case protoreflect.EnumKind:
  121. // Handle enums, which must be a named int32 type.
  122. if t.Kind() == reflect.Int32 {
  123. return newEnumConverter(t, fd)
  124. }
  125. case protoreflect.MessageKind, protoreflect.GroupKind:
  126. return newMessageConverter(t)
  127. }
  128. panic(fmt.Sprintf("invalid Go type %v for field %v", t, fd.FullName()))
  129. }
  130. type boolConverter struct {
  131. goType reflect.Type
  132. def protoreflect.Value
  133. }
  134. func (c *boolConverter) PBValueOf(v reflect.Value) protoreflect.Value {
  135. if v.Type() != c.goType {
  136. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType))
  137. }
  138. return protoreflect.ValueOfBool(v.Bool())
  139. }
  140. func (c *boolConverter) GoValueOf(v protoreflect.Value) reflect.Value {
  141. return reflect.ValueOf(v.Bool()).Convert(c.goType)
  142. }
  143. func (c *boolConverter) IsValidPB(v protoreflect.Value) bool {
  144. _, ok := v.Interface().(bool)
  145. return ok
  146. }
  147. func (c *boolConverter) IsValidGo(v reflect.Value) bool {
  148. return v.IsValid() && v.Type() == c.goType
  149. }
  150. func (c *boolConverter) New() protoreflect.Value { return c.def }
  151. func (c *boolConverter) Zero() protoreflect.Value { return c.def }
  152. type int32Converter struct {
  153. goType reflect.Type
  154. def protoreflect.Value
  155. }
  156. func (c *int32Converter) PBValueOf(v reflect.Value) protoreflect.Value {
  157. if v.Type() != c.goType {
  158. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType))
  159. }
  160. return protoreflect.ValueOfInt32(int32(v.Int()))
  161. }
  162. func (c *int32Converter) GoValueOf(v protoreflect.Value) reflect.Value {
  163. return reflect.ValueOf(int32(v.Int())).Convert(c.goType)
  164. }
  165. func (c *int32Converter) IsValidPB(v protoreflect.Value) bool {
  166. _, ok := v.Interface().(int32)
  167. return ok
  168. }
  169. func (c *int32Converter) IsValidGo(v reflect.Value) bool {
  170. return v.IsValid() && v.Type() == c.goType
  171. }
  172. func (c *int32Converter) New() protoreflect.Value { return c.def }
  173. func (c *int32Converter) Zero() protoreflect.Value { return c.def }
  174. type int64Converter struct {
  175. goType reflect.Type
  176. def protoreflect.Value
  177. }
  178. func (c *int64Converter) PBValueOf(v reflect.Value) protoreflect.Value {
  179. if v.Type() != c.goType {
  180. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType))
  181. }
  182. return protoreflect.ValueOfInt64(int64(v.Int()))
  183. }
  184. func (c *int64Converter) GoValueOf(v protoreflect.Value) reflect.Value {
  185. return reflect.ValueOf(int64(v.Int())).Convert(c.goType)
  186. }
  187. func (c *int64Converter) IsValidPB(v protoreflect.Value) bool {
  188. _, ok := v.Interface().(int64)
  189. return ok
  190. }
  191. func (c *int64Converter) IsValidGo(v reflect.Value) bool {
  192. return v.IsValid() && v.Type() == c.goType
  193. }
  194. func (c *int64Converter) New() protoreflect.Value { return c.def }
  195. func (c *int64Converter) Zero() protoreflect.Value { return c.def }
  196. type uint32Converter struct {
  197. goType reflect.Type
  198. def protoreflect.Value
  199. }
  200. func (c *uint32Converter) PBValueOf(v reflect.Value) protoreflect.Value {
  201. if v.Type() != c.goType {
  202. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType))
  203. }
  204. return protoreflect.ValueOfUint32(uint32(v.Uint()))
  205. }
  206. func (c *uint32Converter) GoValueOf(v protoreflect.Value) reflect.Value {
  207. return reflect.ValueOf(uint32(v.Uint())).Convert(c.goType)
  208. }
  209. func (c *uint32Converter) IsValidPB(v protoreflect.Value) bool {
  210. _, ok := v.Interface().(uint32)
  211. return ok
  212. }
  213. func (c *uint32Converter) IsValidGo(v reflect.Value) bool {
  214. return v.IsValid() && v.Type() == c.goType
  215. }
  216. func (c *uint32Converter) New() protoreflect.Value { return c.def }
  217. func (c *uint32Converter) Zero() protoreflect.Value { return c.def }
  218. type uint64Converter struct {
  219. goType reflect.Type
  220. def protoreflect.Value
  221. }
  222. func (c *uint64Converter) PBValueOf(v reflect.Value) protoreflect.Value {
  223. if v.Type() != c.goType {
  224. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType))
  225. }
  226. return protoreflect.ValueOfUint64(uint64(v.Uint()))
  227. }
  228. func (c *uint64Converter) GoValueOf(v protoreflect.Value) reflect.Value {
  229. return reflect.ValueOf(uint64(v.Uint())).Convert(c.goType)
  230. }
  231. func (c *uint64Converter) IsValidPB(v protoreflect.Value) bool {
  232. _, ok := v.Interface().(uint64)
  233. return ok
  234. }
  235. func (c *uint64Converter) IsValidGo(v reflect.Value) bool {
  236. return v.IsValid() && v.Type() == c.goType
  237. }
  238. func (c *uint64Converter) New() protoreflect.Value { return c.def }
  239. func (c *uint64Converter) Zero() protoreflect.Value { return c.def }
  240. type float32Converter struct {
  241. goType reflect.Type
  242. def protoreflect.Value
  243. }
  244. func (c *float32Converter) PBValueOf(v reflect.Value) protoreflect.Value {
  245. if v.Type() != c.goType {
  246. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType))
  247. }
  248. return protoreflect.ValueOfFloat32(float32(v.Float()))
  249. }
  250. func (c *float32Converter) GoValueOf(v protoreflect.Value) reflect.Value {
  251. return reflect.ValueOf(float32(v.Float())).Convert(c.goType)
  252. }
  253. func (c *float32Converter) IsValidPB(v protoreflect.Value) bool {
  254. _, ok := v.Interface().(float32)
  255. return ok
  256. }
  257. func (c *float32Converter) IsValidGo(v reflect.Value) bool {
  258. return v.IsValid() && v.Type() == c.goType
  259. }
  260. func (c *float32Converter) New() protoreflect.Value { return c.def }
  261. func (c *float32Converter) Zero() protoreflect.Value { return c.def }
  262. type float64Converter struct {
  263. goType reflect.Type
  264. def protoreflect.Value
  265. }
  266. func (c *float64Converter) PBValueOf(v reflect.Value) protoreflect.Value {
  267. if v.Type() != c.goType {
  268. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType))
  269. }
  270. return protoreflect.ValueOfFloat64(float64(v.Float()))
  271. }
  272. func (c *float64Converter) GoValueOf(v protoreflect.Value) reflect.Value {
  273. return reflect.ValueOf(float64(v.Float())).Convert(c.goType)
  274. }
  275. func (c *float64Converter) IsValidPB(v protoreflect.Value) bool {
  276. _, ok := v.Interface().(float64)
  277. return ok
  278. }
  279. func (c *float64Converter) IsValidGo(v reflect.Value) bool {
  280. return v.IsValid() && v.Type() == c.goType
  281. }
  282. func (c *float64Converter) New() protoreflect.Value { return c.def }
  283. func (c *float64Converter) Zero() protoreflect.Value { return c.def }
  284. type stringConverter struct {
  285. goType reflect.Type
  286. def protoreflect.Value
  287. }
  288. func (c *stringConverter) PBValueOf(v reflect.Value) protoreflect.Value {
  289. if v.Type() != c.goType {
  290. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType))
  291. }
  292. return protoreflect.ValueOfString(v.Convert(stringType).String())
  293. }
  294. func (c *stringConverter) GoValueOf(v protoreflect.Value) reflect.Value {
  295. // pref.Value.String never panics, so we go through an interface
  296. // conversion here to check the type.
  297. s := v.Interface().(string)
  298. if c.goType.Kind() == reflect.Slice && s == "" {
  299. return reflect.Zero(c.goType) // ensure empty string is []byte(nil)
  300. }
  301. return reflect.ValueOf(s).Convert(c.goType)
  302. }
  303. func (c *stringConverter) IsValidPB(v protoreflect.Value) bool {
  304. _, ok := v.Interface().(string)
  305. return ok
  306. }
  307. func (c *stringConverter) IsValidGo(v reflect.Value) bool {
  308. return v.IsValid() && v.Type() == c.goType
  309. }
  310. func (c *stringConverter) New() protoreflect.Value { return c.def }
  311. func (c *stringConverter) Zero() protoreflect.Value { return c.def }
  312. type bytesConverter struct {
  313. goType reflect.Type
  314. def protoreflect.Value
  315. }
  316. func (c *bytesConverter) PBValueOf(v reflect.Value) protoreflect.Value {
  317. if v.Type() != c.goType {
  318. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType))
  319. }
  320. if c.goType.Kind() == reflect.String && v.Len() == 0 {
  321. return protoreflect.ValueOfBytes(nil) // ensure empty string is []byte(nil)
  322. }
  323. return protoreflect.ValueOfBytes(v.Convert(bytesType).Bytes())
  324. }
  325. func (c *bytesConverter) GoValueOf(v protoreflect.Value) reflect.Value {
  326. return reflect.ValueOf(v.Bytes()).Convert(c.goType)
  327. }
  328. func (c *bytesConverter) IsValidPB(v protoreflect.Value) bool {
  329. _, ok := v.Interface().([]byte)
  330. return ok
  331. }
  332. func (c *bytesConverter) IsValidGo(v reflect.Value) bool {
  333. return v.IsValid() && v.Type() == c.goType
  334. }
  335. func (c *bytesConverter) New() protoreflect.Value { return c.def }
  336. func (c *bytesConverter) Zero() protoreflect.Value { return c.def }
  337. type enumConverter struct {
  338. goType reflect.Type
  339. def protoreflect.Value
  340. }
  341. func newEnumConverter(goType reflect.Type, fd protoreflect.FieldDescriptor) Converter {
  342. var def protoreflect.Value
  343. if fd.Cardinality() == protoreflect.Repeated {
  344. def = protoreflect.ValueOfEnum(fd.Enum().Values().Get(0).Number())
  345. } else {
  346. def = fd.Default()
  347. }
  348. return &enumConverter{goType, def}
  349. }
  350. func (c *enumConverter) PBValueOf(v reflect.Value) protoreflect.Value {
  351. if v.Type() != c.goType {
  352. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType))
  353. }
  354. return protoreflect.ValueOfEnum(protoreflect.EnumNumber(v.Int()))
  355. }
  356. func (c *enumConverter) GoValueOf(v protoreflect.Value) reflect.Value {
  357. return reflect.ValueOf(v.Enum()).Convert(c.goType)
  358. }
  359. func (c *enumConverter) IsValidPB(v protoreflect.Value) bool {
  360. _, ok := v.Interface().(protoreflect.EnumNumber)
  361. return ok
  362. }
  363. func (c *enumConverter) IsValidGo(v reflect.Value) bool {
  364. return v.IsValid() && v.Type() == c.goType
  365. }
  366. func (c *enumConverter) New() protoreflect.Value {
  367. return c.def
  368. }
  369. func (c *enumConverter) Zero() protoreflect.Value {
  370. return c.def
  371. }
  372. type messageConverter struct {
  373. goType reflect.Type
  374. }
  375. func newMessageConverter(goType reflect.Type) Converter {
  376. return &messageConverter{goType}
  377. }
  378. func (c *messageConverter) PBValueOf(v reflect.Value) protoreflect.Value {
  379. if v.Type() != c.goType {
  380. panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType))
  381. }
  382. if c.isNonPointer() {
  383. if v.CanAddr() {
  384. v = v.Addr() // T => *T
  385. } else {
  386. v = reflect.Zero(reflect.PtrTo(v.Type()))
  387. }
  388. }
  389. if m, ok := v.Interface().(protoreflect.ProtoMessage); ok {
  390. return protoreflect.ValueOfMessage(m.ProtoReflect())
  391. }
  392. return protoreflect.ValueOfMessage(legacyWrapMessage(v))
  393. }
  394. func (c *messageConverter) GoValueOf(v protoreflect.Value) reflect.Value {
  395. m := v.Message()
  396. var rv reflect.Value
  397. if u, ok := m.(unwrapper); ok {
  398. rv = reflect.ValueOf(u.protoUnwrap())
  399. } else {
  400. rv = reflect.ValueOf(m.Interface())
  401. }
  402. if c.isNonPointer() {
  403. if rv.Type() != reflect.PtrTo(c.goType) {
  404. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), reflect.PtrTo(c.goType)))
  405. }
  406. if !rv.IsNil() {
  407. rv = rv.Elem() // *T => T
  408. } else {
  409. rv = reflect.Zero(rv.Type().Elem())
  410. }
  411. }
  412. if rv.Type() != c.goType {
  413. panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), c.goType))
  414. }
  415. return rv
  416. }
  417. func (c *messageConverter) IsValidPB(v protoreflect.Value) bool {
  418. m := v.Message()
  419. var rv reflect.Value
  420. if u, ok := m.(unwrapper); ok {
  421. rv = reflect.ValueOf(u.protoUnwrap())
  422. } else {
  423. rv = reflect.ValueOf(m.Interface())
  424. }
  425. if c.isNonPointer() {
  426. return rv.Type() == reflect.PtrTo(c.goType)
  427. }
  428. return rv.Type() == c.goType
  429. }
  430. func (c *messageConverter) IsValidGo(v reflect.Value) bool {
  431. return v.IsValid() && v.Type() == c.goType
  432. }
  433. func (c *messageConverter) New() protoreflect.Value {
  434. if c.isNonPointer() {
  435. return c.PBValueOf(reflect.New(c.goType).Elem())
  436. }
  437. return c.PBValueOf(reflect.New(c.goType.Elem()))
  438. }
  439. func (c *messageConverter) Zero() protoreflect.Value {
  440. return c.PBValueOf(reflect.Zero(c.goType))
  441. }
  442. // isNonPointer reports whether the type is a non-pointer type.
  443. // This never occurs for generated message types.
  444. func (c *messageConverter) isNonPointer() bool {
  445. return c.goType.Kind() != reflect.Ptr
  446. }