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.
43 // Clone returns a deep copy of a protocol buffer.
44 func Clone(pb Message) Message {
45 in := reflect.ValueOf(pb)
50 out := reflect.New(in.Type().Elem())
51 // out is empty so a merge is a deep copy.
52 mergeStruct(out.Elem(), in.Elem())
53 return out.Interface().(Message)
56 // Merge merges src into dst.
57 // Required and optional fields that are set in src will be set to that value in dst.
58 // Elements of repeated fields will be appended.
59 // Merge panics if src and dst are not the same type, or if dst is nil.
60 func Merge(dst, src Message) {
61 in := reflect.ValueOf(src)
62 out := reflect.ValueOf(dst)
64 panic("proto: nil destination")
66 if in.Type() != out.Type() {
67 // Explicit test prior to mergeStruct so that mistyped nils will fail
68 panic("proto: type mismatch")
71 // Merging nil into non-nil is a quiet no-op
74 mergeStruct(out.Elem(), in.Elem())
77 func mergeStruct(out, in reflect.Value) {
78 sprop := GetProperties(in.Type())
79 for i := 0; i < in.NumField(); i++ {
80 f := in.Type().Field(i)
81 if strings.HasPrefix(f.Name, "XXX_") {
84 mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
87 if emIn, ok := extendable(in.Addr().Interface()); ok {
88 emOut, _ := extendable(out.Addr().Interface())
89 mIn, muIn := emIn.extensionsRead()
91 mOut := emOut.extensionsWrite()
93 mergeExtension(mOut, mIn)
98 uf := in.FieldByName("XXX_unrecognized")
104 out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
108 // mergeAny performs a merge between two values of the same type.
109 // viaPtr indicates whether the values were indirected through a pointer (implying proto2).
110 // prop is set if this is a struct field (it may be nil).
111 func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
112 if in.Type() == protoMessageType {
115 out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
117 Merge(out.Interface().(Message), in.Interface().(Message))
123 case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
124 reflect.String, reflect.Uint32, reflect.Uint64:
125 if !viaPtr && isProto3Zero(in) {
129 case reflect.Interface:
130 // Probably a oneof field; copy non-nil values.
134 // Allocate destination if it is not set, or set to a different type.
135 // Otherwise we will merge as normal.
136 if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
137 out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
139 mergeAny(out.Elem(), in.Elem(), false, nil)
145 out.Set(reflect.MakeMap(in.Type()))
147 // For maps with value types of *T or []byte we need to deep copy each value.
148 elemKind := in.Type().Elem().Kind()
149 for _, key := range in.MapKeys() {
150 var val reflect.Value
153 val = reflect.New(in.Type().Elem().Elem())
154 mergeAny(val, in.MapIndex(key), false, nil)
156 val = in.MapIndex(key)
157 val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
159 val = in.MapIndex(key)
161 out.SetMapIndex(key, val)
168 out.Set(reflect.New(in.Elem().Type()))
170 mergeAny(out.Elem(), in.Elem(), true, nil)
175 if in.Type().Elem().Kind() == reflect.Uint8 {
176 // []byte is a scalar bytes field, not a repeated field.
178 // Edge case: if this is in a proto3 message, a zero length
179 // bytes field is considered the zero value, and should not
181 if prop != nil && prop.proto3 && in.Len() == 0 {
186 // Append to []byte{} instead of []byte(nil) so that we never end up
187 // with a nil result.
188 out.SetBytes(append([]byte{}, in.Bytes()...))
193 out.Set(reflect.MakeSlice(in.Type(), 0, n))
195 switch in.Type().Elem().Kind() {
196 case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
197 reflect.String, reflect.Uint32, reflect.Uint64:
198 out.Set(reflect.AppendSlice(out, in))
200 for i := 0; i < n; i++ {
201 x := reflect.Indirect(reflect.New(in.Type().Elem()))
202 mergeAny(x, in.Index(i), false, nil)
203 out.Set(reflect.Append(out, x))
209 // unknown type, so not a protocol buffer
210 log.Printf("proto: don't know how to copy %v", in)
214 func mergeExtension(out, in map[int32]Extension) {
215 for extNum, eIn := range in {
216 eOut := Extension{desc: eIn.desc}
217 if eIn.value != nil {
218 v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
219 mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
220 eOut.value = v.Interface()
223 eOut.enc = make([]byte, len(eIn.enc))
224 copy(eOut.enc, eIn.enc)