clone.go 6.1 KB

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