You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

181 lines
5.5 KiB

  1. // Go support for Protocol Buffers - Google's data interchange format
  2. //
  3. // Copyright 2010 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. /*
  33. * Support for message sets.
  34. */
  35. import (
  36. "errors"
  37. )
  38. // errNoMessageTypeID occurs when a protocol buffer does not have a message type ID.
  39. // A message type ID is required for storing a protocol buffer in a message set.
  40. var errNoMessageTypeID = errors.New("proto does not have a message type ID")
  41. // The first two types (_MessageSet_Item and messageSet)
  42. // model what the protocol compiler produces for the following protocol message:
  43. // message MessageSet {
  44. // repeated group Item = 1 {
  45. // required int32 type_id = 2;
  46. // required string message = 3;
  47. // };
  48. // }
  49. // That is the MessageSet wire format. We can't use a proto to generate these
  50. // because that would introduce a circular dependency between it and this package.
  51. type _MessageSet_Item struct {
  52. TypeId *int32 `protobuf:"varint,2,req,name=type_id"`
  53. Message []byte `protobuf:"bytes,3,req,name=message"`
  54. }
  55. type messageSet struct {
  56. Item []*_MessageSet_Item `protobuf:"group,1,rep"`
  57. XXX_unrecognized []byte
  58. // TODO: caching?
  59. }
  60. // Make sure messageSet is a Message.
  61. var _ Message = (*messageSet)(nil)
  62. // messageTypeIder is an interface satisfied by a protocol buffer type
  63. // that may be stored in a MessageSet.
  64. type messageTypeIder interface {
  65. MessageTypeId() int32
  66. }
  67. func (ms *messageSet) find(pb Message) *_MessageSet_Item {
  68. mti, ok := pb.(messageTypeIder)
  69. if !ok {
  70. return nil
  71. }
  72. id := mti.MessageTypeId()
  73. for _, item := range ms.Item {
  74. if *item.TypeId == id {
  75. return item
  76. }
  77. }
  78. return nil
  79. }
  80. func (ms *messageSet) Has(pb Message) bool {
  81. return ms.find(pb) != nil
  82. }
  83. func (ms *messageSet) Unmarshal(pb Message) error {
  84. if item := ms.find(pb); item != nil {
  85. return Unmarshal(item.Message, pb)
  86. }
  87. if _, ok := pb.(messageTypeIder); !ok {
  88. return errNoMessageTypeID
  89. }
  90. return nil // TODO: return error instead?
  91. }
  92. func (ms *messageSet) Marshal(pb Message) error {
  93. msg, err := Marshal(pb)
  94. if err != nil {
  95. return err
  96. }
  97. if item := ms.find(pb); item != nil {
  98. // reuse existing item
  99. item.Message = msg
  100. return nil
  101. }
  102. mti, ok := pb.(messageTypeIder)
  103. if !ok {
  104. return errNoMessageTypeID
  105. }
  106. mtid := mti.MessageTypeId()
  107. ms.Item = append(ms.Item, &_MessageSet_Item{
  108. TypeId: &mtid,
  109. Message: msg,
  110. })
  111. return nil
  112. }
  113. func (ms *messageSet) Reset() { *ms = messageSet{} }
  114. func (ms *messageSet) String() string { return CompactTextString(ms) }
  115. func (*messageSet) ProtoMessage() {}
  116. // Support for the message_set_wire_format message option.
  117. func skipVarint(buf []byte) []byte {
  118. i := 0
  119. for ; buf[i]&0x80 != 0; i++ {
  120. }
  121. return buf[i+1:]
  122. }
  123. // unmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
  124. // It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
  125. func unmarshalMessageSet(buf []byte, exts interface{}) error {
  126. var m map[int32]Extension
  127. switch exts := exts.(type) {
  128. case *XXX_InternalExtensions:
  129. m = exts.extensionsWrite()
  130. case map[int32]Extension:
  131. m = exts
  132. default:
  133. return errors.New("proto: not an extension map")
  134. }
  135. ms := new(messageSet)
  136. if err := Unmarshal(buf, ms); err != nil {
  137. return err
  138. }
  139. for _, item := range ms.Item {
  140. id := *item.TypeId
  141. msg := item.Message
  142. // Restore wire type and field number varint, plus length varint.
  143. // Be careful to preserve duplicate items.
  144. b := EncodeVarint(uint64(id)<<3 | WireBytes)
  145. if ext, ok := m[id]; ok {
  146. // Existing data; rip off the tag and length varint
  147. // so we join the new data correctly.
  148. // We can assume that ext.enc is set because we are unmarshaling.
  149. o := ext.enc[len(b):] // skip wire type and field number
  150. _, n := DecodeVarint(o) // calculate length of length varint
  151. o = o[n:] // skip length varint
  152. msg = append(o, msg...) // join old data and new data
  153. }
  154. b = append(b, EncodeVarint(uint64(len(msg)))...)
  155. b = append(b, msg...)
  156. m[id] = Extension{enc: b}
  157. }
  158. return nil
  159. }