1 // Go support for Protocol Buffers - Google's data interchange format
3 // Copyright 2011 The Go Authors. All rights reserved.
4 // https://github.com/golang/protobuf
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are
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
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.
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.
32 // Protocol buffer deep copy and merge.
44 // Clone returns a deep copy of a protocol buffer.
45 func Clone(src Message) Message {
46 in := reflect.ValueOf(src)
50 out := reflect.New(in.Type().Elem())
51 dst := out.Interface().(Message)
56 // Merger is the interface representing objects that can merge messages of the same type.
57 type Merger interface {
58 // Merge merges src into this message.
59 // Required and optional fields that are set in src will be set to that value in dst.
60 // Elements of repeated fields will be appended.
62 // Merge may panic if called with a different argument type than the receiver.
66 // generatedMerger is the custom merge method that generated protos will have.
67 // We must add this method since a generate Merge method will conflict with
68 // many existing protos that have a Merge data field already defined.
69 type generatedMerger interface {
70 XXX_Merge(src Message)
73 // Merge merges src into dst.
74 // Required and optional fields that are set in src will be set to that value in dst.
75 // Elements of repeated fields will be appended.
76 // Merge panics if src and dst are not the same type, or if dst is nil.
77 func Merge(dst, src Message) {
78 if m, ok := dst.(Merger); ok {
83 in := reflect.ValueOf(src)
84 out := reflect.ValueOf(dst)
86 panic("proto: nil destination")
88 if in.Type() != out.Type() {
89 panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src))
92 return // Merge from nil src is a noop
94 if m, ok := dst.(generatedMerger); ok {
98 mergeStruct(out.Elem(), in.Elem())
101 func mergeStruct(out, in reflect.Value) {
102 sprop := GetProperties(in.Type())
103 for i := 0; i < in.NumField(); i++ {
104 f := in.Type().Field(i)
105 if strings.HasPrefix(f.Name, "XXX_") {
108 mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
111 if emIn, ok := in.Addr().Interface().(extensionsBytes); ok {
112 emOut := out.Addr().Interface().(extensionsBytes)
113 bIn := emIn.GetExtensions()
114 bOut := emOut.GetExtensions()
115 *bOut = append(*bOut, *bIn...)
116 } else if emIn, err := extendable(in.Addr().Interface()); err == nil {
117 emOut, _ := extendable(out.Addr().Interface())
118 mIn, muIn := emIn.extensionsRead()
120 mOut := emOut.extensionsWrite()
122 mergeExtension(mOut, mIn)
127 uf := in.FieldByName("XXX_unrecognized")
133 out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
137 // mergeAny performs a merge between two values of the same type.
138 // viaPtr indicates whether the values were indirected through a pointer (implying proto2).
139 // prop is set if this is a struct field (it may be nil).
140 func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
141 if in.Type() == protoMessageType {
144 out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
146 Merge(out.Interface().(Message), in.Interface().(Message))
152 case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
153 reflect.String, reflect.Uint32, reflect.Uint64:
154 if !viaPtr && isProto3Zero(in) {
158 case reflect.Interface:
159 // Probably a oneof field; copy non-nil values.
163 // Allocate destination if it is not set, or set to a different type.
164 // Otherwise we will merge as normal.
165 if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
166 out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
168 mergeAny(out.Elem(), in.Elem(), false, nil)
174 out.Set(reflect.MakeMap(in.Type()))
176 // For maps with value types of *T or []byte we need to deep copy each value.
177 elemKind := in.Type().Elem().Kind()
178 for _, key := range in.MapKeys() {
179 var val reflect.Value
182 val = reflect.New(in.Type().Elem().Elem())
183 mergeAny(val, in.MapIndex(key), false, nil)
185 val = in.MapIndex(key)
186 val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
188 val = in.MapIndex(key)
190 out.SetMapIndex(key, val)
197 out.Set(reflect.New(in.Elem().Type()))
199 mergeAny(out.Elem(), in.Elem(), true, nil)
204 if in.Type().Elem().Kind() == reflect.Uint8 {
205 // []byte is a scalar bytes field, not a repeated field.
207 // Edge case: if this is in a proto3 message, a zero length
208 // bytes field is considered the zero value, and should not
210 if prop != nil && prop.proto3 && in.Len() == 0 {
215 // Append to []byte{} instead of []byte(nil) so that we never end up
216 // with a nil result.
217 out.SetBytes(append([]byte{}, in.Bytes()...))
222 out.Set(reflect.MakeSlice(in.Type(), 0, n))
224 switch in.Type().Elem().Kind() {
225 case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
226 reflect.String, reflect.Uint32, reflect.Uint64:
227 out.Set(reflect.AppendSlice(out, in))
229 for i := 0; i < n; i++ {
230 x := reflect.Indirect(reflect.New(in.Type().Elem()))
231 mergeAny(x, in.Index(i), false, nil)
232 out.Set(reflect.Append(out, x))
238 // unknown type, so not a protocol buffer
239 log.Printf("proto: don't know how to copy %v", in)
243 func mergeExtension(out, in map[int32]Extension) {
244 for extNum, eIn := range in {
245 eOut := Extension{desc: eIn.desc}
246 if eIn.value != nil {
247 v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
248 mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
249 eOut.value = v.Interface()
252 eOut.enc = make([]byte, len(eIn.enc))
253 copy(eOut.enc, eIn.enc)