1// Copyright 2019 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package proto
6
7import (
8 "fmt"
9
10 "google.golang.org/protobuf/reflect/protoreflect"
11 "google.golang.org/protobuf/runtime/protoiface"
12)
13
14// Merge merges src into dst, which must be a message with the same descriptor.
15//
16// Populated scalar fields in src are copied to dst, while populated
17// singular messages in src are merged into dst by recursively calling Merge.
18// The elements of every list field in src is appended to the corresponded
19// list fields in dst. The entries of every map field in src is copied into
20// the corresponding map field in dst, possibly replacing existing entries.
21// The unknown fields of src are appended to the unknown fields of dst.
22//
23// It is semantically equivalent to unmarshaling the encoded form of src
24// into dst with the [UnmarshalOptions.Merge] option specified.
25func Merge(dst, src Message) {
26 // TODO: Should nil src be treated as semantically equivalent to a
27 // untyped, read-only, empty message? What about a nil dst?
28
29 dstMsg, srcMsg := dst.ProtoReflect(), src.ProtoReflect()
30 if dstMsg.Descriptor() != srcMsg.Descriptor() {
31 if got, want := dstMsg.Descriptor().FullName(), srcMsg.Descriptor().FullName(); got != want {
32 panic(fmt.Sprintf("descriptor mismatch: %v != %v", got, want))
33 }
34 panic("descriptor mismatch")
35 }
36 mergeOptions{}.mergeMessage(dstMsg, srcMsg)
37}
38
39// Clone returns a deep copy of m.
40// If the top-level message is invalid, it returns an invalid message as well.
41func Clone(m Message) Message {
42 // NOTE: Most usages of Clone assume the following properties:
43 // t := reflect.TypeOf(m)
44 // t == reflect.TypeOf(m.ProtoReflect().New().Interface())
45 // t == reflect.TypeOf(m.ProtoReflect().Type().Zero().Interface())
46 //
47 // Embedding protobuf messages breaks this since the parent type will have
48 // a forwarded ProtoReflect method, but the Interface method will return
49 // the underlying embedded message type.
50 if m == nil {
51 return nil
52 }
53 src := m.ProtoReflect()
54 if !src.IsValid() {
55 return src.Type().Zero().Interface()
56 }
57 dst := src.New()
58 mergeOptions{}.mergeMessage(dst, src)
59 return dst.Interface()
60}
61
62// CloneOf returns a deep copy of m. If the top-level message is invalid,
63// it returns an invalid message as well.
64func CloneOf[M Message](m M) M {
65 return Clone(m).(M)
66}
67
68// mergeOptions provides a namespace for merge functions, and can be
69// exported in the future if we add user-visible merge options.
70type mergeOptions struct{}
71
72func (o mergeOptions) mergeMessage(dst, src protoreflect.Message) {
73 methods := protoMethods(dst)
74 if methods != nil && methods.Merge != nil {
75 in := protoiface.MergeInput{
76 Destination: dst,
77 Source: src,
78 }
79 out := methods.Merge(in)
80 if out.Flags&protoiface.MergeComplete != 0 {
81 return
82 }
83 }
84
85 if !dst.IsValid() {
86 panic(fmt.Sprintf("cannot merge into invalid %v message", dst.Descriptor().FullName()))
87 }
88
89 src.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
90 switch {
91 case fd.IsList():
92 o.mergeList(dst.Mutable(fd).List(), v.List(), fd)
93 case fd.IsMap():
94 o.mergeMap(dst.Mutable(fd).Map(), v.Map(), fd.MapValue())
95 case fd.Message() != nil:
96 o.mergeMessage(dst.Mutable(fd).Message(), v.Message())
97 case fd.Kind() == protoreflect.BytesKind:
98 dst.Set(fd, o.cloneBytes(v))
99 default:
100 dst.Set(fd, v)
101 }
102 return true
103 })
104
105 if len(src.GetUnknown()) > 0 {
106 dst.SetUnknown(append(dst.GetUnknown(), src.GetUnknown()...))
107 }
108}
109
110func (o mergeOptions) mergeList(dst, src protoreflect.List, fd protoreflect.FieldDescriptor) {
111 // Merge semantics appends to the end of the existing list.
112 for i, n := 0, src.Len(); i < n; i++ {
113 switch v := src.Get(i); {
114 case fd.Message() != nil:
115 dstv := dst.NewElement()
116 o.mergeMessage(dstv.Message(), v.Message())
117 dst.Append(dstv)
118 case fd.Kind() == protoreflect.BytesKind:
119 dst.Append(o.cloneBytes(v))
120 default:
121 dst.Append(v)
122 }
123 }
124}
125
126func (o mergeOptions) mergeMap(dst, src protoreflect.Map, fd protoreflect.FieldDescriptor) {
127 // Merge semantics replaces, rather than merges into existing entries.
128 src.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool {
129 switch {
130 case fd.Message() != nil:
131 dstv := dst.NewValue()
132 o.mergeMessage(dstv.Message(), v.Message())
133 dst.Set(k, dstv)
134 case fd.Kind() == protoreflect.BytesKind:
135 dst.Set(k, o.cloneBytes(v))
136 default:
137 dst.Set(k, v)
138 }
139 return true
140 })
141}
142
143func (o mergeOptions) cloneBytes(v protoreflect.Value) protoreflect.Value {
144 return protoreflect.ValueOfBytes(append([]byte{}, v.Bytes()...))
145}