reflect.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // Copyright 2020 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 protocmp
  5. import (
  6. "reflect"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "google.golang.org/protobuf/internal/genid"
  11. "google.golang.org/protobuf/proto"
  12. "google.golang.org/protobuf/reflect/protoreflect"
  13. "google.golang.org/protobuf/runtime/protoiface"
  14. )
  15. func reflectValueOf(v interface{}) protoreflect.Value {
  16. switch v := v.(type) {
  17. case Enum:
  18. return protoreflect.ValueOfEnum(v.Number())
  19. case Message:
  20. return protoreflect.ValueOfMessage(v.ProtoReflect())
  21. case []byte:
  22. return protoreflect.ValueOfBytes(v) // avoid overlap with reflect.Slice check below
  23. default:
  24. switch rv := reflect.ValueOf(v); {
  25. case rv.Kind() == reflect.Slice:
  26. return protoreflect.ValueOfList(reflectList{rv})
  27. case rv.Kind() == reflect.Map:
  28. return protoreflect.ValueOfMap(reflectMap{rv})
  29. default:
  30. return protoreflect.ValueOf(v)
  31. }
  32. }
  33. }
  34. type reflectMessage Message
  35. func (m reflectMessage) stringKey(fd protoreflect.FieldDescriptor) string {
  36. if m.Descriptor() != fd.ContainingMessage() {
  37. panic("mismatching containing message")
  38. }
  39. return fd.TextName()
  40. }
  41. func (m reflectMessage) Descriptor() protoreflect.MessageDescriptor {
  42. return (Message)(m).Descriptor()
  43. }
  44. func (m reflectMessage) Type() protoreflect.MessageType {
  45. return reflectMessageType{m.Descriptor()}
  46. }
  47. func (m reflectMessage) New() protoreflect.Message {
  48. return m.Type().New()
  49. }
  50. func (m reflectMessage) Interface() protoreflect.ProtoMessage {
  51. return Message(m)
  52. }
  53. func (m reflectMessage) Range(f func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool) {
  54. // Range over populated known fields.
  55. fds := m.Descriptor().Fields()
  56. for i := 0; i < fds.Len(); i++ {
  57. fd := fds.Get(i)
  58. if m.Has(fd) && !f(fd, m.Get(fd)) {
  59. return
  60. }
  61. }
  62. // Range over populated extension fields.
  63. for _, xd := range m[messageTypeKey].(messageMeta).xds {
  64. if m.Has(xd) && !f(xd, m.Get(xd)) {
  65. return
  66. }
  67. }
  68. }
  69. func (m reflectMessage) Has(fd protoreflect.FieldDescriptor) bool {
  70. _, ok := m[m.stringKey(fd)]
  71. return ok
  72. }
  73. func (m reflectMessage) Clear(protoreflect.FieldDescriptor) {
  74. panic("invalid mutation of read-only message")
  75. }
  76. func (m reflectMessage) Get(fd protoreflect.FieldDescriptor) protoreflect.Value {
  77. v, ok := m[m.stringKey(fd)]
  78. if !ok {
  79. switch {
  80. case fd.IsList():
  81. return protoreflect.ValueOfList(reflectList{})
  82. case fd.IsMap():
  83. return protoreflect.ValueOfMap(reflectMap{})
  84. case fd.Message() != nil:
  85. return protoreflect.ValueOfMessage(reflectMessage{
  86. messageTypeKey: messageMeta{md: fd.Message()},
  87. })
  88. default:
  89. return fd.Default()
  90. }
  91. }
  92. // The transformation may leave Any messages in structured form.
  93. // If so, convert them back to a raw-encoded form.
  94. if fd.FullName() == genid.Any_Value_field_fullname {
  95. if m, ok := v.(Message); ok {
  96. b, err := proto.MarshalOptions{Deterministic: true}.Marshal(m)
  97. if err != nil {
  98. panic("BUG: " + err.Error())
  99. }
  100. return protoreflect.ValueOfBytes(b)
  101. }
  102. }
  103. return reflectValueOf(v)
  104. }
  105. func (m reflectMessage) Set(protoreflect.FieldDescriptor, protoreflect.Value) {
  106. panic("invalid mutation of read-only message")
  107. }
  108. func (m reflectMessage) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value {
  109. panic("invalid mutation of read-only message")
  110. }
  111. func (m reflectMessage) NewField(protoreflect.FieldDescriptor) protoreflect.Value {
  112. panic("not implemented")
  113. }
  114. func (m reflectMessage) WhichOneof(od protoreflect.OneofDescriptor) protoreflect.FieldDescriptor {
  115. if m.Descriptor().Oneofs().ByName(od.Name()) != od {
  116. panic("oneof descriptor does not belong to this message")
  117. }
  118. fds := od.Fields()
  119. for i := 0; i < fds.Len(); i++ {
  120. fd := fds.Get(i)
  121. if _, ok := m[m.stringKey(fd)]; ok {
  122. return fd
  123. }
  124. }
  125. return nil
  126. }
  127. func (m reflectMessage) GetUnknown() protoreflect.RawFields {
  128. var nums []protoreflect.FieldNumber
  129. for k := range m {
  130. if len(strings.Trim(k, "0123456789")) == 0 {
  131. n, _ := strconv.ParseUint(k, 10, 32)
  132. nums = append(nums, protoreflect.FieldNumber(n))
  133. }
  134. }
  135. sort.Slice(nums, func(i, j int) bool { return nums[i] < nums[j] })
  136. var raw protoreflect.RawFields
  137. for _, num := range nums {
  138. b, _ := m[strconv.FormatUint(uint64(num), 10)].(protoreflect.RawFields)
  139. raw = append(raw, b...)
  140. }
  141. return raw
  142. }
  143. func (m reflectMessage) SetUnknown(protoreflect.RawFields) {
  144. panic("invalid mutation of read-only message")
  145. }
  146. func (m reflectMessage) IsValid() bool {
  147. invalid, _ := m[messageInvalidKey].(bool)
  148. return !invalid
  149. }
  150. func (m reflectMessage) ProtoMethods() *protoiface.Methods {
  151. return nil
  152. }
  153. type reflectMessageType struct{ protoreflect.MessageDescriptor }
  154. func (t reflectMessageType) New() protoreflect.Message {
  155. panic("not implemented")
  156. }
  157. func (t reflectMessageType) Zero() protoreflect.Message {
  158. panic("not implemented")
  159. }
  160. func (t reflectMessageType) Descriptor() protoreflect.MessageDescriptor {
  161. return t.MessageDescriptor
  162. }
  163. type reflectList struct{ v reflect.Value }
  164. func (ls reflectList) Len() int {
  165. if !ls.IsValid() {
  166. return 0
  167. }
  168. return ls.v.Len()
  169. }
  170. func (ls reflectList) Get(i int) protoreflect.Value {
  171. return reflectValueOf(ls.v.Index(i).Interface())
  172. }
  173. func (ls reflectList) Set(int, protoreflect.Value) {
  174. panic("invalid mutation of read-only list")
  175. }
  176. func (ls reflectList) Append(protoreflect.Value) {
  177. panic("invalid mutation of read-only list")
  178. }
  179. func (ls reflectList) AppendMutable() protoreflect.Value {
  180. panic("invalid mutation of read-only list")
  181. }
  182. func (ls reflectList) Truncate(int) {
  183. panic("invalid mutation of read-only list")
  184. }
  185. func (ls reflectList) NewElement() protoreflect.Value {
  186. panic("not implemented")
  187. }
  188. func (ls reflectList) IsValid() bool {
  189. return ls.v.IsValid()
  190. }
  191. type reflectMap struct{ v reflect.Value }
  192. func (ms reflectMap) Len() int {
  193. if !ms.IsValid() {
  194. return 0
  195. }
  196. return ms.v.Len()
  197. }
  198. func (ms reflectMap) Range(f func(protoreflect.MapKey, protoreflect.Value) bool) {
  199. if !ms.IsValid() {
  200. return
  201. }
  202. ks := ms.v.MapKeys()
  203. for _, k := range ks {
  204. pk := reflectValueOf(k.Interface()).MapKey()
  205. pv := reflectValueOf(ms.v.MapIndex(k).Interface())
  206. if !f(pk, pv) {
  207. return
  208. }
  209. }
  210. }
  211. func (ms reflectMap) Has(k protoreflect.MapKey) bool {
  212. if !ms.IsValid() {
  213. return false
  214. }
  215. return ms.v.MapIndex(reflect.ValueOf(k.Interface())).IsValid()
  216. }
  217. func (ms reflectMap) Clear(protoreflect.MapKey) {
  218. panic("invalid mutation of read-only list")
  219. }
  220. func (ms reflectMap) Get(k protoreflect.MapKey) protoreflect.Value {
  221. if !ms.IsValid() {
  222. return protoreflect.Value{}
  223. }
  224. v := ms.v.MapIndex(reflect.ValueOf(k.Interface()))
  225. if !v.IsValid() {
  226. return protoreflect.Value{}
  227. }
  228. return reflectValueOf(v.Interface())
  229. }
  230. func (ms reflectMap) Set(protoreflect.MapKey, protoreflect.Value) {
  231. panic("invalid mutation of read-only list")
  232. }
  233. func (ms reflectMap) Mutable(k protoreflect.MapKey) protoreflect.Value {
  234. panic("invalid mutation of read-only list")
  235. }
  236. func (ms reflectMap) NewValue() protoreflect.Value {
  237. panic("not implemented")
  238. }
  239. func (ms reflectMap) IsValid() bool {
  240. return ms.v.IsValid()
  241. }