5
0
mirror of https://github.com/cwinfo/matterbridge.git synced 2024-11-30 03:51:35 +00:00
matterbridge/vendor/github.com/golang/protobuf/proto/discard.go

59 lines
1.6 KiB
Go
Raw Normal View History

2020-08-09 22:29:54 +00:00
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
2019-02-21 19:28:13 +00:00
package proto
import (
2020-08-09 22:29:54 +00:00
"google.golang.org/protobuf/reflect/protoreflect"
2019-02-21 19:28:13 +00:00
)
// DiscardUnknown recursively discards all unknown fields from this message
// and all embedded messages.
//
// When unmarshaling a message with unrecognized fields, the tags and values
// of such fields are preserved in the Message. This allows a later call to
// marshal to be able to produce a message that continues to have those
// unrecognized fields. To avoid this, DiscardUnknown is used to
// explicitly clear the unknown fields after unmarshaling.
func DiscardUnknown(m Message) {
2020-08-09 22:29:54 +00:00
if m != nil {
discardUnknown(MessageReflect(m))
2019-02-21 19:28:13 +00:00
}
}
2020-08-09 22:29:54 +00:00
func discardUnknown(m protoreflect.Message) {
m.Range(func(fd protoreflect.FieldDescriptor, val protoreflect.Value) bool {
switch {
// Handle singular message.
case fd.Cardinality() != protoreflect.Repeated:
if fd.Message() != nil {
discardUnknown(m.Get(fd).Message())
2019-02-21 19:28:13 +00:00
}
2020-08-09 22:29:54 +00:00
// Handle list of messages.
case fd.IsList():
if fd.Message() != nil {
ls := m.Get(fd).List()
for i := 0; i < ls.Len(); i++ {
discardUnknown(ls.Get(i).Message())
2019-02-21 19:28:13 +00:00
}
}
2020-08-09 22:29:54 +00:00
// Handle map of messages.
case fd.IsMap():
if fd.MapValue().Message() != nil {
ms := m.Get(fd).Map()
ms.Range(func(_ protoreflect.MapKey, v protoreflect.Value) bool {
discardUnknown(v.Message())
return true
})
2019-02-21 19:28:13 +00:00
}
}
2020-08-09 22:29:54 +00:00
return true
})
2019-02-21 19:28:13 +00:00
2020-08-09 22:29:54 +00:00
// Discard unknown fields.
if len(m.GetUnknown()) > 0 {
m.SetUnknown(nil)
2019-02-21 19:28:13 +00:00
}
}