clone.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. "log"
  36. "reflect"
  37. "strings"
  38. )
  39. // Clone returns a deep copy of a protocol buffer.
  40. func Clone(pb Message) Message {
  41. in := reflect.ValueOf(pb)
  42. if in.IsNil() {
  43. return pb
  44. }
  45. out := reflect.New(in.Type().Elem())
  46. // out is empty so a merge is a deep copy.
  47. mergeStruct(out.Elem(), in.Elem())
  48. return out.Interface().(Message)
  49. }
  50. // Merge merges src into dst.
  51. // Required and optional fields that are set in src will be set to that value in dst.
  52. // Elements of repeated fields will be appended.
  53. // Merge panics if src and dst are not the same type, or if dst is nil.
  54. func Merge(dst, src Message) {
  55. in := reflect.ValueOf(src)
  56. out := reflect.ValueOf(dst)
  57. if out.IsNil() {
  58. panic("proto: nil destination")
  59. }
  60. if in.Type() != out.Type() {
  61. // Explicit test prior to mergeStruct so that mistyped nils will fail
  62. panic("proto: type mismatch")
  63. }
  64. if in.IsNil() {
  65. // Merging nil into non-nil is a quiet no-op
  66. return
  67. }
  68. mergeStruct(out.Elem(), in.Elem())
  69. }
  70. func mergeStruct(out, in reflect.Value) {
  71. sprop := GetProperties(in.Type())
  72. for i := 0; i < in.NumField(); i++ {
  73. f := in.Type().Field(i)
  74. if strings.HasPrefix(f.Name, "XXX_") {
  75. continue
  76. }
  77. mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
  78. }
  79. if emIn, ok := in.Addr().Interface().(extensionsBytes); ok {
  80. emOut := out.Addr().Interface().(extensionsBytes)
  81. bIn := emIn.GetExtensions()
  82. bOut := emOut.GetExtensions()
  83. *bOut = append(*bOut, *bIn...)
  84. } else if emIn, ok := extendable(in.Addr().Interface()); ok {
  85. emOut, _ := extendable(out.Addr().Interface())
  86. mIn, muIn := emIn.extensionsRead()
  87. if mIn != nil {
  88. mOut := emOut.extensionsWrite()
  89. muIn.Lock()
  90. mergeExtension(mOut, mIn)
  91. muIn.Unlock()
  92. }
  93. }
  94. uf := in.FieldByName("XXX_unrecognized")
  95. if !uf.IsValid() {
  96. return
  97. }
  98. uin := uf.Bytes()
  99. if len(uin) > 0 {
  100. out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
  101. }
  102. }
  103. // mergeAny performs a merge between two values of the same type.
  104. // viaPtr indicates whether the values were indirected through a pointer (implying proto2).
  105. // prop is set if this is a struct field (it may be nil).
  106. func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
  107. if in.Type() == protoMessageType {
  108. if !in.IsNil() {
  109. if out.IsNil() {
  110. out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
  111. } else {
  112. Merge(out.Interface().(Message), in.Interface().(Message))
  113. }
  114. }
  115. return
  116. }
  117. switch in.Kind() {
  118. case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
  119. reflect.String, reflect.Uint32, reflect.Uint64:
  120. if !viaPtr && isProto3Zero(in) {
  121. return
  122. }
  123. out.Set(in)
  124. case reflect.Interface:
  125. // Probably a oneof field; copy non-nil values.
  126. if in.IsNil() {
  127. return
  128. }
  129. // Allocate destination if it is not set, or set to a different type.
  130. // Otherwise we will merge as normal.
  131. if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
  132. out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
  133. }
  134. mergeAny(out.Elem(), in.Elem(), false, nil)
  135. case reflect.Map:
  136. if in.Len() == 0 {
  137. return
  138. }
  139. if out.IsNil() {
  140. out.Set(reflect.MakeMap(in.Type()))
  141. }
  142. // For maps with value types of *T or []byte we need to deep copy each value.
  143. elemKind := in.Type().Elem().Kind()
  144. for _, key := range in.MapKeys() {
  145. var val reflect.Value
  146. switch elemKind {
  147. case reflect.Ptr:
  148. val = reflect.New(in.Type().Elem().Elem())
  149. mergeAny(val, in.MapIndex(key), false, nil)
  150. case reflect.Slice:
  151. val = in.MapIndex(key)
  152. val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
  153. default:
  154. val = in.MapIndex(key)
  155. }
  156. out.SetMapIndex(key, val)
  157. }
  158. case reflect.Ptr:
  159. if in.IsNil() {
  160. return
  161. }
  162. if out.IsNil() {
  163. out.Set(reflect.New(in.Elem().Type()))
  164. }
  165. mergeAny(out.Elem(), in.Elem(), true, nil)
  166. case reflect.Slice:
  167. if in.IsNil() {
  168. return
  169. }
  170. if in.Type().Elem().Kind() == reflect.Uint8 {
  171. // []byte is a scalar bytes field, not a repeated field.
  172. // Edge case: if this is in a proto3 message, a zero length
  173. // bytes field is considered the zero value, and should not
  174. // be merged.
  175. if prop != nil && prop.proto3 && in.Len() == 0 {
  176. return
  177. }
  178. // Make a deep copy.
  179. // Append to []byte{} instead of []byte(nil) so that we never end up
  180. // with a nil result.
  181. out.SetBytes(append([]byte{}, in.Bytes()...))
  182. return
  183. }
  184. n := in.Len()
  185. if out.IsNil() {
  186. out.Set(reflect.MakeSlice(in.Type(), 0, n))
  187. }
  188. switch in.Type().Elem().Kind() {
  189. case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
  190. reflect.String, reflect.Uint32, reflect.Uint64:
  191. out.Set(reflect.AppendSlice(out, in))
  192. default:
  193. for i := 0; i < n; i++ {
  194. x := reflect.Indirect(reflect.New(in.Type().Elem()))
  195. mergeAny(x, in.Index(i), false, nil)
  196. out.Set(reflect.Append(out, x))
  197. }
  198. }
  199. case reflect.Struct:
  200. mergeStruct(out, in)
  201. default:
  202. // unknown type, so not a protocol buffer
  203. log.Printf("proto: don't know how to copy %v", in)
  204. }
  205. }
  206. func mergeExtension(out, in map[int32]Extension) {
  207. for extNum, eIn := range in {
  208. eOut := Extension{desc: eIn.desc}
  209. if eIn.value != nil {
  210. v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
  211. mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
  212. eOut.value = v.Interface()
  213. }
  214. if eIn.enc != nil {
  215. eOut.enc = make([]byte, len(eIn.enc))
  216. copy(eOut.enc, eIn.enc)
  217. }
  218. out[extNum] = eOut
  219. }
  220. }