message_set.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. // Go support for Protocol Buffers - Google's data interchange format
  2. //
  3. // Copyright 2010 The Go Authors. All rights reserved.
  4. // http://code.google.com/p/goprotobuf/
  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. "reflect"
  38. "sort"
  39. )
  40. // ErrNoMessageTypeId occurs when a protocol buffer does not have a message type ID.
  41. // A message type ID is required for storing a protocol buffer in a message set.
  42. var ErrNoMessageTypeId = errors.New("proto does not have a message type ID")
  43. // The first two types (_MessageSet_Item and MessageSet)
  44. // model what the protocol compiler produces for the following protocol message:
  45. // message MessageSet {
  46. // repeated group Item = 1 {
  47. // required int32 type_id = 2;
  48. // required string message = 3;
  49. // };
  50. // }
  51. // That is the MessageSet wire format. We can't use a proto to generate these
  52. // because that would introduce a circular dependency between it and this package.
  53. //
  54. // When a proto1 proto has a field that looks like:
  55. // optional message<MessageSet> info = 3;
  56. // the protocol compiler produces a field in the generated struct that looks like:
  57. // Info *_proto_.MessageSet `protobuf:"bytes,3,opt,name=info"`
  58. // The package is automatically inserted so there is no need for that proto file to
  59. // import this package.
  60. type _MessageSet_Item struct {
  61. TypeId *int32 `protobuf:"varint,2,req,name=type_id"`
  62. Message []byte `protobuf:"bytes,3,req,name=message"`
  63. }
  64. type MessageSet struct {
  65. Item []*_MessageSet_Item `protobuf:"group,1,rep"`
  66. XXX_unrecognized []byte
  67. // TODO: caching?
  68. }
  69. // Make sure MessageSet is a Message.
  70. var _ Message = (*MessageSet)(nil)
  71. // messageTypeIder is an interface satisfied by a protocol buffer type
  72. // that may be stored in a MessageSet.
  73. type messageTypeIder interface {
  74. MessageTypeId() int32
  75. }
  76. func (ms *MessageSet) find(pb Message) *_MessageSet_Item {
  77. mti, ok := pb.(messageTypeIder)
  78. if !ok {
  79. return nil
  80. }
  81. id := mti.MessageTypeId()
  82. for _, item := range ms.Item {
  83. if *item.TypeId == id {
  84. return item
  85. }
  86. }
  87. return nil
  88. }
  89. func (ms *MessageSet) Has(pb Message) bool {
  90. if ms.find(pb) != nil {
  91. return true
  92. }
  93. return false
  94. }
  95. func (ms *MessageSet) Unmarshal(pb Message) error {
  96. if item := ms.find(pb); item != nil {
  97. return Unmarshal(item.Message, pb)
  98. }
  99. if _, ok := pb.(messageTypeIder); !ok {
  100. return ErrNoMessageTypeId
  101. }
  102. return nil // TODO: return error instead?
  103. }
  104. func (ms *MessageSet) Marshal(pb Message) error {
  105. msg, err := Marshal(pb)
  106. if err != nil {
  107. return err
  108. }
  109. if item := ms.find(pb); item != nil {
  110. // reuse existing item
  111. item.Message = msg
  112. return nil
  113. }
  114. mti, ok := pb.(messageTypeIder)
  115. if !ok {
  116. return ErrWrongType // TODO: custom error?
  117. }
  118. mtid := mti.MessageTypeId()
  119. ms.Item = append(ms.Item, &_MessageSet_Item{
  120. TypeId: &mtid,
  121. Message: msg,
  122. })
  123. return nil
  124. }
  125. func (ms *MessageSet) Reset() { *ms = MessageSet{} }
  126. func (ms *MessageSet) String() string { return CompactTextString(ms) }
  127. func (*MessageSet) ProtoMessage() {}
  128. // Support for the message_set_wire_format message option.
  129. func skipVarint(buf []byte) []byte {
  130. i := 0
  131. for ; buf[i]&0x80 != 0; i++ {
  132. }
  133. return buf[i+1:]
  134. }
  135. // MarshalMessageSet encodes the extension map represented by m in the message set wire format.
  136. // It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option.
  137. func MarshalMessageSet(m map[int32]Extension) ([]byte, error) {
  138. if err := encodeExtensionMap(m); err != nil {
  139. return nil, err
  140. }
  141. // Sort extension IDs to provide a deterministic encoding.
  142. // See also enc_map in encode.go.
  143. ids := make([]int, 0, len(m))
  144. for id := range m {
  145. ids = append(ids, int(id))
  146. }
  147. sort.Ints(ids)
  148. ms := &MessageSet{Item: make([]*_MessageSet_Item, 0, len(m))}
  149. for _, id := range ids {
  150. e := m[int32(id)]
  151. // Remove the wire type and field number varint, as well as the length varint.
  152. msg := skipVarint(skipVarint(e.enc))
  153. ms.Item = append(ms.Item, &_MessageSet_Item{
  154. TypeId: Int32(int32(id)),
  155. Message: msg,
  156. })
  157. }
  158. return Marshal(ms)
  159. }
  160. // UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
  161. // It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
  162. func UnmarshalMessageSet(buf []byte, m map[int32]Extension) error {
  163. ms := new(MessageSet)
  164. if err := Unmarshal(buf, ms); err != nil {
  165. return err
  166. }
  167. for _, item := range ms.Item {
  168. // restore wire type and field number varint, plus length varint.
  169. b := EncodeVarint(uint64(*item.TypeId)<<3 | WireBytes)
  170. b = append(b, EncodeVarint(uint64(len(item.Message)))...)
  171. b = append(b, item.Message...)
  172. m[*item.TypeId] = Extension{enc: b}
  173. }
  174. return nil
  175. }
  176. // A global registry of types that can be used in a MessageSet.
  177. var messageSetMap = make(map[int32]messageSetDesc)
  178. type messageSetDesc struct {
  179. t reflect.Type // pointer to struct
  180. name string
  181. }
  182. // RegisterMessageSetType is called from the generated code.
  183. func RegisterMessageSetType(i messageTypeIder, name string) {
  184. messageSetMap[i.MessageTypeId()] = messageSetDesc{
  185. t: reflect.TypeOf(i),
  186. name: name,
  187. }
  188. }