blob: 9d912bce19bb61f69634b9eb8ea64f69f9ddde63 [file] [log] [blame]
David Symonds4fee3b12010-11-11 10:00:13 +11001// Go support for Protocol Buffers - Google's data interchange format
2//
David Symondsee6e9c52012-11-29 08:51:07 +11003// Copyright 2010 The Go Authors. All rights reserved.
David Symonds558f13f2014-11-24 10:28:53 +11004// https://github.com/golang/protobuf
David Symonds4fee3b12010-11-11 10:00:13 +11005//
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
32package proto
33
34/*
35 * Support for message sets.
36 */
37
38import (
David Symonds19227ff2014-10-12 16:35:09 +110039 "bytes"
40 "encoding/json"
Rob Pikea17fdd92011-11-02 12:43:05 -070041 "errors"
David Symonds19227ff2014-10-12 16:35:09 +110042 "fmt"
David Symonds1d72f7a2011-08-19 18:28:52 +100043 "reflect"
David Symonds0c1184e2013-06-08 15:42:12 +100044 "sort"
David Symonds4fee3b12010-11-11 10:00:13 +110045)
46
47// ErrNoMessageTypeId occurs when a protocol buffer does not have a message type ID.
48// A message type ID is required for storing a protocol buffer in a message set.
Rob Pikea17fdd92011-11-02 12:43:05 -070049var ErrNoMessageTypeId = errors.New("proto does not have a message type ID")
David Symonds4fee3b12010-11-11 10:00:13 +110050
51// The first two types (_MessageSet_Item and MessageSet)
52// model what the protocol compiler produces for the following protocol message:
53// message MessageSet {
54// repeated group Item = 1 {
55// required int32 type_id = 2;
56// required string message = 3;
57// };
58// }
59// That is the MessageSet wire format. We can't use a proto to generate these
60// because that would introduce a circular dependency between it and this package.
61//
62// When a proto1 proto has a field that looks like:
63// optional message<MessageSet> info = 3;
64// the protocol compiler produces a field in the generated struct that looks like:
David Symonds8935abf2011-07-04 15:53:16 +100065// Info *_proto_.MessageSet `protobuf:"bytes,3,opt,name=info"`
David Symonds4fee3b12010-11-11 10:00:13 +110066// The package is automatically inserted so there is no need for that proto file to
67// import this package.
68
69type _MessageSet_Item struct {
David Symonds8935abf2011-07-04 15:53:16 +100070 TypeId *int32 `protobuf:"varint,2,req,name=type_id"`
71 Message []byte `protobuf:"bytes,3,req,name=message"`
David Symonds4fee3b12010-11-11 10:00:13 +110072}
73
74type MessageSet struct {
David Symonds8935abf2011-07-04 15:53:16 +100075 Item []*_MessageSet_Item `protobuf:"group,1,rep"`
David Symonds10c93ba2012-08-04 16:38:08 +100076 XXX_unrecognized []byte
David Symonds4fee3b12010-11-11 10:00:13 +110077 // TODO: caching?
78}
79
David Symonds9f60f432012-06-14 09:45:25 +100080// Make sure MessageSet is a Message.
81var _ Message = (*MessageSet)(nil)
82
David Symonds4fee3b12010-11-11 10:00:13 +110083// messageTypeIder is an interface satisfied by a protocol buffer type
84// that may be stored in a MessageSet.
85type messageTypeIder interface {
86 MessageTypeId() int32
87}
88
David Symonds9f60f432012-06-14 09:45:25 +100089func (ms *MessageSet) find(pb Message) *_MessageSet_Item {
David Symonds4fee3b12010-11-11 10:00:13 +110090 mti, ok := pb.(messageTypeIder)
91 if !ok {
92 return nil
93 }
94 id := mti.MessageTypeId()
95 for _, item := range ms.Item {
96 if *item.TypeId == id {
97 return item
98 }
99 }
100 return nil
101}
102
David Symonds9f60f432012-06-14 09:45:25 +1000103func (ms *MessageSet) Has(pb Message) bool {
David Symonds4fee3b12010-11-11 10:00:13 +1100104 if ms.find(pb) != nil {
105 return true
106 }
107 return false
108}
109
David Symonds9f60f432012-06-14 09:45:25 +1000110func (ms *MessageSet) Unmarshal(pb Message) error {
David Symonds4fee3b12010-11-11 10:00:13 +1100111 if item := ms.find(pb); item != nil {
112 return Unmarshal(item.Message, pb)
113 }
114 if _, ok := pb.(messageTypeIder); !ok {
115 return ErrNoMessageTypeId
116 }
117 return nil // TODO: return error instead?
118}
119
David Symonds9f60f432012-06-14 09:45:25 +1000120func (ms *MessageSet) Marshal(pb Message) error {
David Symonds4fee3b12010-11-11 10:00:13 +1100121 msg, err := Marshal(pb)
122 if err != nil {
123 return err
124 }
125 if item := ms.find(pb); item != nil {
126 // reuse existing item
127 item.Message = msg
128 return nil
129 }
130
131 mti, ok := pb.(messageTypeIder)
132 if !ok {
David Symondsbaeae8b2014-06-23 09:41:27 +1000133 return ErrNoMessageTypeId
David Symonds4fee3b12010-11-11 10:00:13 +1100134 }
135
136 mtid := mti.MessageTypeId()
137 ms.Item = append(ms.Item, &_MessageSet_Item{
138 TypeId: &mtid,
139 Message: msg,
140 })
141 return nil
142}
143
David Symonds9f60f432012-06-14 09:45:25 +1000144func (ms *MessageSet) Reset() { *ms = MessageSet{} }
145func (ms *MessageSet) String() string { return CompactTextString(ms) }
146func (*MessageSet) ProtoMessage() {}
147
David Symonds4fee3b12010-11-11 10:00:13 +1100148// Support for the message_set_wire_format message option.
149
150func skipVarint(buf []byte) []byte {
151 i := 0
152 for ; buf[i]&0x80 != 0; i++ {
153 }
154 return buf[i+1:]
155}
156
157// MarshalMessageSet encodes the extension map represented by m in the message set wire format.
158// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option.
Rob Pikea17fdd92011-11-02 12:43:05 -0700159func MarshalMessageSet(m map[int32]Extension) ([]byte, error) {
David Symonds1d72f7a2011-08-19 18:28:52 +1000160 if err := encodeExtensionMap(m); err != nil {
161 return nil, err
162 }
163
David Symonds0c1184e2013-06-08 15:42:12 +1000164 // Sort extension IDs to provide a deterministic encoding.
165 // See also enc_map in encode.go.
166 ids := make([]int, 0, len(m))
167 for id := range m {
168 ids = append(ids, int(id))
169 }
170 sort.Ints(ids)
171
172 ms := &MessageSet{Item: make([]*_MessageSet_Item, 0, len(m))}
173 for _, id := range ids {
174 e := m[int32(id)]
David Symonds4fee3b12010-11-11 10:00:13 +1100175 // Remove the wire type and field number varint, as well as the length varint.
David Symonds1d72f7a2011-08-19 18:28:52 +1000176 msg := skipVarint(skipVarint(e.enc))
David Symonds4fee3b12010-11-11 10:00:13 +1100177
David Symonds0c1184e2013-06-08 15:42:12 +1000178 ms.Item = append(ms.Item, &_MessageSet_Item{
179 TypeId: Int32(int32(id)),
David Symonds1d72f7a2011-08-19 18:28:52 +1000180 Message: msg,
David Symonds0c1184e2013-06-08 15:42:12 +1000181 })
David Symonds4fee3b12010-11-11 10:00:13 +1100182 }
183 return Marshal(ms)
184}
185
186// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
187// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
Rob Pikea17fdd92011-11-02 12:43:05 -0700188func UnmarshalMessageSet(buf []byte, m map[int32]Extension) error {
David Symonds4fee3b12010-11-11 10:00:13 +1100189 ms := new(MessageSet)
190 if err := Unmarshal(buf, ms); err != nil {
191 return err
192 }
193 for _, item := range ms.Item {
David Symonds25535e32014-07-30 09:23:20 +1000194 id := *item.TypeId
195 msg := item.Message
David Symonds4fee3b12010-11-11 10:00:13 +1100196
David Symonds25535e32014-07-30 09:23:20 +1000197 // Restore wire type and field number varint, plus length varint.
198 // Be careful to preserve duplicate items.
199 b := EncodeVarint(uint64(id)<<3 | WireBytes)
200 if ext, ok := m[id]; ok {
201 // Existing data; rip off the tag and length varint
202 // so we join the new data correctly.
203 // We can assume that ext.enc is set because we are unmarshaling.
204 o := ext.enc[len(b):] // skip wire type and field number
205 _, n := DecodeVarint(o) // calculate length of length varint
206 o = o[n:] // skip length varint
207 msg = append(o, msg...) // join old data and new data
208 }
209 b = append(b, EncodeVarint(uint64(len(msg)))...)
210 b = append(b, msg...)
211
212 m[id] = Extension{enc: b}
David Symonds4fee3b12010-11-11 10:00:13 +1100213 }
214 return nil
215}
David Symonds1d72f7a2011-08-19 18:28:52 +1000216
David Symonds19227ff2014-10-12 16:35:09 +1100217// MarshalMessageSetJSON encodes the extension map represented by m in JSON format.
218// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
219func MarshalMessageSetJSON(m map[int32]Extension) ([]byte, error) {
220 var b bytes.Buffer
221 b.WriteByte('{')
222
223 // Process the map in key order for deterministic output.
224 ids := make([]int32, 0, len(m))
225 for id := range m {
226 ids = append(ids, id)
227 }
228 sort.Sort(int32Slice(ids)) // int32Slice defined in text.go
229
230 for i, id := range ids {
231 ext := m[id]
232 if i > 0 {
233 b.WriteByte(',')
234 }
235
236 msd, ok := messageSetMap[id]
237 if !ok {
238 // Unknown type; we can't render it, so skip it.
239 continue
240 }
241 fmt.Fprintf(&b, `"[%s]":`, msd.name)
242
243 x := ext.value
244 if x == nil {
245 x = reflect.New(msd.t.Elem()).Interface()
246 if err := Unmarshal(ext.enc, x.(Message)); err != nil {
247 return nil, err
248 }
249 }
250 d, err := json.Marshal(x)
251 if err != nil {
252 return nil, err
253 }
254 b.Write(d)
255 }
256 b.WriteByte('}')
257 return b.Bytes(), nil
258}
259
260// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format.
261// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
262func UnmarshalMessageSetJSON(buf []byte, m map[int32]Extension) error {
263 // Common-case fast path.
264 if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) {
265 return nil
266 }
267
268 // This is fairly tricky, and it's not clear that it is needed.
269 return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented")
270}
271
David Symonds1d72f7a2011-08-19 18:28:52 +1000272// A global registry of types that can be used in a MessageSet.
273
274var messageSetMap = make(map[int32]messageSetDesc)
275
276type messageSetDesc struct {
277 t reflect.Type // pointer to struct
278 name string
279}
280
281// RegisterMessageSetType is called from the generated code.
David Symonds19227ff2014-10-12 16:35:09 +1100282func RegisterMessageSetType(m Message, fieldNum int32, name string) {
283 messageSetMap[fieldNum] = messageSetDesc{
284 t: reflect.TypeOf(m),
David Symonds1d72f7a2011-08-19 18:28:52 +1000285 name: name,
286 }
287}