discard.go 5.0 KB

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