messageset.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. // Package messageset encodes and decodes the obsolete MessageSet wire format.
  5. package messageset
  6. import (
  7. "google.golang.org/protobuf/internal/encoding/wire"
  8. "google.golang.org/protobuf/internal/errors"
  9. pref "google.golang.org/protobuf/reflect/protoreflect"
  10. preg "google.golang.org/protobuf/reflect/protoregistry"
  11. )
  12. // The MessageSet wire format is equivalent to a message defiend as follows,
  13. // where each Item defines an extension field with a field number of 'type_id'
  14. // and content of 'message'. MessageSet extensions must be non-repeated message
  15. // fields.
  16. //
  17. // message MessageSet {
  18. // repeated group Item = 1 {
  19. // required int32 type_id = 2;
  20. // required string message = 3;
  21. // }
  22. // }
  23. const (
  24. FieldItem = wire.Number(1)
  25. FieldTypeID = wire.Number(2)
  26. FieldMessage = wire.Number(3)
  27. )
  28. // ExtensionName is the field name for extensions of MessageSet.
  29. //
  30. // A valid MessageSet extension must be of the form:
  31. // message MyMessage {
  32. // extend proto2.bridge.MessageSet {
  33. // optional MyMessage message_set_extension = 1234;
  34. // }
  35. // ...
  36. // }
  37. const ExtensionName = "message_set_extension"
  38. // IsMessageSet returns whether the message uses the MessageSet wire format.
  39. func IsMessageSet(md pref.MessageDescriptor) bool {
  40. xmd, ok := md.(interface{ IsMessageSet() bool })
  41. return ok && xmd.IsMessageSet()
  42. }
  43. // IsMessageSetExtension reports this field extends a MessageSet.
  44. func IsMessageSetExtension(fd pref.FieldDescriptor) bool {
  45. if fd.Name() != ExtensionName {
  46. return false
  47. }
  48. if fd.FullName().Parent() != fd.Message().FullName() {
  49. return false
  50. }
  51. return IsMessageSet(fd.ContainingMessage())
  52. }
  53. // FindMessageSetExtension locates a MessageSet extension field by name.
  54. // In text and JSON formats, the extension name used is the message itself.
  55. // The extension field name is derived by appending ExtensionName.
  56. func FindMessageSetExtension(r preg.ExtensionTypeResolver, s pref.FullName) (pref.ExtensionType, error) {
  57. xt, err := r.FindExtensionByName(s.Append(ExtensionName))
  58. if err != nil {
  59. return nil, err
  60. }
  61. if !IsMessageSetExtension(xt.TypeDescriptor()) {
  62. return nil, preg.NotFound
  63. }
  64. return xt, nil
  65. }
  66. // SizeField returns the size of a MessageSet item field containing an extension
  67. // with the given field number, not counting the contents of the message subfield.
  68. func SizeField(num wire.Number) int {
  69. return 2*wire.SizeTag(FieldItem) + wire.SizeTag(FieldTypeID) + wire.SizeVarint(uint64(num))
  70. }
  71. // ConsumeField parses a MessageSet item field and returns the contents of the
  72. // type_id and message subfields and the total item length.
  73. func ConsumeField(b []byte) (typeid wire.Number, message []byte, n int, err error) {
  74. num, wtyp, n := wire.ConsumeTag(b)
  75. if n < 0 {
  76. return 0, nil, 0, wire.ParseError(n)
  77. }
  78. if num != FieldItem || wtyp != wire.StartGroupType {
  79. return 0, nil, 0, errors.New("invalid MessageSet field number")
  80. }
  81. typeid, message, fieldLen, err := ConsumeFieldValue(b[n:], false)
  82. if err != nil {
  83. return 0, nil, 0, err
  84. }
  85. return typeid, message, n + fieldLen, nil
  86. }
  87. // ConsumeFieldValue parses b as a MessageSet item field value until and including
  88. // the trailing end group marker. It assumes the start group tag has already been parsed.
  89. // It returns the contents of the type_id and message subfields and the total
  90. // item length.
  91. //
  92. // If wantLen is true, the returned message value includes the length prefix.
  93. // This is ugly, but simplifies the fast-path decoder in internal/impl.
  94. func ConsumeFieldValue(b []byte, wantLen bool) (typeid wire.Number, message []byte, n int, err error) {
  95. ilen := len(b)
  96. for {
  97. num, wtyp, n := wire.ConsumeTag(b)
  98. if n < 0 {
  99. return 0, nil, 0, wire.ParseError(n)
  100. }
  101. b = b[n:]
  102. switch {
  103. case num == FieldItem && wtyp == wire.EndGroupType:
  104. if wantLen && len(message) == 0 {
  105. // The message field was missing, which should never happen.
  106. // Be prepared for this case anyway.
  107. message = wire.AppendVarint(message, 0)
  108. }
  109. return typeid, message, ilen - len(b), nil
  110. case num == FieldTypeID && wtyp == wire.VarintType:
  111. v, n := wire.ConsumeVarint(b)
  112. if n < 0 {
  113. return 0, nil, 0, wire.ParseError(n)
  114. }
  115. b = b[n:]
  116. typeid = wire.Number(v)
  117. case num == FieldMessage && wtyp == wire.BytesType:
  118. m, n := wire.ConsumeBytes(b)
  119. if n < 0 {
  120. return 0, nil, 0, wire.ParseError(n)
  121. }
  122. if message == nil {
  123. if wantLen {
  124. message = b[:n]
  125. } else {
  126. message = m
  127. }
  128. } else {
  129. // This case should never happen in practice, but handle it for
  130. // correctness: The MessageSet item contains multiple message
  131. // fields, which need to be merged.
  132. //
  133. // In the case where we're returning the length, this becomes
  134. // quite inefficient since we need to strip the length off
  135. // the existing data and reconstruct it with the combined length.
  136. if wantLen {
  137. _, nn := wire.ConsumeVarint(message)
  138. m0 := message[nn:]
  139. message = message[:0]
  140. message = wire.AppendVarint(message, uint64(len(m0)+len(m)))
  141. message = append(message, m0...)
  142. message = append(message, m...)
  143. } else {
  144. message = append(message, m...)
  145. }
  146. }
  147. b = b[n:]
  148. }
  149. }
  150. }
  151. // AppendFieldStart appends the start of a MessageSet item field containing
  152. // an extension with the given number. The caller must add the message
  153. // subfield (including the tag).
  154. func AppendFieldStart(b []byte, num wire.Number) []byte {
  155. b = wire.AppendTag(b, FieldItem, wire.StartGroupType)
  156. b = wire.AppendTag(b, FieldTypeID, wire.VarintType)
  157. b = wire.AppendVarint(b, uint64(num))
  158. return b
  159. }
  160. // AppendFieldEnd appends the trailing end group marker for a MessageSet item field.
  161. func AppendFieldEnd(b []byte) []byte {
  162. return wire.AppendTag(b, FieldItem, wire.EndGroupType)
  163. }