clone.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // Copyright 2011 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. // Protocol buffer deep copy and merge.
  5. // TODO: RawMessage.
  6. package proto
  7. import (
  8. "fmt"
  9. "log"
  10. "reflect"
  11. "strings"
  12. "google.golang.org/protobuf/reflect/protoreflect"
  13. )
  14. // Clone returns a deep copy of a protocol buffer.
  15. func Clone(src Message) Message {
  16. in := reflect.ValueOf(src)
  17. if in.IsNil() {
  18. return src
  19. }
  20. out := reflect.New(in.Type().Elem())
  21. dst := out.Interface().(Message)
  22. Merge(dst, src)
  23. return dst
  24. }
  25. // Merger is the interface representing objects that can merge messages of the same type.
  26. type Merger interface {
  27. // Merge merges src into this message.
  28. // Required and optional fields that are set in src will be set to that value in dst.
  29. // Elements of repeated fields will be appended.
  30. //
  31. // Merge may panic if called with a different argument type than the receiver.
  32. Merge(src Message)
  33. }
  34. // generatedMerger is the custom merge method that generated protos will have.
  35. // We must add this method since a generate Merge method will conflict with
  36. // many existing protos that have a Merge data field already defined.
  37. type generatedMerger interface {
  38. XXX_Merge(src Message)
  39. }
  40. // Merge merges src into dst.
  41. // Required and optional fields that are set in src will be set to that value in dst.
  42. // Elements of repeated fields will be appended.
  43. // Merge panics if src and dst are not the same type, or if dst is nil.
  44. func Merge(dst, src Message) {
  45. if m, ok := dst.(Merger); ok {
  46. m.Merge(src)
  47. return
  48. }
  49. in := reflect.ValueOf(src)
  50. out := reflect.ValueOf(dst)
  51. if out.IsNil() {
  52. panic("proto: nil destination")
  53. }
  54. if in.Type() != out.Type() {
  55. panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src))
  56. }
  57. if in.IsNil() {
  58. return // Merge from nil src is a noop
  59. }
  60. if m, ok := dst.(generatedMerger); ok {
  61. m.XXX_Merge(src)
  62. return
  63. }
  64. mergeStruct(out.Elem(), in.Elem())
  65. }
  66. func mergeStruct(out, in reflect.Value) {
  67. sprop := GetProperties(in.Type())
  68. for i := 0; i < in.NumField(); i++ {
  69. f := in.Type().Field(i)
  70. if strings.HasPrefix(f.Name, "XXX_") || f.PkgPath != "" {
  71. continue
  72. }
  73. mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
  74. }
  75. if emIn, err := extendable(in.Addr().Interface()); err == nil {
  76. emOut, _ := extendable(out.Addr().Interface())
  77. if emIn != nil {
  78. mergeExtension(emOut, emIn)
  79. }
  80. }
  81. uf := unknownFieldsValue(in)
  82. if !uf.IsValid() {
  83. return
  84. }
  85. uin := uf.Bytes()
  86. if len(uin) > 0 {
  87. unknownFieldsValue(out).SetBytes(append([]byte(nil), uin...))
  88. }
  89. }
  90. // mergeAny performs a merge between two values of the same type.
  91. // viaPtr indicates whether the values were indirected through a pointer (implying proto2).
  92. // prop is set if this is a struct field (it may be nil).
  93. func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
  94. if in.Type() == protoMessageType {
  95. if !in.IsNil() {
  96. if out.IsNil() {
  97. out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
  98. } else {
  99. Merge(out.Interface().(Message), in.Interface().(Message))
  100. }
  101. }
  102. return
  103. }
  104. switch in.Kind() {
  105. case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
  106. reflect.String, reflect.Uint32, reflect.Uint64:
  107. if !viaPtr && isProto3Zero(in) {
  108. return
  109. }
  110. out.Set(in)
  111. case reflect.Interface:
  112. // Probably a oneof field; copy non-nil values.
  113. if in.IsNil() {
  114. return
  115. }
  116. // Allocate destination if it is not set, or set to a different type.
  117. // Otherwise we will merge as normal.
  118. if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
  119. out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
  120. }
  121. mergeAny(out.Elem(), in.Elem(), false, nil)
  122. case reflect.Map:
  123. if in.Len() == 0 {
  124. return
  125. }
  126. if out.IsNil() {
  127. out.Set(reflect.MakeMap(in.Type()))
  128. }
  129. // For maps with value types of *T or []byte we need to deep copy each value.
  130. elemKind := in.Type().Elem().Kind()
  131. for _, key := range in.MapKeys() {
  132. var val reflect.Value
  133. switch elemKind {
  134. case reflect.Ptr:
  135. val = reflect.New(in.Type().Elem().Elem())
  136. mergeAny(val, in.MapIndex(key), false, nil)
  137. case reflect.Slice:
  138. val = in.MapIndex(key)
  139. val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
  140. default:
  141. val = in.MapIndex(key)
  142. }
  143. out.SetMapIndex(key, val)
  144. }
  145. case reflect.Ptr:
  146. if in.IsNil() {
  147. return
  148. }
  149. if out.IsNil() {
  150. out.Set(reflect.New(in.Elem().Type()))
  151. }
  152. mergeAny(out.Elem(), in.Elem(), true, nil)
  153. case reflect.Slice:
  154. if in.IsNil() {
  155. return
  156. }
  157. if in.Type().Elem().Kind() == reflect.Uint8 {
  158. // []byte is a scalar bytes field, not a repeated field.
  159. // Edge case: if this is in a proto3 message, a zero length
  160. // bytes field is considered the zero value, and should not
  161. // be merged.
  162. if prop != nil && prop.Proto3 && in.Len() == 0 {
  163. return
  164. }
  165. // Make a deep copy.
  166. // Append to []byte{} instead of []byte(nil) so that we never end up
  167. // with a nil result.
  168. out.SetBytes(append([]byte{}, in.Bytes()...))
  169. return
  170. }
  171. n := in.Len()
  172. if out.IsNil() {
  173. out.Set(reflect.MakeSlice(in.Type(), 0, n))
  174. }
  175. switch in.Type().Elem().Kind() {
  176. case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
  177. reflect.String, reflect.Uint32, reflect.Uint64:
  178. out.Set(reflect.AppendSlice(out, in))
  179. default:
  180. for i := 0; i < n; i++ {
  181. x := reflect.Indirect(reflect.New(in.Type().Elem()))
  182. mergeAny(x, in.Index(i), false, nil)
  183. out.Set(reflect.Append(out, x))
  184. }
  185. }
  186. case reflect.Struct:
  187. mergeStruct(out, in)
  188. default:
  189. // unknown type, so not a protocol buffer
  190. log.Printf("proto: don't know how to copy %v", in)
  191. }
  192. }
  193. func mergeExtension(out, in *extensionMap) {
  194. in.Range(func(extNum protoreflect.FieldNumber, eIn Extension) bool {
  195. var eOut Extension
  196. eOut.SetType(eIn.GetType())
  197. if eIn.HasValue() {
  198. v := reflect.New(reflect.TypeOf(eIn.GetValue())).Elem()
  199. mergeAny(v, reflect.ValueOf(eIn.GetValue()), false, nil)
  200. eOut.SetEagerValue(v.Interface())
  201. }
  202. out.Set(extNum, eOut)
  203. return true
  204. })
  205. }