clone.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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: MessageSet and 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. for i := 0; i < in.NumField(); i++ {
  72. f := in.Type().Field(i)
  73. if strings.HasPrefix(f.Name, "XXX_") {
  74. continue
  75. }
  76. mergeAny(out.Field(i), in.Field(i))
  77. }
  78. if emIn, ok := in.Addr().Interface().(extendableProto); ok {
  79. emOut := out.Addr().Interface().(extendableProto)
  80. mergeExtension(emOut.ExtensionMap(), emIn.ExtensionMap())
  81. }
  82. uf := in.FieldByName("XXX_unrecognized")
  83. if !uf.IsValid() {
  84. return
  85. }
  86. uin := uf.Bytes()
  87. if len(uin) > 0 {
  88. out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
  89. }
  90. }
  91. func mergeAny(out, in reflect.Value) {
  92. if in.Type() == protoMessageType {
  93. if !in.IsNil() {
  94. if out.IsNil() {
  95. out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
  96. } else {
  97. Merge(out.Interface().(Message), in.Interface().(Message))
  98. }
  99. }
  100. return
  101. }
  102. switch in.Kind() {
  103. case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
  104. reflect.String, reflect.Uint32, reflect.Uint64:
  105. out.Set(in)
  106. case reflect.Map:
  107. if in.Len() == 0 {
  108. return
  109. }
  110. if out.IsNil() {
  111. out.Set(reflect.MakeMap(in.Type()))
  112. }
  113. // For maps with value types of *T or []byte we need to deep copy each value.
  114. elemKind := in.Type().Elem().Kind()
  115. for _, key := range in.MapKeys() {
  116. var val reflect.Value
  117. switch elemKind {
  118. case reflect.Ptr:
  119. val = reflect.New(in.Type().Elem().Elem())
  120. mergeAny(val, in.MapIndex(key))
  121. case reflect.Slice:
  122. val = in.MapIndex(key)
  123. val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
  124. default:
  125. val = in.MapIndex(key)
  126. }
  127. out.SetMapIndex(key, val)
  128. }
  129. case reflect.Ptr:
  130. if in.IsNil() {
  131. return
  132. }
  133. if out.IsNil() {
  134. out.Set(reflect.New(in.Elem().Type()))
  135. }
  136. mergeAny(out.Elem(), in.Elem())
  137. case reflect.Slice:
  138. if in.IsNil() {
  139. return
  140. }
  141. if in.Type().Elem().Kind() == reflect.Uint8 {
  142. // []byte is a scalar bytes field, not a repeated field.
  143. // Make a deep copy.
  144. // Append to []byte{} instead of []byte(nil) so that we never end up
  145. // with a nil result.
  146. out.SetBytes(append([]byte{}, in.Bytes()...))
  147. return
  148. }
  149. n := in.Len()
  150. if out.IsNil() {
  151. out.Set(reflect.MakeSlice(in.Type(), 0, n))
  152. }
  153. switch in.Type().Elem().Kind() {
  154. case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
  155. reflect.String, reflect.Uint32, reflect.Uint64:
  156. out.Set(reflect.AppendSlice(out, in))
  157. default:
  158. for i := 0; i < n; i++ {
  159. x := reflect.Indirect(reflect.New(in.Type().Elem()))
  160. mergeAny(x, in.Index(i))
  161. out.Set(reflect.Append(out, x))
  162. }
  163. }
  164. case reflect.Struct:
  165. mergeStruct(out, in)
  166. default:
  167. // unknown type, so not a protocol buffer
  168. log.Printf("proto: don't know how to copy %v", in)
  169. }
  170. }
  171. func mergeExtension(out, in map[int32]Extension) {
  172. for extNum, eIn := range in {
  173. eOut := Extension{desc: eIn.desc}
  174. if eIn.value != nil {
  175. v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
  176. mergeAny(v, reflect.ValueOf(eIn.value))
  177. eOut.value = v.Interface()
  178. }
  179. if eIn.enc != nil {
  180. eOut.enc = make([]byte, len(eIn.enc))
  181. copy(eOut.enc, eIn.enc)
  182. }
  183. out[extNum] = eOut
  184. }
  185. }