clone.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // Go support for Protocol Buffers - Google's data interchange format
  2. //
  3. // Copyright 2011 The Go Authors. All rights reserved.
  4. // https://github.com/golang/protobuf
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. // Protocol buffer deep copy and merge.
  32. // TODO: RawMessage.
  33. package proto
  34. import (
  35. "fmt"
  36. "log"
  37. "reflect"
  38. "strings"
  39. )
  40. // Clone returns a deep copy of a protocol buffer.
  41. func Clone(src Message) Message {
  42. in := reflect.ValueOf(src)
  43. if in.IsNil() {
  44. return src
  45. }
  46. out := reflect.New(in.Type().Elem())
  47. dst := out.Interface().(Message)
  48. Merge(dst, src)
  49. return dst
  50. }
  51. // Merger is the interface representing objects that can merge messages of the same type.
  52. type Merger interface {
  53. // Merge merges src into this message.
  54. // Required and optional fields that are set in src will be set to that value in dst.
  55. // Elements of repeated fields will be appended.
  56. //
  57. // Merge may panic if called with a different argument type than the receiver.
  58. Merge(src Message)
  59. }
  60. // generatedMerger is the custom merge method that generated protos will have.
  61. // We must add this method since a generate Merge method will conflict with
  62. // many existing protos that have a Merge data field already defined.
  63. type generatedMerger interface {
  64. XXX_Merge(src Message)
  65. }
  66. // Merge merges src into dst.
  67. // Required and optional fields that are set in src will be set to that value in dst.
  68. // Elements of repeated fields will be appended.
  69. // Merge panics if src and dst are not the same type, or if dst is nil.
  70. func Merge(dst, src Message) {
  71. if m, ok := dst.(Merger); ok {
  72. m.Merge(src)
  73. return
  74. }
  75. in := reflect.ValueOf(src)
  76. out := reflect.ValueOf(dst)
  77. if out.IsNil() {
  78. panic("proto: nil destination")
  79. }
  80. if in.Type() != out.Type() {
  81. panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src))
  82. }
  83. if in.IsNil() {
  84. return // Merge from nil src is a noop
  85. }
  86. if m, ok := dst.(generatedMerger); ok {
  87. m.XXX_Merge(src)
  88. return
  89. }
  90. mergeStruct(out.Elem(), in.Elem())
  91. }
  92. func mergeStruct(out, in reflect.Value) {
  93. sprop := GetProperties(in.Type())
  94. for i := 0; i < in.NumField(); i++ {
  95. f := in.Type().Field(i)
  96. if strings.HasPrefix(f.Name, "XXX_") {
  97. continue
  98. }
  99. mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
  100. }
  101. if emIn, ok := in.Addr().Interface().(extensionsBytes); ok {
  102. emOut := out.Addr().Interface().(extensionsBytes)
  103. bIn := emIn.GetExtensions()
  104. bOut := emOut.GetExtensions()
  105. *bOut = append(*bOut, *bIn...)
  106. } else if emIn, err := extendable(in.Addr().Interface()); err == nil {
  107. emOut, _ := extendable(out.Addr().Interface())
  108. mIn, muIn := emIn.extensionsRead()
  109. if mIn != nil {
  110. mOut := emOut.extensionsWrite()
  111. muIn.Lock()
  112. mergeExtension(mOut, mIn)
  113. muIn.Unlock()
  114. }
  115. }
  116. uf := in.FieldByName("XXX_unrecognized")
  117. if !uf.IsValid() {
  118. return
  119. }
  120. uin := uf.Bytes()
  121. if len(uin) > 0 {
  122. out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
  123. }
  124. }
  125. // mergeAny performs a merge between two values of the same type.
  126. // viaPtr indicates whether the values were indirected through a pointer (implying proto2).
  127. // prop is set if this is a struct field (it may be nil).
  128. func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
  129. if in.Type() == protoMessageType {
  130. if !in.IsNil() {
  131. if out.IsNil() {
  132. out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
  133. } else {
  134. Merge(out.Interface().(Message), in.Interface().(Message))
  135. }
  136. }
  137. return
  138. }
  139. switch in.Kind() {
  140. case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
  141. reflect.String, reflect.Uint32, reflect.Uint64:
  142. if !viaPtr && isProto3Zero(in) {
  143. return
  144. }
  145. out.Set(in)
  146. case reflect.Interface:
  147. // Probably a oneof field; copy non-nil values.
  148. if in.IsNil() {
  149. return
  150. }
  151. // Allocate destination if it is not set, or set to a different type.
  152. // Otherwise we will merge as normal.
  153. if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
  154. out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
  155. }
  156. mergeAny(out.Elem(), in.Elem(), false, nil)
  157. case reflect.Map:
  158. if in.Len() == 0 {
  159. return
  160. }
  161. if out.IsNil() {
  162. out.Set(reflect.MakeMap(in.Type()))
  163. }
  164. // For maps with value types of *T or []byte we need to deep copy each value.
  165. elemKind := in.Type().Elem().Kind()
  166. for _, key := range in.MapKeys() {
  167. var val reflect.Value
  168. switch elemKind {
  169. case reflect.Ptr:
  170. val = reflect.New(in.Type().Elem().Elem())
  171. mergeAny(val, in.MapIndex(key), false, nil)
  172. case reflect.Slice:
  173. val = in.MapIndex(key)
  174. val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
  175. default:
  176. val = in.MapIndex(key)
  177. }
  178. out.SetMapIndex(key, val)
  179. }
  180. case reflect.Ptr:
  181. if in.IsNil() {
  182. return
  183. }
  184. if out.IsNil() {
  185. out.Set(reflect.New(in.Elem().Type()))
  186. }
  187. mergeAny(out.Elem(), in.Elem(), true, nil)
  188. case reflect.Slice:
  189. if in.IsNil() {
  190. return
  191. }
  192. if in.Type().Elem().Kind() == reflect.Uint8 {
  193. // []byte is a scalar bytes field, not a repeated field.
  194. // Edge case: if this is in a proto3 message, a zero length
  195. // bytes field is considered the zero value, and should not
  196. // be merged.
  197. if prop != nil && prop.proto3 && in.Len() == 0 {
  198. return
  199. }
  200. // Make a deep copy.
  201. // Append to []byte{} instead of []byte(nil) so that we never end up
  202. // with a nil result.
  203. out.SetBytes(append([]byte{}, in.Bytes()...))
  204. return
  205. }
  206. n := in.Len()
  207. if out.IsNil() {
  208. out.Set(reflect.MakeSlice(in.Type(), 0, n))
  209. }
  210. switch in.Type().Elem().Kind() {
  211. case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
  212. reflect.String, reflect.Uint32, reflect.Uint64:
  213. out.Set(reflect.AppendSlice(out, in))
  214. default:
  215. for i := 0; i < n; i++ {
  216. x := reflect.Indirect(reflect.New(in.Type().Elem()))
  217. mergeAny(x, in.Index(i), false, nil)
  218. out.Set(reflect.Append(out, x))
  219. }
  220. }
  221. case reflect.Struct:
  222. mergeStruct(out, in)
  223. default:
  224. // unknown type, so not a protocol buffer
  225. log.Printf("proto: don't know how to copy %v", in)
  226. }
  227. }
  228. func mergeExtension(out, in map[int32]Extension) {
  229. for extNum, eIn := range in {
  230. eOut := Extension{desc: eIn.desc}
  231. if eIn.value != nil {
  232. v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
  233. mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
  234. eOut.value = v.Interface()
  235. }
  236. if eIn.enc != nil {
  237. eOut.enc = make([]byte, len(eIn.enc))
  238. copy(eOut.enc, eIn.enc)
  239. }
  240. out[extNum] = eOut
  241. }
  242. }