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