merge.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. // Copyright 2019 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 proto
  5. import (
  6. "fmt"
  7. "google.golang.org/protobuf/reflect/protoreflect"
  8. "google.golang.org/protobuf/runtime/protoiface"
  9. )
  10. // Merge merges src into dst, which must be a message with the same descriptor.
  11. //
  12. // Populated scalar fields in src are copied to dst, while populated
  13. // singular messages in src are merged into dst by recursively calling Merge.
  14. // The elements of every list field in src is appended to the corresponded
  15. // list fields in dst. The entries of every map field in src is copied into
  16. // the corresponding map field in dst, possibly replacing existing entries.
  17. // The unknown fields of src are appended to the unknown fields of dst.
  18. //
  19. // It is semantically equivalent to unmarshaling the encoded form of src
  20. // into dst with the [UnmarshalOptions.Merge] option specified.
  21. func Merge(dst, src Message) {
  22. // TODO: Should nil src be treated as semantically equivalent to a
  23. // untyped, read-only, empty message? What about a nil dst?
  24. dstMsg, srcMsg := dst.ProtoReflect(), src.ProtoReflect()
  25. if dstMsg.Descriptor() != srcMsg.Descriptor() {
  26. if got, want := dstMsg.Descriptor().FullName(), srcMsg.Descriptor().FullName(); got != want {
  27. panic(fmt.Sprintf("descriptor mismatch: %v != %v", got, want))
  28. }
  29. panic("descriptor mismatch")
  30. }
  31. mergeOptions{}.mergeMessage(dstMsg, srcMsg)
  32. }
  33. // Clone returns a deep copy of m.
  34. // If the top-level message is invalid, it returns an invalid message as well.
  35. func Clone(m Message) Message {
  36. // NOTE: Most usages of Clone assume the following properties:
  37. // t := reflect.TypeOf(m)
  38. // t == reflect.TypeOf(m.ProtoReflect().New().Interface())
  39. // t == reflect.TypeOf(m.ProtoReflect().Type().Zero().Interface())
  40. //
  41. // Embedding protobuf messages breaks this since the parent type will have
  42. // a forwarded ProtoReflect method, but the Interface method will return
  43. // the underlying embedded message type.
  44. if m == nil {
  45. return nil
  46. }
  47. src := m.ProtoReflect()
  48. if !src.IsValid() {
  49. return src.Type().Zero().Interface()
  50. }
  51. dst := src.New()
  52. mergeOptions{}.mergeMessage(dst, src)
  53. return dst.Interface()
  54. }
  55. // mergeOptions provides a namespace for merge functions, and can be
  56. // exported in the future if we add user-visible merge options.
  57. type mergeOptions struct{}
  58. func (o mergeOptions) mergeMessage(dst, src protoreflect.Message) {
  59. methods := protoMethods(dst)
  60. if methods != nil && methods.Merge != nil {
  61. in := protoiface.MergeInput{
  62. Destination: dst,
  63. Source: src,
  64. }
  65. out := methods.Merge(in)
  66. if out.Flags&protoiface.MergeComplete != 0 {
  67. return
  68. }
  69. }
  70. if !dst.IsValid() {
  71. panic(fmt.Sprintf("cannot merge into invalid %v message", dst.Descriptor().FullName()))
  72. }
  73. src.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
  74. switch {
  75. case fd.IsList():
  76. o.mergeList(dst.Mutable(fd).List(), v.List(), fd)
  77. case fd.IsMap():
  78. o.mergeMap(dst.Mutable(fd).Map(), v.Map(), fd.MapValue())
  79. case fd.Message() != nil:
  80. o.mergeMessage(dst.Mutable(fd).Message(), v.Message())
  81. case fd.Kind() == protoreflect.BytesKind:
  82. dst.Set(fd, o.cloneBytes(v))
  83. default:
  84. dst.Set(fd, v)
  85. }
  86. return true
  87. })
  88. if len(src.GetUnknown()) > 0 {
  89. dst.SetUnknown(append(dst.GetUnknown(), src.GetUnknown()...))
  90. }
  91. }
  92. func (o mergeOptions) mergeList(dst, src protoreflect.List, fd protoreflect.FieldDescriptor) {
  93. // Merge semantics appends to the end of the existing list.
  94. for i, n := 0, src.Len(); i < n; i++ {
  95. switch v := src.Get(i); {
  96. case fd.Message() != nil:
  97. dstv := dst.NewElement()
  98. o.mergeMessage(dstv.Message(), v.Message())
  99. dst.Append(dstv)
  100. case fd.Kind() == protoreflect.BytesKind:
  101. dst.Append(o.cloneBytes(v))
  102. default:
  103. dst.Append(v)
  104. }
  105. }
  106. }
  107. func (o mergeOptions) mergeMap(dst, src protoreflect.Map, fd protoreflect.FieldDescriptor) {
  108. // Merge semantics replaces, rather than merges into existing entries.
  109. src.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool {
  110. switch {
  111. case fd.Message() != nil:
  112. dstv := dst.NewValue()
  113. o.mergeMessage(dstv.Message(), v.Message())
  114. dst.Set(k, dstv)
  115. case fd.Kind() == protoreflect.BytesKind:
  116. dst.Set(k, o.cloneBytes(v))
  117. default:
  118. dst.Set(k, v)
  119. }
  120. return true
  121. })
  122. }
  123. func (o mergeOptions) cloneBytes(v protoreflect.Value) protoreflect.Value {
  124. return protoreflect.ValueOfBytes(append([]byte{}, v.Bytes()...))
  125. }