Skip to content

Commit 9255415

Browse files
authored
proto: add DiscardUnknown function (#498)
This copies the discardLegacy logic from the dev branch. The unit tests are located on the dev branch and will be merged into the master branch in the near future. This function is cherrypicked into master in order to support the master to dev transition.
1 parent c65a041 commit 9255415

File tree

1 file changed

+151
-0
lines changed

1 file changed

+151
-0
lines changed

proto/discard.go

+151
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
// Go support for Protocol Buffers - Google's data interchange format
2+
//
3+
// Copyright 2017 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+
package proto
33+
34+
import (
35+
"fmt"
36+
"reflect"
37+
"strings"
38+
)
39+
40+
// DiscardUnknown recursively discards all unknown fields from this message
41+
// and all embedded messages.
42+
//
43+
// When unmarshaling a message with unrecognized fields, the tags and values
44+
// of such fields are preserved in the Message. This allows a later call to
45+
// marshal to be able to produce a message that continues to have those
46+
// unrecognized fields. To avoid this, DiscardUnknown is used to
47+
// explicitly clear the unknown fields after unmarshaling.
48+
//
49+
// For proto2 messages, the unknown fields of message extensions are only
50+
// discarded from messages that have been accessed via GetExtension.
51+
func DiscardUnknown(m Message) {
52+
discardLegacy(m)
53+
}
54+
55+
func discardLegacy(m Message) {
56+
v := reflect.ValueOf(m)
57+
if v.Kind() != reflect.Ptr || v.IsNil() {
58+
return
59+
}
60+
v = v.Elem()
61+
if v.Kind() != reflect.Struct {
62+
return
63+
}
64+
t := v.Type()
65+
66+
for i := 0; i < v.NumField(); i++ {
67+
f := t.Field(i)
68+
if strings.HasPrefix(f.Name, "XXX_") {
69+
continue
70+
}
71+
vf := v.Field(i)
72+
tf := f.Type
73+
74+
// Unwrap tf to get its most basic type.
75+
var isPointer, isSlice bool
76+
if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
77+
isSlice = true
78+
tf = tf.Elem()
79+
}
80+
if tf.Kind() == reflect.Ptr {
81+
isPointer = true
82+
tf = tf.Elem()
83+
}
84+
if isPointer && isSlice && tf.Kind() != reflect.Struct {
85+
panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name))
86+
}
87+
88+
switch tf.Kind() {
89+
case reflect.Struct:
90+
switch {
91+
case !isPointer:
92+
panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name))
93+
case isSlice: // E.g., []*pb.T
94+
for j := 0; j < vf.Len(); j++ {
95+
discardLegacy(vf.Index(j).Interface().(Message))
96+
}
97+
default: // E.g., *pb.T
98+
discardLegacy(vf.Interface().(Message))
99+
}
100+
case reflect.Map:
101+
switch {
102+
case isPointer || isSlice:
103+
panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name))
104+
default: // E.g., map[K]V
105+
tv := vf.Type().Elem()
106+
if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T)
107+
for _, key := range vf.MapKeys() {
108+
val := vf.MapIndex(key)
109+
discardLegacy(val.Interface().(Message))
110+
}
111+
}
112+
}
113+
case reflect.Interface:
114+
// Must be oneof field.
115+
switch {
116+
case isPointer || isSlice:
117+
panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name))
118+
default: // E.g., test_proto.isCommunique_Union interface
119+
if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" {
120+
vf = vf.Elem() // E.g., *test_proto.Communique_Msg
121+
if !vf.IsNil() {
122+
vf = vf.Elem() // E.g., test_proto.Communique_Msg
123+
vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value
124+
if vf.Kind() == reflect.Ptr {
125+
discardLegacy(vf.Interface().(Message))
126+
}
127+
}
128+
}
129+
}
130+
}
131+
}
132+
133+
if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() {
134+
if vf.Type() != reflect.TypeOf([]byte{}) {
135+
panic("expected XXX_unrecognized to be of type []byte")
136+
}
137+
vf.Set(reflect.ValueOf([]byte(nil)))
138+
}
139+
140+
// For proto2 messages, only discard unknown fields in message extensions
141+
// that have been accessed via GetExtension.
142+
if em, ok := extendable(m); ok {
143+
// Ignore lock since discardLegacy is not concurrency safe.
144+
emm, _ := em.extensionsRead()
145+
for _, mx := range emm {
146+
if m, ok := mx.value.(Message); ok {
147+
discardLegacy(m)
148+
}
149+
}
150+
}
151+
}

0 commit comments

Comments
 (0)