convert.go 15 KB

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